github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/dock.go (about)

     1  // Copyright (c) 2020 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package protocol
     7  
     8  import (
     9  	"github.com/pkg/errors"
    10  
    11  	"github.com/iotexproject/iotex-core/state"
    12  )
    13  
    14  // Errors
    15  var (
    16  	ErrNoName = errors.New("name does not exist")
    17  )
    18  
    19  type dock struct {
    20  	stash map[string]map[string][]byte
    21  }
    22  
    23  // NewDock returns a new dock
    24  func NewDock() Dock {
    25  	return &dock{
    26  		stash: map[string]map[string][]byte{},
    27  	}
    28  }
    29  
    30  func (d *dock) ProtocolDirty(name string) bool {
    31  	_, hit := d.stash[name]
    32  	return hit
    33  }
    34  
    35  func (d *dock) Load(ns, key string, v interface{}) error {
    36  	ser, err := state.Serialize(v)
    37  	if err != nil {
    38  		return err
    39  	}
    40  
    41  	if _, hit := d.stash[ns]; !hit {
    42  		d.stash[ns] = map[string][]byte{}
    43  	}
    44  	d.stash[ns][key] = ser
    45  	return nil
    46  }
    47  
    48  func (d *dock) Unload(ns, key string, v interface{}) error {
    49  	if _, hit := d.stash[ns]; !hit {
    50  		return ErrNoName
    51  	}
    52  
    53  	ser, hit := d.stash[ns][key]
    54  	if !hit {
    55  		return ErrNoName
    56  	}
    57  	return state.Deserialize(v, ser)
    58  }
    59  
    60  func (d *dock) Reset() {
    61  	for k := range d.stash {
    62  		delete(d.stash, k)
    63  	}
    64  }