Skip to content

Instantly share code, notes, and snippets.

@mururu
Last active February 17, 2016 12:45
Show Gist options
  • Save mururu/9705cc01db37c012fa70 to your computer and use it in GitHub Desktop.
Save mururu/9705cc01db37c012fa70 to your computer and use it in GitHub Desktop.
-module(fifocache).
-export([new/1, push/3, lookup/2]).
%%-----------------------------------------
%% FIFO cache
%%
%% - Representation
%%
%% {Map, Array, Size, Bottom, Top, NewFlag}
%%
%% - Usage
%%
%% Cache = ffcache:new(10).
%% Cache0 = ffcache:put(key0, value0, Cache).
%% value0 = ffcache:lookup(key0, Cache0).
%% not_found = ffcache:lookup(key1, Cache0).
%%
-type fifocache() :: {array:array(), map(), non_neg_integer(),
non_neg_integer(), non_neg_integer(), boolean()}.
-spec new(Size :: non_neg_integer()) -> fifocache().
new(Size) ->
{maps:new(), array:new(Size), Size, 0, 0, true}.
-spec push(term(), term(), fifocache()) -> fifocache().
push(Key, Value, {Map, Array, Size, Bottom, Top, false}) when Bottom == Top ->
RemoveKey = array:get(Top, Array),
Map0 = maps:remove(RemoveKey, Map),
{maps:put(Key, Value, Map0), array:set(Top, Key, Array),
Size, (Bottom + 1) rem Size, (Top + 1) rem Size, false};
push(Key, Value, {Map, Array, Size, Bottom, Top, _}) ->
{maps:put(Key, Value, Map), array:set(Top, Key, Array),
Size, Bottom, (Top + 1) rem Size, false}.
-spec lookup(term(), fifocache()) -> term() | not_found.
lookup(Key, {Map, _, _, _, _, _}) ->
case maps:find(Key, Map) of
{ok, Value} ->
Value;
error ->
not_found
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment