go-vise

Constrained Size Output Virtual Machine
Info | Log | Files | Refs | README | LICENSE

fs.go (1955B)


      1 package persist
      2 
      3 import (
      4 	"io/ioutil"
      5 	"path"
      6 	"path/filepath"
      7 	"github.com/fxamacker/cbor/v2"
      8 
      9 	"git.defalsify.org/vise.git/cache"
     10 	"git.defalsify.org/vise.git/state"
     11 )
     12 
     13 // FsPersister is an implementation of Persister that saves state to the file system.
     14 type FsPersister struct {
     15 	State *state.State
     16 	Memory *cache.Cache
     17 	dir string
     18 }
     19 
     20 // NewFsPersister creates a new FsPersister.
     21 //
     22 // The filesystem store will be at the given directory. The directory must exist.
     23 func NewFsPersister(dir string) *FsPersister {
     24 	fp, err := filepath.Abs(dir)
     25 	if err != nil {
     26 		panic(err)
     27 	}
     28 	return &FsPersister{
     29 		dir: fp,
     30 	}
     31 }
     32 
     33 // WithContent sets a current State and Cache object.
     34 //
     35 // This method is normally called before Serialize / Save.
     36 func(p *FsPersister) WithContent(st *state.State, ca *cache.Cache) *FsPersister {
     37 	p.State = st
     38 	p.Memory = ca
     39 	return p
     40 }
     41 
     42 // GetState implements the Persister interface.
     43 func(p *FsPersister) GetState() *state.State {
     44 	return p.State
     45 }
     46 
     47 // GetMemory implements the Persister interface.
     48 func(p *FsPersister) GetMemory() cache.Memory {
     49 	return p.Memory
     50 }
     51 
     52 // Serialize implements the Persister interface.
     53 func(p *FsPersister) Serialize() ([]byte, error) {
     54 	return cbor.Marshal(p)
     55 }
     56 
     57 // Deserialize implements the Persister interface.
     58 func(p *FsPersister) Deserialize(b []byte) error {
     59 	err := cbor.Unmarshal(b, p)
     60 	return err
     61 }
     62 
     63 // Save implements the Persister interface.
     64 func(p *FsPersister) Save(key string) error {
     65 	b, err := p.Serialize()
     66 	if err != nil {
     67 		return err
     68 	}
     69 	fp := path.Join(p.dir, key)
     70 	Logg.Debugf("saved state and cache", "key", key, "bytecode", p.State.Code)
     71 	return ioutil.WriteFile(fp, b, 0600)
     72 }
     73 
     74 // Load implements the Persister interface.
     75 func(p *FsPersister) Load(key string) error {
     76 	fp := path.Join(p.dir, key)
     77 	b, err := ioutil.ReadFile(fp)
     78 	if err != nil {
     79 		return err
     80 	}
     81 	err = p.Deserialize(b)
     82 	Logg.Debugf("loaded state and cache", "key", key, "bytecode", p.State.Code)
     83 	return err
     84 }