Skip to content

Commit

Permalink
Improved Bit class
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Sep 10, 2024
1 parent f714b30 commit 0204010
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions lib/src/bit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,43 @@ import 'dart:typed_data';
import 'utils.dart';

class Bit {
final List<bool> _vec;
final int _len;
final Uint8List _data;

const Bit(this._vec);
const Bit._(this._len, this._data);

factory Bit.fromBinary(Uint8List bytes) {
var buf = new ByteData.view(bytes.buffer, bytes.offsetInBytes);
var length = buf.getInt32(0);

var vec = <bool>[];
factory Bit(List<bool> value) {
var length = value.length;
var data = Uint8List(((length + 7) / 8).toInt());
for (var i = 0; i < length; i++) {
vec.add((bytes[4 + (i / 8).toInt()] >> (7 - (i % 8))) & 1 == 1);
data[(i / 8).toInt()] |= (value[i] ? 1 : 0) << (7 - (i % 8));
}
return Bit._(length, data);
}

return Bit(vec);
factory Bit.fromBinary(Uint8List bytes) {
var buf = new ByteData.view(bytes.buffer, bytes.offsetInBytes);
var length = buf.getInt32(0);
return Bit._(length, bytes.sublist(4));
}

List<bool> toList() {
return _vec;
var vec = <bool>[];
for (var i = 0; i < _len; i++) {
vec.add((_data[(i / 8).toInt()] >> (7 - (i % 8))) & 1 == 1);
}
return vec;
}

@override
String toString() {
return _vec.map((v) => v ? '1' : '0').join();
return toList().map((v) => v ? '1' : '0').join();
}

@override
bool operator ==(Object other) =>
other is Bit && listEquals(other._vec, _vec);
other is Bit && other._len == _len && listEquals(other._data, _data);

@override
int get hashCode => _vec.hashCode;
int get hashCode => Object.hash(_len, _data);
}

0 comments on commit 0204010

Please sign in to comment.