github.com/philpearl/plenc@v0.0.15/plenccodec/bool.go (about)

     1  package plenccodec
     2  
     3  import (
     4  	"fmt"
     5  	"unsafe"
     6  
     7  	"github.com/philpearl/plenc/plenccore"
     8  )
     9  
    10  // BoolCodec is a codec for a bool
    11  type BoolCodec struct{}
    12  
    13  // append encodes a bool
    14  func (BoolCodec) append(data []byte, ptr unsafe.Pointer) []byte {
    15  	var uv uint64
    16  	if *(*bool)(ptr) {
    17  		uv = 1
    18  	}
    19  	return plenccore.AppendVarUint(data, uv)
    20  }
    21  
    22  // Read decodes a bool
    23  func (BoolCodec) Read(data []byte, ptr unsafe.Pointer, wt plenccore.WireType) (n int, err error) {
    24  	uv, n := plenccore.ReadVarUint(data)
    25  	if n < 0 {
    26  		return 0, fmt.Errorf("corrupt var int")
    27  	}
    28  	*(*bool)(ptr) = (uv != 0)
    29  	return n, nil
    30  }
    31  
    32  // New creates a pointer to a new bool
    33  func (c BoolCodec) New() unsafe.Pointer {
    34  	return unsafe.Pointer(new(bool))
    35  }
    36  
    37  // WireType returns the wire type used to encode this type
    38  func (c BoolCodec) WireType() plenccore.WireType {
    39  	return plenccore.WTVarInt
    40  }
    41  
    42  // Omit indicates whether this field should be omitted
    43  func (c BoolCodec) Omit(ptr unsafe.Pointer) bool {
    44  	return !*(*bool)(ptr)
    45  }
    46  
    47  func (c BoolCodec) Descriptor() Descriptor {
    48  	return Descriptor{Type: FieldTypeBool}
    49  }
    50  
    51  func (c BoolCodec) Size(ptr unsafe.Pointer, tag []byte) int {
    52  	return 1 + len(tag)
    53  }
    54  
    55  func (c BoolCodec) Append(data []byte, ptr unsafe.Pointer, tag []byte) []byte {
    56  	data = append(data, tag...)
    57  	return c.append(data, ptr)
    58  }