Radix.update
You're seeing just the function
update
, go back to Radix module for more information.
Specs
Updates a key,value-pair in tree
by invoking fun
after a longest prefix
match lookup.
After a longest prefix match lookup for given search key
, the callback fun
is called with:
{:matched, matching_key, value}
, in case there was a match{:nomatch, original_key}
, in case there was no match
If the callback fun
returns {:ok, key, value}
, then value will be stored
under key in the given tree
. Anything else will return the tree
unchanged.
Examples
iex> max24bits = fn key when bit_size(key) > 24 ->
...> <<bits::bitstring-size(24), _::bitstring>> = key; <<bits::bitstring>>
...> key -> key
...> end
iex>
iex> counter = fn {k, v} -> {:ok, k, v + 1}
...> {k} -> {:ok, max24bits.(k), 1}
...> end
iex> new()
...> |> update(<<1, 1, 1, 1>>, counter)
...> |> update(<<1, 1, 1, 128>>, counter)
...> |> update(<<1, 1, 1, 255>>, counter)
{0, [{<<1, 1, 1>>, 3}], nil}
# only interested in known prefixes
iex> counter = fn {k, v} -> {:ok, k, v + 1}
...> _discard -> nil
...> end
iex> new()
...> |> put(<<1, 1, 1>>, 0)
...> |> update(<<1, 1, 1, 1>>, counter)
...> |> update(<<1, 1, 1, 2>>, counter)
...> |> update(<<2, 2, 2, 2>>, counter)
{0, [{<<1, 1, 1>>, 2}], nil}
Specs
Looks up the longest prefix match for given search key
in tree
and
updates its value through fun
.
If key
has a longest prefix match in tree
then its value is passed to
fun
and its result is used as the updated value of the matching key. If
key
cannot be matched the {key
, default
}-pair is inserted in
the tree
.
Example
iex> t = new()
iex> t = update(t, <<1, 1, 1>>, 1, fn x -> x+1 end)
iex> t
{0, [{<<1, 1, 1>>, 1}], nil}
iex> t = update(t, <<1, 1, 1, 0>>, 1, fn x -> x+1 end)
iex> t
{0, [{<<1, 1, 1>>, 2}], nil}
iex> t = update(t, <<1, 1, 1, 255>>, 1, fn x -> x+1 end)
iex> t
{0, [{<<1, 1, 1>>, 3}], nil}