go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/llx/byte_conversions.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package llx
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/binary"
     9  	"encoding/hex"
    10  	"math"
    11  	"time"
    12  )
    13  
    14  func bool2bytes(b bool) []byte {
    15  	if b {
    16  		return []byte{1}
    17  	}
    18  	return []byte{0}
    19  }
    20  
    21  func bytes2bool(b []byte) bool {
    22  	return len(b) > 0 && b[0] > 0
    23  }
    24  
    25  func int2bytes(i int64) []byte {
    26  	v := make([]byte, binary.MaxVarintLen64)
    27  	n := binary.PutVarint(v, i)
    28  	return v[:n]
    29  }
    30  
    31  func bytes2int(b []byte) int64 {
    32  	r := bytes.NewReader(b)
    33  	res, err := binary.ReadVarint(r)
    34  	if err != nil {
    35  		panic("Failed to read bytes into integer: '" + hex.EncodeToString(b) + "'\n")
    36  	}
    37  	return res
    38  }
    39  
    40  func float2bytes(f float64) []byte {
    41  	var v [8]byte
    42  	binary.LittleEndian.PutUint64(v[:], math.Float64bits(f))
    43  	return v[:]
    44  }
    45  
    46  func bytes2float(b []byte) float64 {
    47  	return math.Float64frombits(binary.LittleEndian.Uint64(b))
    48  }
    49  
    50  func bytes2time(b []byte) time.Time {
    51  	secs := int64(binary.LittleEndian.Uint64(b[0:8]))
    52  	nanos := int64(binary.LittleEndian.Uint32(b[8:]))
    53  	return time.Unix(secs, nanos)
    54  }