Pfx.compare

You're seeing just the function compare, go back to Pfx module for more information.
Link to this function

compare(prefix1, prefix2)

View Source

Specs

compare(prefix(), prefix()) :: :eq | :lt | :gt

Compares prefix1 to prefix2 for sorting purposes.

The result is one of:

  • :eq prefix1 is equal to prefix2
  • :lt prefix1 has a smaller maxlen, more bits or is left of prefix2
  • :gt prefix1 has a larger maxlen, less bits or is right of prefix2

Note that if prefixes are not of the same type, they are compared solely on their maxlen property.

This function enables Enum.sort/2 to be handed the Pfx module to determine how to sort a list of prefixes. When building some sort of acl, use {:desc, Pfx} to sort from less to more specific prefixes.

Examples

iex> compare("10.0.0.0/8", "11.0.0.0/8")
:lt

iex> compare("10.0.0.0/8", {{11, 0, 0, 0}, 8})
:lt

iex> compare({10, 0, 0, 0}, {{11, 0, 0, 0}, 16})
:lt

iex> compare(new(<<10>>, 32), new(<<11>>, 32))
:lt

iex> compare("10.10.10.10", "acdc::1")
:lt

# sort prefixes, ascending (more to less specific)
iex> ["10.11.0.0/16", "10.10.10.0/24", "10.10.0.0/16"]
...> |> Enum.sort(Pfx)
[
  "10.10.10.0/24",
  "10.10.0.0/16",
  "10.11.0.0/16"
]

# sort prefixes, descending (less to more specific)
iex> ["10.11.0.0/16", "10.10.10.0/24", "10.10.0.0/16"]
...> |> Enum.sort({:desc, Pfx})
[
  "10.11.0.0/16",
  "10.10.0.0/16",
  "10.10.10.0/24"
]

# regular sort
iex> ["10.11.0.0/16", "10.10.10.0/24", "10.10.0.0/16"]
...> |> Enum.sort()
[
  "10.10.0.0/16",
  "10.10.10.0/24",
  "10.11.0.0/16"
]

iex> [new(<<10, 11>>, 32), new(<<10,10,10>>, 32), new(<<10,10>>, 32)]
...> |> Enum.sort(Pfx)
[
  %Pfx{bits: <<10, 10, 10>>, maxlen: 32},
  %Pfx{bits: <<10, 10>>, maxlen: 32},
  %Pfx{bits: <<10, 11>>, maxlen: 32}
]

# mixed representations
iex> ["10.11.0.0/16", {{10, 10, 10, 0}, 24}, %Pfx{bits: <<10, 10>>, maxlen: 32}]
...> |> Enum.sort(Pfx)
[
  {{10, 10, 10, 0}, 24},
  %Pfx{bits: <<10, 10>>, maxlen: 32},
  "10.11.0.0/16",
]

# mixed prefix types
iex> ["10.10.10.0/24", "10.10.0.0/16", "acdc::1", "acdc::/32"]
...> |> Enum.sort({:desc, Pfx})
["acdc::/32", "acdc::1", "10.10.0.0/16", "10.10.10.0/24"]