github.com/chain5j/chain5j-pkg@v1.0.7/types/multi_hash.go (about)

     1  // Package types
     2  //
     3  // @author: xwc1125
     4  package types
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"math/big"
    10  	"strconv"
    11  )
    12  
    13  var (
    14  	EmptyMultiHash = MultiHash{}
    15  )
    16  
    17  type MultiHash []byte
    18  
    19  func BytesToMultiHash(b []byte) MultiHash {
    20  	var h MultiHash
    21  	h.SetBytes(b)
    22  	return h
    23  }
    24  
    25  func StringToMultiHash(s string) MultiHash {
    26  	s1, err := strconv.Unquote(s)
    27  	if err == nil {
    28  		s = s1
    29  	}
    30  	return BytesToMultiHash([]byte(s))
    31  }
    32  
    33  func (h MultiHash) Bytes() []byte { return h[:] }
    34  
    35  func (h MultiHash) String() string {
    36  	return string(h.Bytes())
    37  }
    38  
    39  func (h MultiHash) TerminalString() string {
    40  	return h.String()
    41  }
    42  
    43  // Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
    44  // without going through the stringer interface used for logging.
    45  // log会调用此接口
    46  func (h MultiHash) Format(s fmt.State, c rune) {
    47  	fmt.Fprintf(s, "%"+string(c), h.Bytes())
    48  }
    49  
    50  func (h *MultiHash) SetBytes(b []byte) {
    51  	var des = make([]byte, len(b))
    52  	copy(des, b)
    53  	*h = des
    54  }
    55  
    56  func (h MultiHash) Nil() bool {
    57  	return len(h) == 0
    58  }
    59  
    60  type extMultiHash string
    61  
    62  func (h MultiHash) MarshalJSON() ([]byte, error) {
    63  	var extMultiHash = h.String()
    64  	return json.Marshal(extMultiHash)
    65  }
    66  func (h *MultiHash) UnmarshalJSON(data []byte) error {
    67  	var extMultiHash extMultiHash
    68  	err := json.Unmarshal(data, &extMultiHash)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	multiHash := StringToMultiHash(string(extMultiHash))
    73  	*h = multiHash
    74  	return nil
    75  }
    76  
    77  func (h MultiHash) MarshalText() ([]byte, error) {
    78  	return h.MarshalJSON()
    79  }
    80  
    81  // UnmarshalText .
    82  func (h *MultiHash) UnmarshalText(input []byte) error {
    83  	return h.UnmarshalJSON(input)
    84  }
    85  
    86  func (h MultiHash) Big() *big.Int {
    87  	return new(big.Int).SetBytes(h[:])
    88  }
    89  
    90  // func (h MultiHash) EncodeRLP(w io.Writer) error {
    91  // 	return rlp.Encode(w, h.String())
    92  // }
    93  // func (h *MultiHash) DecodeRLP(s *rlp.Stream) error {
    94  // 	origin, err := s.Raw()
    95  // 	if err == nil {
    96  // 		var hashStr string
    97  // 		err = rlp.DecodeBytes(origin, &hashStr)
    98  // 		if err != nil {
    99  // 			return err
   100  // 		}
   101  // 		multiHash := StringToMultiHash(hashStr)
   102  // 		*h = multiHash
   103  // 	}
   104  // 	return err
   105  // }