Pfx.to_tuple
You're seeing just the function
to_tuple
, go back to Pfx module for more information.
Specs
Returns a prefix
in the form of a tuple, with or without mask.
The options include:
:mask
whether to apply and include the mask (i.e. prefix length):width
how many bits in an address part (default depends)
The :width
defaults to 8
, except when maxlen is 128, in which case it is 16
.
These defaults are a good fit for IPv4, IPv6, EUI48 and EUI64 prefixes and produces
a tuple representation that can easily be converted back into a Pfx.t/0
struct
if the need arises.
Examples
iex> to_tuple("1.1.1.0/24")
{{1, 1, 1, 0}, 24}
# mask is applied by default
iex> to_tuple("1.1.1.12/24")
{{1, 1, 1, 0}, 24}
# unless :mask option is false
iex> to_tuple("1.1.1.12/24", mask: false)
{1, 1, 1, 12}
# converts other formats of IPv4/6 and EUI48/64 as well
iex> to_tuple({1, 1, 1, 12})
{{1, 1, 1, 12}, 32}
iex> to_tuple(%Pfx{bits: <<1, 1, 1, 12>>, maxlen: 32})
{{1, 1, 1, 12}, 32}
iex> to_tuple("acdc:1976::/32")
{{0xacdc, 0x1976, 0, 0, 0, 0, 0, 0}, 32}
# convert back
iex> to_tuple("acdc:1976::/32")
...> |> new()
%Pfx{bits: <<0xacdc::size(16), 0x1976::size(16)>>, maxlen: 128}
For other types of prefixes, use the :width
option to override how many bits
go into an address part. If the prefix has a maxlen that is not the number
of address digits * their width, maxlen will need to be known when converting
the tuple representation back into a Pfx.t/0
struct (since it cannot be
deduced).
# maxlen is 30 bits, not 8*4
iex> to_tuple(%Pfx{bits: <<0x12, 0x34, 0x56>>, maxlen: 30}, width: 4)
{{1, 2, 3, 4, 5, 6, 0, 0}, 24}
# conversion back into a Pfx struct requires `width` and `maxlen` to be known
iex> pfx = %Pfx{bits: <<0x12, 0x34, 0x56>>, maxlen: 30}
iex> {parts, pfxlen} = to_tuple(pfx, width: 4)
iex> bits = for x <- Tuple.to_list(parts), into: <<>>, do: <<x::size(4)>>
iex> new(bits, 30)
...> |> keep(pfxlen)
%Pfx{bits: <<0x12, 0x34, 0x56>>, maxlen: 30}
# or less convoluted
iex> pfx = %Pfx{bits: <<0x12, 0x34, 0x56>>, maxlen: 30}
iex> to_tuple(pfx, width: 4)
...> |> undigits(4)
...> |> new(30)
%Pfx{bits: <<0x12, 0x34, 0x56>>, maxlen: 30}