parseDataSize function

int parseDataSize(
  1. String value
)

Reads a size written in a property, such as logging.file.rolling-policy.max-file-size, and returns it in bytes.

Accepts 10MB, 512 KB, 1GB, 100B or a plain number of bytes (1024); the unit is case-insensitive. Units are binary, as in Spring's DataSize: 1 KB is 1024 bytes. Throws a FormatException for anything else, such as 10 megabytes or -1MB.

parseDataSize('10MB'); // 10485760

Implementation

int parseDataSize(String value) {
  final match = RegExp(
    r'^\s*(\d+)\s*(B|KB|MB|GB|TB)?\s*$',
    caseSensitive: false,
  ).firstMatch(value);
  if (match == null) {
    throw FormatException('Not a data size (e.g. 10MB)', value);
  }
  final unit = switch (match.group(2)?.toUpperCase()) {
    'KB' => 1024,
    'MB' => 1024 * 1024,
    'GB' => 1024 * 1024 * 1024,
    'TB' => 1024 * 1024 * 1024 * 1024,
    _ => 1,
  };
  return int.parse(match.group(1)!) * unit;
}