convert method
Converts input and returns the result of the conversion.
Implementation
@override
Uint8List convert(String s) {
var result = Uint8List(64);
var resultLength = 0;
var lineNumber = 0;
for (var line in s.split('\n')) {
lineNumber++;
// Remove possible line prefix (like "0000000: ")
final match = _prefixRegExp.matchAsPrefix(line);
if (match != null) {
line = line.substring(match.end);
}
int? firstGroupLength;
// Parse each group of hexadecimal digits
while (true) {
final match = _hexRegExp.matchAsPrefix(line);
if (match == null) break;
final group = match.group(1)!;
line = line.substring(match.end);
// Validate even length
if (group.length.isOdd) {
throw ArgumentError(
"Error at line $lineNumber: invalid group of hexadecimal digits (non-even length): '$group'",
);
}
// Record the length of the first group for comparison
if (firstGroupLength == null) {
firstGroupLength = group.length;
} else if (group.length > firstGroupLength) {
// Longer than the first group → stop parsing hex for this line
break;
}
// Parse each byte from the hex string
for (var i = 0; i < group.length; i += 2) {
final byteString = group.substring(i, i + 2);
int byte;
try {
byte = int.parse(byteString, radix: 16);
} catch (_) {
throw ArgumentError.value(
"Error at line $lineNumber: '$byteString' is not valid hex",
);
}
// Expand buffer if needed
if (resultLength == result.lengthInBytes) {
final oldResult = result;
result = Uint8List(resultLength * 2);
result.setAll(0, oldResult);
}
// Append parsed byte
result[resultLength++] = byte;
}
}
}
return Uint8List.view(result.buffer, 0, resultLength);
}