Radix.update
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_key, value}
, in case there was a match{original_key}
, in case there was no match
If the callback fun
returns
{:ok, new_key, new_value}
, then new_value will be stored under new_key in the giventree
- anything else will return the
tree
unchanged.
Note that when new_key
differs from matched_key
, the latter is not
deleted from the tree. Because of the longest prefix match, the
matched_key
is provided to the callback fun
.
The main use case is for when dealing with full keys and doing statistics on
some less specific level. If an exact match is required,
Radix.get_and_update/3
might be a better fit.
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 the associated 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
without calling fun
.
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}