Skip to content

Instantly share code, notes, and snippets.

@mururu
Last active February 17, 2016 12:45
Show Gist options
  • Select an option

  • Save mururu/9705cc01db37c012fa70 to your computer and use it in GitHub Desktop.

Select an option

Save mururu/9705cc01db37c012fa70 to your computer and use it in GitHub Desktop.

Revisions

  1. Yuki Ito revised this gist Feb 17, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion fifocache.erl
    Original file line number Diff line number Diff line change
    @@ -7,7 +7,7 @@
    %%
    %% - Representation
    %%
    %% {Map, Array, Bottom, Top, NewFlag}
    %% {Map, Array, Size, Bottom, Top, NewFlag}
    %%
    %% - Usage
    %%
  2. Yuki Ito created this gist Feb 17, 2016.
    44 changes: 44 additions & 0 deletions fifocache.erl
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    -module(fifocache).

    -export([new/1, push/3, lookup/2]).

    %%-----------------------------------------
    %% FIFO cache
    %%
    %% - Representation
    %%
    %% {Map, Array, 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.