emqx_utils_ets.erl 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2018-2023 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_utils_ets).
  17. -export([
  18. new/1,
  19. new/2
  20. ]).
  21. -export([
  22. lookup_value/2,
  23. lookup_value/3
  24. ]).
  25. -export([delete/1]).
  26. %% Create an ets table.
  27. -spec new(atom()) -> ok.
  28. new(Tab) ->
  29. new(Tab, []).
  30. %% Create a named_table ets.
  31. -spec new(atom(), list()) -> ok.
  32. new(Tab, Opts) ->
  33. case ets:info(Tab, name) of
  34. undefined ->
  35. _ = ets:new(Tab, lists:usort([named_table | Opts])),
  36. ok;
  37. Tab ->
  38. ok
  39. end.
  40. %% KV lookup
  41. -spec lookup_value(ets:tab(), term()) -> any().
  42. lookup_value(Tab, Key) ->
  43. lookup_value(Tab, Key, undefined).
  44. -spec lookup_value(ets:tab(), term(), any()) -> any().
  45. lookup_value(Tab, Key, Def) ->
  46. try
  47. ets:lookup_element(Tab, Key, 2)
  48. catch
  49. error:badarg -> Def
  50. end.
  51. %% Delete the ets table.
  52. -spec delete(ets:tab()) -> ok.
  53. delete(Tab) ->
  54. case ets:info(Tab, name) of
  55. undefined ->
  56. ok;
  57. Tab ->
  58. ets:delete(Tab),
  59. ok
  60. end.