feat(emqx): add `emqx_inflight:fold/3` generic function

This commit is contained in:
Andrew Mayorov 2023-07-20 20:13:09 +02:00
parent 596ce157fd
commit f022c9b1a4
No known key found for this signature in database
GPG Key ID: 2837C62ACFBFED5D
2 changed files with 24 additions and 0 deletions

View File

@ -28,6 +28,7 @@
update/3,
resize/2,
delete/2,
fold/3,
values/1,
to_list/1,
to_list/2,
@ -77,6 +78,18 @@ delete(Key, ?INFLIGHT(MaxSize, Tree)) ->
update(Key, Val, ?INFLIGHT(MaxSize, Tree)) ->
?INFLIGHT(MaxSize, gb_trees:update(Key, Val, Tree)).
-spec fold(fun((key(), Val :: term(), Acc) -> Acc), Acc, inflight()) -> Acc.
fold(FoldFun, AccIn, ?INFLIGHT(Tree)) ->
fold_iterator(FoldFun, AccIn, gb_trees:iterator(Tree)).
fold_iterator(FoldFun, Acc, It) ->
case gb_trees:next(It) of
{Key, Val, ItNext} ->
fold_iterator(FoldFun, FoldFun(Key, Val, Acc), ItNext);
none ->
Acc
end.
-spec resize(integer(), inflight()) -> inflight().
resize(MaxSize, ?INFLIGHT(Tree)) ->
?INFLIGHT(MaxSize, Tree).

View File

@ -76,6 +76,17 @@ t_values(_) ->
?assertEqual([1, 2], emqx_inflight:values(Inflight)),
?assertEqual([{a, 1}, {b, 2}], emqx_inflight:to_list(Inflight)).
t_fold(_) ->
Inflight = maps:fold(
fun emqx_inflight:insert/3,
emqx_inflight:new(),
#{a => 1, b => 2, c => 42}
),
?assertEqual(
emqx_inflight:fold(fun(_, V, S) -> S + V end, 0, Inflight),
lists:foldl(fun({_, V}, S) -> S + V end, 0, emqx_inflight:to_list(Inflight))
).
t_is_full(_) ->
Inflight = emqx_inflight:insert(k, v, emqx_inflight:new()),
?assertNot(emqx_inflight:is_full(Inflight)),