-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitPackerTest.java
More file actions
74 lines (56 loc) · 2.47 KB
/
BitPackerTest.java
File metadata and controls
74 lines (56 loc) · 2.47 KB
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
package com.example.bip39.bit;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class BitPackerTest {
@Test
void readsBitsMostSignificantBitFirstFromSignedBytes() {
byte[] source = {(byte) 0x80, (byte) 0xf1};
assertEquals(1, BitPacker.readBits(source, 0, 1));
assertEquals(0, BitPacker.readBits(source, 1, 7));
assertEquals(0xf1, BitPacker.readBits(source, 8, 8));
assertEquals(0x01, BitPacker.readBits(source, 12, 4));
}
@Test
void writesBitsAndExtractsBytesWithoutLosingUnsignedValues() {
byte[] target = new byte[3];
BitPacker.writeBits(target, 0, 8, 0x80);
BitPacker.writeBits(target, 8, 8, 0x01);
BitPacker.writeBits(target, 16, 8, 0xff);
assertArrayEquals(new byte[] {(byte) 0x80, 0x01, (byte) 0xff}, target);
assertArrayEquals(target, BitPacker.extractBytes(target, 0, 24));
}
@Test
void extractsBytesAcrossByteBoundaries() {
byte[] source = {0x12, 0x34, 0x56};
assertArrayEquals(new byte[] {0x23, 0x45}, BitPacker.extractBytes(source, 4, 16));
}
@Test
void splitsKnownBitSequenceIntoElevenBitValues() {
byte[] source = {0x12, 0x34, 0x56};
assertArrayEquals(new int[] {145, 1301}, BitPacker.splitTo11BitValues(source, 22));
}
@Test
void packsElevenBitValuesInMostSignificantBitOrder() {
assertArrayEquals(
new byte[] {0x12, 0x34, 0x54}, BitPacker.pack11BitValues(new int[] {145, 1301}));
}
@Test
void elevenBitPackingAndSplittingRoundTrips() {
int[] values = {0, 1, 1024, 2047, 42};
byte[] packed = BitPacker.pack11BitValues(values);
assertArrayEquals(values, BitPacker.splitTo11BitValues(packed, values.length * 11));
}
@Test
void rejectsInvalidBitAccessAndOutOfRangeValues() {
byte[] source = new byte[2];
assertThrows(IllegalArgumentException.class, () -> BitPacker.readBits(source, -1, 1));
assertThrows(IllegalArgumentException.class, () -> BitPacker.readBits(source, 0, 17));
assertThrows(IllegalArgumentException.class, () -> BitPacker.writeBits(source, 0, 3, 0b1000));
assertThrows(
IllegalArgumentException.class, () -> BitPacker.splitTo11BitValues(source, Byte.SIZE));
assertThrows(IllegalArgumentException.class, () -> BitPacker.pack11BitValues(new int[] {2048}));
assertThrows(IllegalArgumentException.class, () -> BitPacker.extractBytes(source, 0, 7));
}
}