byteOption function

int? byteOption(
  1. String longName,
  2. String? shortName,
  3. String argument
)

Tests whether the argument has the longName or the shortName and byte value given by an int an a unit. Returns the int value. Throws OptionException on error. longName: the long name to inspect, e.g. 'max-size' shortName: the short name to inspect, e.g. 'm' argument: argument to inspect, e.g. '--max-size=50G'

Implementation

int? byteOption(String longName, String? shortName, String argument) {
  int? rc;
  String? value;
  if (argument == '--$longName') {
    throw OptionException('missing =<count><unit> in $argument');
  } else if (argument.startsWith('--$longName=')) {
    value = argument.substring(longName.length + 3);
  } else if (shortName != null && argument.startsWith('-$shortName')) {
    value = argument.substring(2);
  }
  if (value != null) {
    var matcher = RegExp(r'(\d+)([kmgt]i?)?(b(yte)?)?$', caseSensitive: false)
        .firstMatch(value);
    if (matcher == null) {
      throw OptionException(
          'wrong syntax (<count>[<unit>]) in $argument: examples: 1234321 3G 2TByte 200ki 128mbyte');
    }
    rc = int.parse(matcher.group(1) ?? '');
    var unit = matcher.group(2)?.toLowerCase();
    if (unit != null && unit != '') {
      var factor = unit.length > 1 && unit[1] == 'i' ? 1024 : 1000;
      switch (unit[0]) {
        case 'k':
          rc *= factor;
          break;
        case 'm':
          rc *= factor * factor;
          break;
        case 'g':
          rc *= factor * factor * factor;
          break;
        case 't':
          rc *= factor * factor * factor * factor;
          break;
      }
    }
  }
  return rc;
}