parse static method
Parses a human-readable size string into a BinarySize object.
The string may contain an integer part, an optional fractional part, and a unit suffix. Examples of valid inputs:
"344 B""1.00 KiB""3.25 GiB""7.5 MB"
Standard detection:
- If the unit contains an
i(e.g. KiB, MiB), the IEC standard is used. - Otherwise,
fallbackStandardis used (defaults to BinarySizeSiStandard).
Returns null if the input string does not match the expected format.
final size = BinarySize.parse('3.25 GiB');
print(size?.bytesCount); // BigInt 3489660928
print(size?.displayText); // "3.25 GiB"
Implementation
static BinarySize? parse(String size, {BinarySizeConventionStandard? fallbackStandard}) {
BinarySize? result;
fallbackStandard ??= BinarySizeSiStandard();
var exp = RegExp(r'(\d+).?(\d*)\s*(B|Ki?B|Mi?B|Gi?B|Ti?B|Pi?B|Ei?B)', caseSensitive: false);
if (exp.hasMatch(size)) {
result = BinarySize();
var match = exp.firstMatch(size);
if (match == null) return null;
var integer = match.group(1) ?? '';
var left = match.group(2) ?? '';
var unit = match.group(3) ?? '';
var isIec = unit.toLowerCase().contains('i');
result.standard = isIec ? BinarySizeIecStandard() : fallbackStandard;
var diff = result.standard.getLevelBase();
var scale = BigInt.from(1);
switch (unit.toUpperCase().replaceAll('IB', 'B')) {
case 'B':
break;
case 'KB':
scale = diff;
break;
case 'MB':
scale = diff * diff;
break;
case 'GB':
scale = diff * diff * diff;
break;
case 'TB':
scale = diff * diff * diff * diff;
break;
case 'PB':
scale = diff * diff * diff * diff * diff;
break;
case 'EB':
scale = diff * diff * diff * diff * diff * diff;
break;
default:
break;
}
var p = 0;
for (var i = integer.length - 1; i >= 0; --i, ++p) {
var addon = BigInt.from(int.parse(integer[i]) * pow(10, p)) * scale;
result.bytesCount += addon;
}
p = -1;
for (var i = 0; i < left.length; ++i, --p) {
var addon = BigInt.from(int.parse(left[i]) * pow(10, p)) * scale;
result.bytesCount += addon;
}
if (unit.contains('b')) result.bytesCount = BigInt.from(result.bytesCount / BigInt.from(8));
}
return result;
}