31 lines
845 B
Go
31 lines
845 B
Go
|
|
package utils
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"fmt"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Uint24 represents an integer existing out of 3 bytes. It is actually a
|
||
|
|
// uint32, but is an alias for the sake of clarity.
|
||
|
|
type Uint24 uint32
|
||
|
|
|
||
|
|
// ReadUint24 reads 3 bytes from the buffer passed and combines it into a
|
||
|
|
// uint24. If there were no 3 bytes to read, an error is returned.
|
||
|
|
func ReadUint24(b *bytes.Buffer) (Uint24, error) {
|
||
|
|
ba, _ := b.ReadByte()
|
||
|
|
bb, _ := b.ReadByte()
|
||
|
|
bc, err := b.ReadByte()
|
||
|
|
if err != nil {
|
||
|
|
return 0, fmt.Errorf("error reading uint24: %v", err)
|
||
|
|
}
|
||
|
|
return Uint24(ba) | (Uint24(bb) << 8) | (Uint24(bc) << 16), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// WriteUint24 writes a uint24 to the buffer passed as 3 bytes. If not
|
||
|
|
// successful, an error is returned.
|
||
|
|
func WriteUint24(b *bytes.Buffer, value Uint24) {
|
||
|
|
b.WriteByte(byte(value))
|
||
|
|
b.WriteByte(byte(value >> 8))
|
||
|
|
b.WriteByte(byte(value >> 16))
|
||
|
|
}
|