1+ package com .igormaznitsa .jbbp .io ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertArrayEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertEquals ;
5+
6+ import java .io .ByteArrayInputStream ;
7+ import java .io .ByteArrayOutputStream ;
8+ import java .util .BitSet ;
9+ import java .util .Random ;
10+ import org .junit .jupiter .params .ParameterizedTest ;
11+ import org .junit .jupiter .params .provider .EnumSource ;
12+
13+ public class JBBPBitOrderTest {
14+
15+ @ ParameterizedTest
16+ @ EnumSource (JBBPBitOrder .class )
17+ void testBitWriteRead (final JBBPBitOrder bitOrder ) throws Exception {
18+ final int bits = 10_000_000 ;
19+
20+ final Random rnd = new Random (1232345L );
21+
22+ final BitSet bitSet = new BitSet (bits * 5 );
23+ for (int i = 0 ; i < bits ; i ++) {
24+ bitSet .set (rnd .nextInt (bitSet .size ()));
25+ }
26+
27+ final byte [] array = bitSet .toByteArray ();
28+
29+ final ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();
30+
31+ final JBBPBitOutputStream bitOutputStream = new JBBPBitOutputStream (outputStream , bitOrder );
32+
33+ final ByteArrayOutputStream portions = new ByteArrayOutputStream ();
34+ int dataIndex = 0 ;
35+ while (dataIndex < array .length ) {
36+ int bitsLeft = 8 ;
37+ int acc = array [dataIndex ++] & 0xFF ;
38+ while (bitsLeft > 0 ) {
39+ final int portion = Math .min (bitsLeft , rnd .nextInt (8 ) + 1 );
40+ bitsLeft -= portion ;
41+
42+ final JBBPBitNumber bitNumber = JBBPBitNumber .decode (portion );
43+
44+ bitOutputStream .writeBits (acc , JBBPBitNumber .decode (portion ));
45+ acc >>>= portion ;
46+ portions .write (portion );
47+ }
48+ }
49+ bitOutputStream .close ();
50+ outputStream .close ();
51+
52+ final byte [] portionsArray = portions .toByteArray ();
53+ final byte [] dataArray = outputStream .toByteArray ();
54+
55+ final JBBPBitInputStream inputStream =
56+ new JBBPBitInputStream (new ByteArrayInputStream (dataArray ), bitOrder );
57+
58+ final ByteArrayOutputStream restoredDataStream = new ByteArrayOutputStream ();
59+
60+ for (int i = 0 ; i < portionsArray .length ; ) {
61+ int readBits = 0 ;
62+ int acc = 0 ;
63+ while (readBits < 8 ) {
64+ final int portion = portionsArray [i ++];
65+ final JBBPBitNumber bitNumber = JBBPBitNumber .decode (portion );
66+ final int data = inputStream .readBits (bitNumber );
67+ acc |= ((data & bitNumber .getMask ()) << readBits );
68+
69+ readBits += portion ;
70+ if (readBits > 8 ) {
71+ throw new Error ("unexpected" );
72+ }
73+ if (readBits == 8 ) {
74+ restoredDataStream .write (acc );
75+ }
76+ }
77+ }
78+ restoredDataStream .close ();
79+
80+ final byte [] readData = restoredDataStream .toByteArray ();
81+
82+ assertEquals (array .length , readData .length );
83+ assertArrayEquals (array , readData );
84+ }
85+
86+ }
0 commit comments