From a9703589ba24c29ad3674e06ec877dcd19ec9402 Mon Sep 17 00:00:00 2001 From: "John R. Daily" Date: Tue, 4 Aug 2015 16:50:09 -0400 Subject: [PATCH 1/2] Safe mechanism for converting strings to existing atoms --- src/cuttlefish_datatypes.erl | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/cuttlefish_datatypes.erl b/src/cuttlefish_datatypes.erl index 4a823e12..91b6af95 100644 --- a/src/cuttlefish_datatypes.erl +++ b/src/cuttlefish_datatypes.erl @@ -193,10 +193,18 @@ to_string(Value, MaybeExtendedDatatype) -> {error, {type, {Value, MaybeExtendedDatatype}}} end. --spec from_string(term(), datatype()) -> term() | cuttlefish_error:error(). +-spec from_string(term(), datatype()|'existing_atom') -> term() | cuttlefish_error:error(). from_string(Atom, atom) when is_atom(Atom) -> Atom; from_string(String, atom) when is_list(String) -> list_to_atom(String); +from_string(String, existing_atom) when is_list(String) -> + try + list_to_existing_atom(String) + catch + error:badarg -> + {error, {conversion, {String, atom}}} + end; + from_string(Value, {enum, Enum}) -> cuttlefish_enum:parse(Value, {enum, Enum}); @@ -338,7 +346,12 @@ to_string_unsupported_datatype_test() -> from_string_atom_test() -> ?assertEqual(split_the, from_string(split_the, atom)), - ?assertEqual(split_the, from_string("split_the", atom)). + ?assertEqual(split_the, from_string("split_the", atom)), + ?assertMatch({error, {conversion, _}}, from_string("unknown_atom_to_explode_table", existing_atom)), + %% Using `assertEqual' as above introduces the atom to be created, + %% so they don't actually test that the following works for + %% unknown atoms. + ?assert(is_atom(from_string("unknown_atom_to_explode_table", atom))). from_string_integer_test() -> ?assertEqual(32, from_string(32, integer)), From 8ac7a941f00d3b14939a87282d1a58927160f8c2 Mon Sep 17 00:00:00 2001 From: "John R. Daily" Date: Wed, 5 Aug 2015 13:35:49 -0400 Subject: [PATCH 2/2] Awkward grammar is awkward --- src/cuttlefish_datatypes.erl | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cuttlefish_datatypes.erl b/src/cuttlefish_datatypes.erl index 91b6af95..ab7d5d51 100644 --- a/src/cuttlefish_datatypes.erl +++ b/src/cuttlefish_datatypes.erl @@ -349,8 +349,7 @@ from_string_atom_test() -> ?assertEqual(split_the, from_string("split_the", atom)), ?assertMatch({error, {conversion, _}}, from_string("unknown_atom_to_explode_table", existing_atom)), %% Using `assertEqual' as above introduces the atom to be created, - %% so they don't actually test that the following works for - %% unknown atoms. + %% so they don't actually test that unknown atoms work properly. ?assert(is_atom(from_string("unknown_atom_to_explode_table", atom))). from_string_integer_test() ->