-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_cache.erl
66 lines (45 loc) · 1.41 KB
/
gen_cache.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-module (gen_cache).
-behaviour (gen_server).
-export([start_link/0, add/2, remove/1, get/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {dict}).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
add(Key, Value) ->
gen_server:cast(?MODULE, {add, Key, Value}).
remove(Key) ->
gen_server:cast(?MODULE, {remove, Key}).
get(Key) ->
gen_server:call(?MODULE, {get, Key}).
init([]) ->
io:format("Starting ~p~n", [?MODULE]),
{ok, #state{dict=dict:new()}}.
%% Add and Remove CASTS!!!
handle_cast({add, Key, Value}, State) ->
#state{dict=Dictionary} = State,
NewState = State#state{dict=dict:store(Key, Value, Dictionary)},
{noreply, NewState};
handle_cast({remove, Key}, State) ->
#state{dict=Dictionary} = State,
NewState = State#state{dict=dict:erase(Key, Dictionary)},
{noreply, NewState};
handle_cast(_Msg, State) ->
{noreply, State}.
%% Get CALLS!!!
handle_call({get, Key}, _From, State) ->
#state{dict=Dictionary} = State,
case dict:find(Key, Dictionary) of
error ->
{reply, {error, not_found}, State};
{ok, Value} ->
{reply, Value, State}
end;
handle_call(_Request, _From, State) ->
{reply, ignored, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.