Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #183, parsing of unsigned large binary integers #184

Merged
merged 1 commit into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions lib/src/values/logic_value.dart
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ abstract class LogicValue {
final width = stringRepresentation.length;

if (width <= _INT_BITS) {
final value = int.parse(valueString, radix: 2);
final invalid = int.parse(invalidString, radix: 2);
final value = _unsignedBinaryParse(valueString);
final invalid = _unsignedBinaryParse(invalidString);
return _SmallLogicValue(value, invalid, width);
} else {
final value = BigInt.parse(valueString, radix: 2);
Expand Down Expand Up @@ -791,7 +791,24 @@ enum _ShiftType { left, right, arithmeticRight }
/// Converts a binary [String] representation to a binary [int].
///
/// Ignores all '_' in the provided binary.
int bin(String s) => int.parse(s.replaceAll('_', ''), radix: 2);
int bin(String s) => _unsignedBinaryParse(s.replaceAll('_', ''));

/// Parses [source] as a binary integer, similarly to [int.parse].
///
/// If [source] interpreted as a positive signed integer would be larger than
/// the maximum allowed by [int], then [int.parse] will throw an exception. This
/// function will instead properly interpret it as an unsigned integer.
int _unsignedBinaryParse(String source) {
final val = int.tryParse(source, radix: 2);
if (val != null) {
return val;
} else {
final hex = BigInt.parse(source, radix: 2).toRadixString(16);

// With `0x` in front of a hex literal, it will be interpreted as unsigned.
return int.parse('0x$hex');
}
}

/// Enum for a [LogicValue]'s value.
enum _LogicValueEnum { zero, one, x, z }
3 changes: 3 additions & 0 deletions test/logic_value_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ void main() {
expect(
<LogicValue>[].swizzle(), equals(LogicValue.ofBigInt(BigInt.two, 0)));
});
test('big unsigned int string', () {
expect(LogicValue.ofString('1' * 64), equals(LogicValue.ofInt(-1, 64)));
});
test('unary', () {
expect(LogicValue.one.isValid, equals(true));
expect(LogicValue.zero.isValid, equals(true));
Expand Down