github.com/zly-app/zapp@v1.3.3/pkg/serializer/bytes.go (about)

     1  package serializer
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"reflect"
     7  	"unsafe"
     8  )
     9  
    10  const BytesSerializerName = "bytes"
    11  
    12  type bytesSerializer struct{}
    13  
    14  func (bytesSerializer) toBytes(a interface{}) ([]byte, error) {
    15  	switch v := a.(type) {
    16  	case []byte:
    17  		return v, nil
    18  	case *[]byte:
    19  		return *v, nil
    20  	case string:
    21  		return StringToBytes(&v), nil
    22  	case *string:
    23  		return StringToBytes(v), nil
    24  	}
    25  	return nil, fmt.Errorf("a not bytes, it's %T", a)
    26  }
    27  
    28  func (b bytesSerializer) Marshal(a interface{}, w io.Writer) error {
    29  	bs, err := b.toBytes(a)
    30  	if err != nil {
    31  		return err
    32  	}
    33  	_, err = w.Write(bs)
    34  	return err
    35  }
    36  
    37  func (b bytesSerializer) MarshalBytes(a interface{}) ([]byte, error) {
    38  	bs, err := b.toBytes(a)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	ret := make([]byte, len(bs))
    43  	copy(ret, bs)
    44  	return ret, nil
    45  }
    46  
    47  func (bytesSerializer) Unmarshal(r io.Reader, a interface{}) error {
    48  	bs, err := io.ReadAll(r)
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	switch v := a.(type) {
    54  	case *[]byte:
    55  		*v = bs
    56  		return nil
    57  	case *string:
    58  		*v = *BytesToString(bs)
    59  		return nil
    60  	}
    61  	return fmt.Errorf("a not bytes, it's %T", a)
    62  }
    63  
    64  func (bytesSerializer) UnmarshalBytes(data []byte, a interface{}) error {
    65  	switch v := a.(type) {
    66  	case *[]byte:
    67  		ret := make([]byte, len(data))
    68  		copy(ret, data)
    69  		*v = ret
    70  		return nil
    71  	case *string:
    72  		ret := make([]byte, len(data))
    73  		copy(ret, data)
    74  		*v = *BytesToString(ret)
    75  		return nil
    76  	}
    77  	return fmt.Errorf("a not bytes, it's %T", a)
    78  }
    79  
    80  func StringToBytes(s *string) []byte {
    81  	sh := (*reflect.StringHeader)(unsafe.Pointer(s))
    82  	bh := reflect.SliceHeader{
    83  		Data: sh.Data,
    84  		Len:  sh.Len,
    85  		Cap:  sh.Len,
    86  	}
    87  	return *(*[]byte)(unsafe.Pointer(&bh))
    88  }
    89  func BytesToString(b []byte) *string {
    90  	return (*string)(unsafe.Pointer(&b))
    91  }