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

     1  // Copyright (c) 2018 IoTeX
     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 state
     7  
     8  import (
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  var (
    13  	// ErrStateSerialization is the error that the state marshaling is failed
    14  	ErrStateSerialization = errors.New("failed to marshal state")
    15  
    16  	// ErrStateDeserialization is the error that the state un-marshaling is failed
    17  	ErrStateDeserialization = errors.New("failed to unmarshal state")
    18  
    19  	// ErrStateNotExist is the error that the state does not exist
    20  	ErrStateNotExist = errors.New("state does not exist")
    21  )
    22  
    23  // State is the interface, which defines the common methods for state struct to be handled by state factory
    24  type State interface {
    25  	Serialize() ([]byte, error)
    26  	Deserialize(data []byte) error
    27  }
    28  
    29  // Serializer has Serialize method to serialize struct to binary data.
    30  type Serializer interface {
    31  	Serialize() ([]byte, error)
    32  }
    33  
    34  // Deserializer has Deserialize method to deserialize binary data to struct.
    35  type Deserializer interface {
    36  	Deserialize(data []byte) error
    37  }
    38  
    39  // Serialize check if input is Serializer, if it is, use the input's Serialize method, otherwise use Gob.
    40  func Serialize(d interface{}) ([]byte, error) {
    41  	if s, ok := d.(Serializer); ok {
    42  		return s.Serialize()
    43  	}
    44  	panic("data holder doesn't implement Serializer interface!")
    45  }
    46  
    47  // Deserialize check if input is Deserializer, if it is, use the input's Deserialize method, otherwise use Gob.
    48  func Deserialize(x interface{}, data []byte) error {
    49  	if s, ok := x.(Deserializer); ok {
    50  		return s.Deserialize(data)
    51  	}
    52  	panic("data holder doesn't implement Deserializer interface!")
    53  }