github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/codec/bytes.go (about)

     1  package codec
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  type byteCodec struct{}
     8  
     9  // Bytes only support []byte and string data type
    10  var Bytes SerializeType = RegisterCodec("Bytes", &byteCodec{})
    11  
    12  // Encode returns raw slice of bytes.
    13  func (c byteCodec) Encode(i interface{}) ([]byte, error) {
    14  	if i == nil {
    15  		return []byte{}, nil
    16  	}
    17  
    18  	switch v := i.(type) {
    19  	case []byte:
    20  		return v, nil
    21  	case string:
    22  		return []byte(v), nil
    23  
    24  	default:
    25  		return nil, fmt.Errorf("%T is not a []byte", i)
    26  	}
    27  }
    28  
    29  // Decode returns raw slice of bytes.
    30  func (c byteCodec) Decode(data []byte, out interface{}) error {
    31  	// #1 reflect method but is slow
    32  	//reflect.Indirect(reflect.ValueOf(i)).SetBytes(data)
    33  
    34  	// #2
    35  	switch v := out.(type) {
    36  	case *[]byte:
    37  		*v = *&data
    38  		return nil
    39  	case *string:
    40  		*v = string(data)
    41  		return nil
    42  
    43  	default:
    44  		return fmt.Errorf("%T is not a []byte", out)
    45  	}
    46  }
    47  
    48  func (c byteCodec) String() string {
    49  	return "Bytes"
    50  }