mac function

LivrRule mac(
  1. List<Object?> args,
  2. RuleContext context
)

mac: the value must be a MAC address, six pairs of hexadecimal digits (48 bits, MAC-48 or EUI-48) separated by : or by -, the same separator everywhere: 00:1A:2b:3c:4D:5e. {mac: 64} takes eight pairs (EUI-64). The output is the value as a string.

Implementation

LivrRule mac(List<Object?> args, RuleContext context) {
  // Arguments after the first one are ignored. A string with a number is
  // the number
  final arg = args.isEmpty ? 48 : args[0];
  final bits = _numberArg(arg);
  if (bits != 48 && bits != 64) {
    throw LivrSchemaException(
      'Rule [mac] expects no arguments, 48 or 64, got [$arg]',
    );
  }

  // Pairs and separators: 6 pairs are 17 characters, 8 pairs 23
  final length = bits == 48 ? 17 : 23;
  return (value, allValues) => _check(value, (str) {
    if (str.length != length) return false;

    final separator = str.codeUnitAt(2);
    if (separator != 0x3A && separator != 0x2D) return false; // ":" or "-"
    for (var i = 0; i < length; i++) {
      final char = str.codeUnitAt(i);
      if (i % 3 == 2) {
        if (char != separator) return false;
      } else if (!_isHexChar(char)) {
        return false;
      }
    }
    return true;
  });
}