-module(erl_shim). -export([get_table/0, lookup/2, insert_new/2, replace/3]). %% The documentation for the smut module advises the user to call %% `init()` (which ultimately calls this function) early in their %% program and pass out the returned handle to any piece of code that %% needs to instantiate a slot of state. This is the "proper, functional" %% way to do things. %% %% However, it's actually possible to just call `init()` anywhere. This %% function will create the global ETS table for this module if it doesn't %% exist, and will just return a handle to it if it does. %% %% Shhhh. Don't tell the Gleam programmers. get_table() -> case ets:whereis(?MODULE) of undefined -> ets:new(?MODULE, [named_table, public]), ets:insert(?MODULE, {key_counter, 0}), ets:whereis(?MODULE); Ref -> Ref end. lookup(Table, Key) -> case ets:lookup(Table, Key) of [{Key, Value} | _Rest] -> {ok, Value}; _ -> {error, nil} end. insert_new(Table, Value) -> NewKey = ets:update_counter(Table, key_counter, 1), ets:insert(Table, {NewKey, Value}), NewKey. replace(Table, Key, Value) -> ets:insert(Table, {Key, Value}), nil.