parseSizeToBytes function
Parses a human-readable size string in input into a byte count.
Accepts an optional decimal number followed by an optional binary unit
(K, M, G, T, P, E) and an optional trailing B, case-insensitive
with surrounding whitespace allowed. Units use 1024-based factors. The result
is rounded to the nearest whole byte. Returns null for malformed input or a
negative value.
Example:
parseSizeToBytes('1.5 MB'); // 1572864
parseSizeToBytes('512K'); // 524288
parseSizeToBytes('big'); // null
Implementation
int? parseSizeToBytes(String input) {
final RegExpMatch? m = _sizeRegex.firstMatch(input.trim());
if (m == null) return null;
final String? g1 = m.group(1);
if (g1 == null) return null;
final double? value = double.tryParse(g1);
if (value == null || value < 0) return null;
// The unit group may be 'K', 'KB', or 'B'; strip the trailing 'B' so that
// 'KB' and 'K' both key into the factor table as 'K' (and 'B'/'' as bytes).
final String unit = (m.group(2) ?? '').toUpperCase().replaceAll(_kUnitB, '');
// 1024-based (binary) factors: callers expect '1 MB' = 1048576 bytes, not 1e6.
const Map<String, int> factors = <String, int>{
'': 1,
'K': 1024,
'M': 1048576,
'G': 1073741824,
'T': 1099511627776,
'P': 1125899906842624,
'E': 1152921504606846976,
};
final int? factor = factors[unit];
if (factor == null) return null;
return (value * factor).round();
}