github.com/kamalshkeir/kencoding@v0.0.2-0.20230409043843-44b609a0475a/proto/float32.go (about)

     1  package proto
     2  
     3  import (
     4  	"math"
     5  	"unsafe"
     6  )
     7  
     8  var float32Codec = codec{
     9  	wire:   fixed32,
    10  	size:   sizeOfFloat32,
    11  	encode: encodeFloat32,
    12  	decode: decodeFloat32,
    13  }
    14  
    15  func sizeOfFloat32(p unsafe.Pointer, flags flags) int {
    16  	if p != nil {
    17  		if v := *(*float32)(p); v != 0 || flags.has(wantzero) || math.Signbit(float64(v)) {
    18  			return 4
    19  		}
    20  	}
    21  	return 0
    22  }
    23  
    24  func encodeFloat32(b []byte, p unsafe.Pointer, flags flags) (int, error) {
    25  	if p != nil {
    26  		if v := *(*float32)(p); v != 0 || flags.has(wantzero) || math.Signbit(float64(v)) {
    27  			return encodeLE32(b, math.Float32bits(v))
    28  		}
    29  	}
    30  	return 0, nil
    31  }
    32  
    33  func decodeFloat32(b []byte, p unsafe.Pointer, _ flags) (int, error) {
    34  	v, n, err := decodeLE32(b)
    35  	*(*float32)(p) = math.Float32frombits(v)
    36  	return n, err
    37  }