github.com/segmentio/encoding@v0.4.0/proto/uint32.go (about)

     1  package proto
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"unsafe"
     7  )
     8  
     9  var uint32Codec = codec{
    10  	wire:   varint,
    11  	size:   sizeOfUint32,
    12  	encode: encodeUint32,
    13  	decode: decodeUint32,
    14  }
    15  
    16  func sizeOfUint32(p unsafe.Pointer, flags flags) int {
    17  	if p != nil {
    18  		if v := *(*uint32)(p); v != 0 || flags.has(wantzero) {
    19  			return sizeOfVarint(uint64(v))
    20  		}
    21  	}
    22  	return 0
    23  }
    24  
    25  func encodeUint32(b []byte, p unsafe.Pointer, flags flags) (int, error) {
    26  	if p != nil {
    27  		if v := *(*uint32)(p); v != 0 || flags.has(wantzero) {
    28  			return encodeVarint(b, uint64(v))
    29  		}
    30  	}
    31  	return 0, nil
    32  }
    33  
    34  func decodeUint32(b []byte, p unsafe.Pointer, _ flags) (int, error) {
    35  	v, n, err := decodeVarint(b)
    36  	if v > math.MaxUint32 {
    37  		return n, fmt.Errorf("integer overflow decoding %v into uint32", v)
    38  	}
    39  	*(*uint32)(p) = uint32(v)
    40  	return n, err
    41  }
    42  
    43  var fixed32Codec = codec{
    44  	wire:   fixed32,
    45  	size:   sizeOfFixed32,
    46  	encode: encodeFixed32,
    47  	decode: decodeFixed32,
    48  }
    49  
    50  func sizeOfFixed32(p unsafe.Pointer, flags flags) int {
    51  	if p != nil {
    52  		if v := *(*uint32)(p); v != 0 || flags.has(wantzero) {
    53  			return 4
    54  		}
    55  	}
    56  	return 0
    57  }
    58  
    59  func encodeFixed32(b []byte, p unsafe.Pointer, flags flags) (int, error) {
    60  	if p != nil {
    61  		if v := *(*uint32)(p); v != 0 || flags.has(wantzero) {
    62  			return encodeLE32(b, v)
    63  		}
    64  	}
    65  	return 0, nil
    66  }
    67  
    68  func decodeFixed32(b []byte, p unsafe.Pointer, _ flags) (int, error) {
    69  	v, n, err := decodeLE32(b)
    70  	*(*uint32)(p) = v
    71  	return n, err
    72  }