Skip to content

Commit

Permalink
reuse encoder in DB
Browse files Browse the repository at this point in the history
  • Loading branch information
chris124567 committed Aug 6, 2023
1 parent 6ffb348 commit f56dcb7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
26 changes: 16 additions & 10 deletions chain/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ func (b *dbBucket) putRaw(key, value []byte) {

func (b *dbBucket) put(key []byte, v types.EncoderTo) {
var buf bytes.Buffer
e := types.NewEncoder(&buf)
v.EncodeTo(e)
e.Flush()
b.db.enc.Reset(&buf)
v.EncodeTo(b.db.enc)
b.db.enc.Flush()
b.putRaw(key, buf.Bytes())
}

Expand All @@ -205,6 +205,8 @@ type DBStore struct {

unflushed int
lastFlush time.Time

enc *types.Encoder
}

func (db *DBStore) bucket(name []byte) *dbBucket {
Expand Down Expand Up @@ -326,15 +328,15 @@ func (db *DBStore) putDelayedSiacoinOutputs(dscods []consensus.DelayedSiacoinOut
b := db.bucket(bSiacoinOutputs)
key := db.encHeight(maturityHeight)
var buf bytes.Buffer
e := types.NewEncoder(&buf)
b.db.enc.Reset(&buf)
for _, dscod := range dscods {
if dscod.MaturityHeight != maturityHeight {
check(errors.New("mismatched maturity heights"))
return
}
dscod.EncodeTo(e)
dscod.EncodeTo(b.db.enc)
}
e.Flush()
b.db.enc.Flush()
b.putRaw(key, append(b.getRaw(key), buf.Bytes()[:]...))
}

Expand All @@ -352,18 +354,18 @@ func (db *DBStore) deleteDelayedSiacoinOutputs(dscods []consensus.DelayedSiacoin
toDelete[dscod.ID] = struct{}{}
}
var buf bytes.Buffer
e := types.NewEncoder(&buf)
db.enc.Reset(&buf)
for _, mdscod := range db.MaturedSiacoinOutputs(maturityHeight) {
if _, ok := toDelete[mdscod.ID]; !ok {
mdscod.EncodeTo(e)
mdscod.EncodeTo(db.enc)
}
delete(toDelete, mdscod.ID)
}
if len(toDelete) != 0 {
check(errors.New("missing delayed siacoin output(s)"))
return
}
e.Flush()
db.enc.Flush()
db.bucket(bSiacoinOutputs).putRaw(db.encHeight(maturityHeight), buf.Bytes())
}

Expand Down Expand Up @@ -623,7 +625,11 @@ func NewDBStore(db DB, n *consensus.Network, genesisBlock types.Block) (_ *DBSto
return nil, Checkpoint{}, errors.New("detected siad database, refusing to proceed")
}

dbs := &DBStore{db: db, n: n}
dbs := &DBStore{
db: db,
n: n,
enc: &types.Encoder{},
}

// if the db is empty, initialize it; otherwise, check that the genesis
// block is correct
Expand Down
8 changes: 8 additions & 0 deletions types/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ func (e *Encoder) WriteString(s string) {
e.WriteBytes([]byte(s))
}

// Reset resets the Encoder to write to w. Any unflushed data, along with any
// error previously encountered, is discarded.
func (e *Encoder) Reset(w io.Writer) {
e.w = w
e.n = 0
e.err = nil
}

// NewEncoder returns an Encoder that wraps the provided stream.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
Expand Down

0 comments on commit f56dcb7

Please sign in to comment.