Skip to content

Commit c814216

Browse files
authored
[Feature] Support for importing from Uint8List (#12)
* [Feature] Support for importing from Uint8List * [Feature] Support for BitArray.fromString * [Code Review] Changes according to code review comments
1 parent 4503143 commit c814216

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

lib/src/bit_array.dart

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,35 @@ class BitArray extends BitSet {
2828
return BitArray._(data);
2929
}
3030

31+
/// Creates a bit array using a Uint8List.
32+
factory BitArray.fromUint8List(Uint8List list) {
33+
if (list.lengthInBytes % 4 != 0) {
34+
throw FormatException('Uint8List length must be a multiplication of 4');
35+
}
36+
final data =
37+
list.buffer.asUint32List(list.offsetInBytes, list.lengthInBytes >> 2);
38+
return BitArray._(data);
39+
}
40+
41+
/// Create a bit array from a binary string.
42+
factory BitArray.parseBinary(String bitString) {
43+
var data = Uint32List((bitString.length + 31) >> 5);
44+
var bitIndex = 0;
45+
for (var i = bitString.length - 1; i >= 0; i--) {
46+
if (bitString[i] == '0') {
47+
bitIndex++;
48+
// Nothing to do
49+
} else if (bitString[i] == '1') {
50+
var wordIndex = (bitIndex) >> 5;
51+
data[wordIndex] |= 1 << (bitIndex % 32);
52+
bitIndex++;
53+
} else {
54+
throw FormatException('Binary string should consist of 0s and 1s only');
55+
}
56+
}
57+
return BitArray._(data);
58+
}
59+
3160
/// The value of the bit with the specified [index].
3261
@override
3362
bool operator [](int index) {

test/bit_array_test.dart

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import 'dart:typed_data';
2+
13
import 'package:test/test.dart';
24

35
import 'package:bit_array/bit_array.dart';
@@ -81,6 +83,35 @@ void main() {
8183
expect(deccumulator[i], accumulator[i]);
8284
}
8385
});
86+
87+
test('fromUint8list', () {
88+
var list = Uint8List.fromList(<int>[0xAA, 0x55, 0x1b, 0x1a]);
89+
var bitArray = BitArray.fromUint8List(list);
90+
91+
for (int w = 0; w < 2; w++) {
92+
var word = 0;
93+
for (int b = 7; b >= 0; b--) {
94+
word <<= 1;
95+
word |= (bitArray[b + w * 8] ? 1 : 0);
96+
}
97+
expect(word, list[w]);
98+
}
99+
});
100+
101+
test('fromString', () {
102+
void testBitString(String bitString) {
103+
var reversedBitString = bitString.split('').reversed.join();
104+
var bitArray = BitArray.parseBinary(bitString);
105+
for (int i = 0; i < bitString.length; i++) {
106+
expect(bitArray[i], reversedBitString[i] == '1');
107+
}
108+
}
109+
110+
testBitString('111010');
111+
testBitString('101010010101001001000100101110');
112+
testBitString('10101001011101110101110011101010110101011111110110');
113+
});
114+
84115
test('array ops', () {
85116
final oooo = BitArray(32);
86117
expect(oooo.toBinaryString().substring(0, 4), '0000');

0 commit comments

Comments
 (0)