cidr function

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

cidr: the value must be an IP address, / and a prefix length, 0-32 for IPv4 and 0-128 for IPv6, without leading zeros: 10.0.0.0/8, 2001:db8::/32. Host bits may be set: 10.0.0.1/8 passes. {cidr: 'v4'} accepts only IPv4, {cidr: 'v6'} only IPv6. The output is the value as a string.

Implementation

LivrRule cidr(List<Object?> args, RuleContext context) {
  final version = _version(args, 'cidr');
  return (value, allValues) => _check(value, (str) {
    // An address never has "/"
    final slash = str.indexOf('/');
    if (slash == -1) return false;

    final int maxPrefixLength;
    if (version != 6 && _isIPv4(str, 0, slash)) {
      maxPrefixLength = 32;
    } else if (version != 4 && _isIPv6(str, 0, slash)) {
      maxPrefixLength = 128;
    } else {
      return false;
    }
    return _isPrefixLength(str, slash + 1, maxPrefixLength);
  });
}