# Pfx.compare

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

# compare(pfx1, pfx2)

View Source

## Specs

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

Compares `pfx1` to `pfx2` for sorting purposes.

The result is one of:

• `:eq` prefix1 is equal to prefix2
• `:lt` prefix1 has more bits or lies to the left of prefix2
• `:gt` prefix1 has less bits or lies to the right of prefix2

The prefixes must have the same maxlen and are first compared by size (i.e. a shorter prefix is considered larger), and second on their bitstring value.

## 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

# sort on prefixes, first on bit_size than bits-values

iex> list = ["10.11.0.0/16", "10.10.10.0/24", "10.10.0.0/16"]
iex> Enum.sort(list, Pfx)
[
"10.10.10.0/24",
"10.10.0.0/16",
"10.11.0.0/16"
]
# whereas regular sort does:
#
iex> Enum.sort(list)
[
"10.10.0.0/16",
"10.10.10.0/24",
"10.11.0.0/16"
]

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

# not advisable, but mixed representations are possible as well
iex> l = ["10.11.0.0/16", {{10, 10, 10, 0}, 24}, %Pfx{bits: <<10, 10>>, maxlen: 32}]
iex> Enum.sort(l, Pfx)
[
{{10, 10, 10, 0}, 24},
%Pfx{bits: <<10, 10>>, maxlen: 32},
"10.11.0.0/16",
]

# note: all prefixes must have the same `maxlen`
iex> compare(new(<<10>>, 32), new(<<10>>, 128))
** (ArgumentError) prefixes have different maxlen's: {%Pfx{bits: "\n", maxlen: 32}, %Pfx{bits: "\n", maxlen: 128}}``````