parseSizeBytes function

int parseSizeBytes(
  1. String raw
)

Parses a size string to bytes: a plain integer ('1024') is bytes; binary suffixes K/KiB, M/Mi/MiB, G/GiB are 1024-based and decimal B, KB, MB, GB are 1000-based (case-insensitive).

Throws FormatException on malformed input (non-integer magnitude, unknown suffix, negative or empty string).

Implementation

int parseSizeBytes(String raw) {
  final match = _sizePattern.firstMatch(raw.trim());
  if (match == null) {
    throw FormatException(
      'invalid size "$raw" — expected an integer byte count or a size like '
      '512Mi, 100MiB, 1GB',
    );
  }
  final magnitude = int.parse(match.group(1)!);
  final suffix = match.group(2)!.toUpperCase();
  const binary = 1024, decimal = 1000;
  final multiplier = switch (suffix) {
    '' || 'B' => 1,
    'K' || 'KIB' => binary,
    'KB' => decimal,
    'M' || 'MI' || 'MIB' => binary * binary,
    'MB' => decimal * decimal,
    'G' || 'GIB' => binary * binary * binary,
    'GB' => decimal * decimal * decimal,
    _ => throw FormatException(
      'unknown size suffix "$suffix" in "$raw" — supported: B, K/KiB, '
      'KB, M/Mi/MiB, MB, G/GiB, GB',
    ),
  };
  return magnitude * multiplier;
}