Skip to content

Instantly share code, notes, and snippets.

@leonardb
Created December 31, 2021 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardb/d2f168b61f76e01883dfafe490a42b56 to your computer and use it in GitHub Desktop.
Save leonardb/d2f168b61f76e01883dfafe490a42b56 to your computer and use it in GitHub Desktop.
shq_ets_counters
-module(shq_ets_counters).
-export([init/1,
in/2,
in_r/2,
out/1,
out_r/1,
size/1,
test_in_out/1]).
init(Tab) ->
Ref = ets:new(Tab, [public, set]),
ets:insert(Ref, [{front, 0}, {rear, 0}]),
{ok, Ref}.
in(Ref, Value) ->
true = ets:insert(Ref, {ets:update_counter(Ref, rear, 1) - 1, Value}),
ok.
in_r(Ref, Value) ->
true = ets:insert(Ref, {ets:update_counter(Ref, front, -1), Value}),
ok.
out(Ref) ->
KF = ets:update_counter(Ref, front, 1) - 1,
case ets:take(Ref, KF) of
[{_, V}] ->
{ok, V};
[] ->
%% reset counter
ets:update_counter(Ref, front, -1),
empty
end.
out_r(Ref) ->
KR1 = ets:update_counter(Ref, rear, -1),
case ets:take(Ref, KR1) of
[{_, V}] ->
{ok, V};
[] ->
%% reset counter
ets:update_counter(Ref, rear, 1),
empty
end.
size(Ref) ->
ets:lookup_element(Ref, rear, 2) - ets:lookup_element(Ref, front, 2).
test_in_out(Ref) ->
in(Ref, 0),
out(Ref).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment