summaryrefslogtreecommitdiffstats
path: root/lib/byte.go
blob: 02746ae67457014bc526b2577398df82904565fd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright © 2021 siddharth ravikumar <s@ricketyspace.net>
// SPDX-License-Identifier: ISC

package lib

// Returns true if byte `b` is in `bs`
func ByteInBytes(b byte, bs []byte) bool {
	for _, bi := range bs {
		if b == bi {
			return true
		}
	}
	return false
}

// Returns bytes that are common in the given array of array of bytes
// `bbytes`.
func BytesInCommon(bbytes [][]byte) []byte {
	var common []byte
	switch l := len(bbytes); {
	case l == 1:
		common = make([]byte, len(bbytes[0]))
		copy(common, bbytes[0])
	case l > 1:
		common = make([]byte, 0)
		commonRest := BytesInCommon(bbytes[1:])
		for _, b := range bbytes[0] {
			if ByteInBytes(b, commonRest) {
				common = append(common, b)
			}
		}
	}
	return common
}

func ByteIsUpper(b byte) bool {
	if 'A' <= b && b <= 'Z' {
		return true
	}
	return false
}

func BytesEqual(a, b []byte) bool {
	return BlocksEqual(a, b)
}

func BytesToUint32s(bs []byte) []uint32 {
	u32s := make([]uint32, 0)

	ui := uint32(0) // 32-bit word.
	ab := uint(32)  // Available bits in ui.
	for _, b := range bs {
		if ab == 0 {
			// ui full; add to u32s and reset ui.
			u32s = append(u32s, ui)
			ui = uint32(0)
			ab = 32
		}
		// Stuff byte into ui.
		ui = ui | uint32(b)<<(ab-8)
		ab = ab - 8
	}
	if ui > 0 {
		u32s = append(u32s, ui)
	}
	return u32s
}

func BytesToUint32sLittleEndian(bs []byte) []uint32 {
	u32s := make([]uint32, 0)

	ui := uint32(0) // 32-bit word.
	ab := uint(0)   // Occupied bits in ui
	for _, b := range bs {
		if ab == 32 {
			// ui full; add to u32s and reset ui.
			u32s = append(u32s, ui)
			ui = uint32(0)
			ab = 0
		}
		// Stuff byte into ui.
		ui = ui | uint32(b)<<ab
		ab = ab + 8
	}
	if ui > 0 {
		u32s = append(u32s, ui)
	}
	return u32s
}