Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize memory #75

Draft
wants to merge 16 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
convert: use unsafe string <-> []byte conversions
  • Loading branch information
johningve committed Aug 22, 2022
commit 6559ef4dd44a7b8a0214dad4fd86cc7b59627185
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))
}