From c4b3c6441a38d40ccf20cddee241ed9ef1208158 Mon Sep 17 00:00:00 2001 From: brent s Date: Tue, 1 Feb 2022 18:26:26 -0500 Subject: [PATCH] adding Bytes() to MaskBit --- bitmask/bitmask.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/bitmask/bitmask.go b/bitmask/bitmask.go index 549bfae..4080e3b 100644 --- a/bitmask/bitmask.go +++ b/bitmask/bitmask.go @@ -1,5 +1,12 @@ package bitmask +import ( + "bytes" + "errors" + "encoding/binary" + "math/bits" +) + // MaskBit is a flag container. type MaskBit uint @@ -62,6 +69,46 @@ func (m *MaskBit) ToggleFlag(flag MaskBit) { return } +/* + Bytes returns the current value of a MasBit as a byte slice (big-endian). + + If trim is false, b will (probably) be 4 bytes long if you're on a 32-bit size system, + and b will (probably) be 8 bytes long if you're on a 64-bit size system. You can determine + the size of the resulting slice via (math/)bits.UintSize / 8. + + If trim is true, it will trim leading null bytes (if any). This will lead to an unpredictable + byte slice length in b, but is most likely preferred for byte operations. + +*/ +func (m *MaskBit) Bytes(trim bool) (b []byte) { + + var b2 []byte + var size int = bits.UintSize / 8 + var err error + + b2 = make([]byte, size) + + switch s := bits.UintSize; s { + case 32: + binary.BigEndian.PutUint32(b2[:], uint32(*m)) + case 64: + binary.BigEndian.PutUint64(b2[:], uint64(*m)) + default: + err = errors.New("unsupported Uint/system bit size") + panic(err) + } + + if trim { + b = bytes.TrimLeft(b2, "\x00") + return + } else { + b = b2 + return + } + + return +} + // Value returns the current raw uint value of a MaskBit. func (m *MaskBit) Value() (v uint) {