Search code examples
listerlangets

Store a list in Erlang ETS


I am trying to insert a list into ETS to pull out later and for some reason it is saying it is a bad arg. I'm not sure if I'm inserting it incorrectly.

Is it just not possible to insert a list into ETS?

The offending line is ets:insert(table, [{parsed_file, UUIDs}]).

Here is the code:

readUUID(Id, Props) ->
    fun () -> 
        %%TableBool = proplists:get_value(table_bool, Props, <<"">>),
        [{_, Parsed}] = ets:lookup(table, parsed_bool),
        case Parsed of
          true  ->
            {uuids, UUIDs} = ets:lookup(table, parsed_bool),
            Index = random:uniform(length(UUIDs)),
            list_to_binary(lists:nth(Index, UUIDs));
          false -> 
            [{_, Dir}] = ets:lookup(table, config_dir),
            File = proplists:get_value(uuid_file, Props, <<"">>),
            UUIDs = parse_file(filename:join([Dir, "config", File])),
            ets:insert(table, [{parsed_file, {uuids, UUIDs}}]),
            ets:insert(table, [{parsed_bool, true}]),
            Index = random:uniform(length(UUIDs)),
            list_to_binary(lists:nth(Index, UUIDs))
        end
    end.

parse_file(File) ->
  {ok, Data} = file:read_file(File),
  parse(Data, []).

parse([], Done) ->
  lists:reverse(Done);

parse(Data, Done) ->
  {Line, Rest} = case re:split(Data, "\n", [{return, list}, {parts, 2}]) of
                   [L,R] -> {L,R};
                   [L]   -> {L,[]}
                 end,
  parse(Rest, [Line|Done]).

Solution

  • If you create the table in the same proc with something like

    ets:new(table, [set, named_table, public]).
    

    then you should be ok. Default permissions are protected, where only creating process can write.