Skip to content

Commit

Permalink
less allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
mmsqe committed Dec 5, 2022
1 parent 5085b1f commit 7e0c55d
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions versiondb/tmdb/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,58 +34,59 @@ func NewStore(plainDB, historyDB, changesetDB dbm.DB) *Store {

// PutAtVersion implements VersionStore interface
// TODO reduce allocation within iterations.
func (s *Store) PutAtVersion(version int64, changeSet []types.StoreKVPair) error {
func (s *Store) PutAtVersion(version int64, changeSet []types.StoreKVPair) (err error) {
plainBatch := s.plainDB.NewBatch()
defer plainBatch.Close()
historyBatch := s.historyDB.NewBatch()
defer historyBatch.Close()
changesetBatch := s.changesetDB.NewBatch()
defer changesetBatch.Close()

var key, original []byte
for _, pair := range changeSet {
key := prependStoreKey(pair.StoreKey, pair.Key)
key = prependStoreKey(pair.StoreKey, pair.Key)

if version == 0 {
// genesis state is written into plain state directly
if pair.Delete {
return errors.New("can't delete at genesis")
}
if err := plainBatch.Set(key, pair.Value); err != nil {
return err
if err = plainBatch.Set(key, pair.Value); err != nil {
return
}
continue
}

original, err := s.plainDB.Get(key)
original, err = s.plainDB.Get(key)
if err != nil {
return err
return
}
if bytes.Equal(original, pair.Value) {
// do nothing if the value is not changed
continue
}

// write history index
if err := WriteHistoryIndex(s.historyDB, historyBatch, key, uint64(version)); err != nil {
return err
if err = WriteHistoryIndex(s.historyDB, historyBatch, key, uint64(version)); err != nil {
return
}

// write the old value to changeset
if len(original) > 0 {
changesetKey := append(sdk.Uint64ToBigEndian(uint64(version)), key...)
if err := changesetBatch.Set(changesetKey, original); err != nil {
return err
if err = changesetBatch.Set(changesetKey, original); err != nil {
return
}
}

// write the new value to plain state
if pair.Delete {
if err := plainBatch.Delete(key); err != nil {
return err
if err = plainBatch.Delete(key); err != nil {
return
}
} else {
if err := plainBatch.Set(key, pair.Value); err != nil {
return err
if err = plainBatch.Set(key, pair.Value); err != nil {
return
}
}
}
Expand Down

0 comments on commit 7e0c55d

Please sign in to comment.