parse static method
Parse a text into a BinarySize object
When unit contains 'i', it will be considered as IEC standard
When unit contains no 'i', we will use fallbackStandard
to determine the standard
fallbackStandard
in default is BinarySizeSiStandard
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;
}