decode method
Decodes hexStr into bytes.
Throws HexFormatError if hexStr has an odd length or contains a
non-hex character.
Implementation
BuBytes decode(String hexStr) {
if (hexStr.isEmpty) return BuBytes.empty();
if (!hexStr.length.isEven) {
throw BuError(
DefaultErrorType.invalidLength,
'Invalid hex string.',
details: {'reason': 'odd length (${hexStr.length})'},
);
}
final result = BuBytes.fill(hexStr.length ~/ 2, 0);
// Tracks the first bad character's index without bailing out early -
// keeps the loop branch-light (same trick the original used, just
// extended to remember *where* rather than only *whether*), so a
// caller gets a specific, actionable error instead of a generic one.
var firstBadIndex = -1;
for (var i = 0; i < hexStr.length; i += 2) {
final v0 = _decodeNibble(hexStr.codeUnitAt(i));
final v1 = _decodeNibble(hexStr.codeUnitAt(i + 1));
result[i ~/ 2] = ((v0 << 4) | v1) & 0xFF;
if (firstBadIndex == -1 &&
(v0 == _invalidHexNibble || v1 == _invalidHexNibble)) {
firstBadIndex = v0 == _invalidHexNibble ? i : i + 1;
}
}
if (firstBadIndex != -1) {
throw BuError(
DefaultErrorType.badHex,
'Invalid hex string.',
details: {
'reason':
'invalid character "${hexStr[firstBadIndex]}" at index $firstBadIndex',
},
);
}
return result;
}