github.com/aergoio/aergo@v1.3.1/state/statedata.go (about) 1 package state 2 3 import ( 4 "bytes" 5 "encoding/gob" 6 7 "github.com/aergoio/aergo-lib/db" 8 "github.com/aergoio/aergo/types" 9 "github.com/golang/protobuf/proto" 10 ) 11 12 func saveData(store db.DB, key []byte, data interface{}) error { 13 if key == nil { 14 return errSaveData 15 } 16 var err error 17 var raw []byte 18 switch data.(type) { 19 case *[]byte: 20 raw = *(data.(*[]byte)) 21 case proto.Message: 22 raw, err = proto.Marshal(data.(proto.Message)) 23 if err != nil { 24 return err 25 } 26 default: 27 buffer := &bytes.Buffer{} 28 enc := gob.NewEncoder(buffer) 29 err = enc.Encode(data) 30 if err != nil { 31 return err 32 } 33 raw = buffer.Bytes() 34 if err != nil { 35 return err 36 } 37 } 38 store.Set(key, raw) 39 return nil 40 } 41 42 func loadData(store db.DB, key []byte, data interface{}) error { 43 if key == nil { 44 return errLoadData 45 } 46 raw := store.Get(key) 47 48 if len(raw) == 0 { 49 return nil 50 } 51 var err error 52 switch data.(type) { 53 case *[]byte: 54 *(data).(*[]byte) = raw 55 case proto.Message: 56 err = proto.Unmarshal(raw, data.(proto.Message)) 57 default: 58 reader := bytes.NewReader(raw) 59 dec := gob.NewDecoder(reader) 60 err = dec.Decode(data) 61 } 62 return err 63 } 64 65 func (states *StateDB) loadStateData(key []byte) (*types.State, error) { 66 if len(key) == 0 { 67 return nil, errLoadStateData 68 } 69 data := &types.State{} 70 if err := loadData(states.store, key, data); err != nil { 71 return nil, err 72 } 73 return data, nil 74 }