|
| 1 | +import gleam/dynamic |
| 2 | +import gleam/dynamic/decode |
| 3 | + |
1 | 4 | /// Atom is a special string-like data-type that is most commonly used for |
2 | 5 | /// interfacing with code written in other BEAM languages such as Erlang and |
3 | 6 | /// Elixir. It is preferable to define your own custom types to use instead of |
@@ -47,3 +50,32 @@ pub fn create(a: String) -> Atom |
47 | 50 | /// |
48 | 51 | @external(erlang, "erlang", "atom_to_binary") |
49 | 52 | pub fn to_string(a: Atom) -> String |
| 53 | + |
| 54 | +/// Convert an atom to a dynamic value, throwing away the type information. |
| 55 | +/// |
| 56 | +/// This may be useful for testing decoders. |
| 57 | +/// |
| 58 | +@external(erlang, "gleam_erlang_ffi", "identity") |
| 59 | +pub fn to_dynamic(a: Atom) -> dynamic.Dynamic |
| 60 | + |
| 61 | +@external(erlang, "gleam_erlang_ffi", "identity") |
| 62 | +pub fn cast_from_dynamic(a: dynamic.Dynamic) -> Atom |
| 63 | + |
| 64 | +/// A dynamic decoder for atoms. |
| 65 | +/// |
| 66 | +/// You almost certainly should not use this to work with externally defined |
| 67 | +/// functions. They return known types, so you should define the external |
| 68 | +/// functions with the correct types, defining wrapper functions in Erlang if |
| 69 | +/// the external types cannot be mapped directly onto Gleam types. |
| 70 | +/// |
| 71 | +pub fn decoder() -> decode.Decoder(Atom) { |
| 72 | + decode.new_primitive_decoder("Atom", fn(data) { |
| 73 | + case is_atom(data) { |
| 74 | + True -> Ok(cast_from_dynamic(data)) |
| 75 | + False -> Error(create("nil")) |
| 76 | + } |
| 77 | + }) |
| 78 | +} |
| 79 | + |
| 80 | +@external(erlang, "erlang", "is_atom") |
| 81 | +fn is_atom(data: dynamic.Dynamic) -> Bool |
0 commit comments