Skip to content

Commit

Permalink
convert: use unsafe string <-> []byte conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
johningve committed Aug 19, 2022
1 parent 024c4c2 commit c8c68f0
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions internal/proto/hotstuffpb/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package hotstuffpb

import (
"math/big"
"reflect"
"unsafe"

"github.com/relab/hotstuff"
"github.com/relab/hotstuff/crypto"
Expand Down Expand Up @@ -116,7 +118,7 @@ func BlockToProto(block *hotstuff.Block) *Block {
parentHash := block.Parent()
return &Block{
Parent: parentHash[:],
Command: []byte(block.Command()),
Command: unsafeStringToBytes(block.Command()),
QC: QuorumCertToProto(block.QuorumCert()),
View: uint64(block.View()),
Proposer: uint32(block.Proposer()),
Expand All @@ -130,7 +132,7 @@ func BlockFromProto(block *Block) *hotstuff.Block {
return hotstuff.NewBlock(
p,
QuorumCertFromProto(block.GetQC()),
hotstuff.Command(block.GetCommand()),
unsafeBytesToString(block.GetCommand()),
hotstuff.View(block.GetView()),
hotstuff.ID(block.GetProposer()),
)
Expand Down Expand Up @@ -222,3 +224,18 @@ func SyncInfoToProto(syncInfo hotstuff.SyncInfo) *SyncInfo {
}
return m
}

func unsafeStringToBytes(s string) []byte {
if s == "" {
return []byte{}
}
const max = 0x7fff0000
if len(s) > max {
panic("string too long")
}
return (*[max]byte)(unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data))[:len(s):len(s)]
}

func unsafeBytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

0 comments on commit c8c68f0

Please sign in to comment.