1%% 2%% %CopyrightBegin% 3%% 4%% Copyright Ericsson AB 2008-2017. All Rights Reserved. 5%% 6%% Licensed under the Apache License, Version 2.0 (the "License"); 7%% you may not use this file except in compliance with the License. 8%% You may obtain a copy of the License at 9%% 10%% http://www.apache.org/licenses/LICENSE-2.0 11%% 12%% Unless required by applicable law or agreed to in writing, software 13%% distributed under the License is distributed on an "AS IS" BASIS, 14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15%% See the License for the specific language governing permissions and 16%% limitations under the License. 17%% 18%% %CopyrightEnd% 19%% 20 21-module(dict_test_lib). 22 23-export([new/2]). 24 25new(Mod, Eq) -> 26 fun (enter, {K,V,D}) -> enter(Mod, K, V, D); 27 (empty, []) -> empty(Mod); 28 (equal, {D1,D2}) -> Eq(D1, D2); 29 (from_list, L) -> from_list(Mod, L); 30 (module, []) -> Mod; 31 (size, D) -> Mod:size(D); 32 (is_empty, D) -> Mod:is_empty(D); 33 (iterator, S) -> Mod:iterator(S); 34 (iterator_from, {Start, S}) -> Mod:iterator_from(Start, S); 35 (next, I) -> Mod:next(I); 36 (to_list, D) -> to_list(Mod, D); 37 (erase, {K,D}) -> erase(Mod, K, D); 38 (take, {K,D}) -> take(Mod, K, D) 39 end. 40 41empty(Mod) -> 42 %% The dict module might not be loaded since it not used by 43 %% anything in the core parts of Erlang/OTP. 44 {module,Mod} = code:ensure_loaded(Mod), 45 case erlang:function_exported(Mod, new, 0) of 46 false -> Mod:empty(); 47 true -> Mod:new() 48 end. 49 50to_list(Mod, D) -> 51 Mod:to_list(D). 52 53from_list(Mod, L) -> 54 {module,Mod} = code:ensure_loaded(Mod), 55 case erlang:function_exported(Mod, from_orddict, 1) of 56 false -> 57 Mod:from_list(L); 58 true -> 59 %% The gb_trees module has no from_list/1 function. 60 %% 61 %% The keys in S are not unique. To make sure 62 %% that we pick the same key/value pairs as 63 %% dict/orddict, first convert the list to an orddict. 64 Orddict = orddict:from_list(L), 65 Mod:from_orddict(Orddict) 66 end. 67 68%% Store new value into dictionary or update previous value in dictionary. 69enter(Mod, Key, Val, Dict) -> 70 {module,Mod} = code:ensure_loaded(Mod), 71 case erlang:function_exported(Mod, store, 3) of 72 false -> 73 Mod:enter(Key, Val, Dict); 74 true -> 75 Mod:store(Key, Val, Dict) 76 end. 77 78erase(Mod, Key, Val) when Mod =:= dict; Mod =:= orddict -> 79 Mod:erase(Key, Val); 80erase(gb_trees, Key, Val) -> 81 gb_trees:delete_any(Key, Val). 82 83take(gb_trees, Key, Val) -> 84 Res = try 85 gb_trees:take(Key, Val) 86 catch 87 error:_ -> 88 error 89 end, 90 Res = gb_trees:take_any(Key, Val); 91take(Mod, Key, Val) -> 92 Mod:take(Key, Val). 93