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
67
68
69
70
71
72
73
74
75
76
|
# Copyright 2019 Hubert Chathi <hubert@uhoreg.ca>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule Polyjuice.Client.Storage.Ets do
@moduledoc """
Storage using Erlang [ets](http://erlang.org/doc/man/ets.html). This should
only be used for testing.
"""
defstruct [
:table
]
def open() do
table = :ets.new(:polyjuice_client, [])
%__MODULE__{
table: table
}
end
defimpl Polyjuice.Client.Storage, for: __MODULE__ do
def close(%{table: table}) do
:ets.delete_all_objects(table)
end
def get_sync_token(%{table: table}) do
case :ets.lookup(table, :sync_token) do
[sync_token: token] -> token
_ -> nil
end
end
def set_sync_token(%{table: table}, token) do
:ets.insert(table, {:sync_token, token})
end
def set_filter_id(%{table: table}, filter, id) when is_map(filter) and is_binary(id) do
{:ok, json} = Polyjuice.Util.JSON.canonical_json(filter)
hash = :crypto.hash(:sha256, json)
:ets.insert(table, {"filter_" <> hash, id})
end
def get_filter_id(%{table: table}, filter) do
{:ok, json} = Polyjuice.Util.JSON.canonical_json(filter)
hash = :crypto.hash(:sha256, json)
case :ets.lookup(table, "filter_" <> hash) do
[{_, id}] -> id
_ -> nil
end
end
def kv_put(%{table: table}, key, value) when is_binary(key) do
:ets.insert(table, {"kv_" <> key, value})
end
def kv_get(%{table: table}, key, default \\ nil) when is_binary(key) do
case :ets.lookup(table, "kv_" <> key) do
[{_, value}] -> value
_ -> default
end
end
end
end
|