diff options
-rw-r--r-- | src/gleam/dynamic.gleam | 40 |
1 files changed, 26 insertions, 14 deletions
diff --git a/src/gleam/dynamic.gleam b/src/gleam/dynamic.gleam index 4fbee8b..2b7aea2 100644 --- a/src/gleam/dynamic.gleam +++ b/src/gleam/dynamic.gleam @@ -27,33 +27,45 @@ pub external fn from(a) -> Dynamic = pub external fn unsafe_coerce(Dynamic) -> a = "gleam_stdlib" "identity" -/// Check to see whether a Dynamic value is a bit_string, and return the bit_string if +external fn erl_string(from: Dynamic) -> Result(BitString, String) = + "gleam_stdlib" "decode_string" + +/// Check to see whether a Dynamic value is a string, and return the string if /// it is. /// /// ## Examples /// -/// > bit_string(from("Hello")) == bit_string.from_string("Hello") -/// True +/// > string(from("Hello")) +/// Ok("Hello") /// -/// > bit_string(from(123)) -/// Error("Expected a BitString, got `123`") +/// > string(from(123)) +/// Error("Expected a String, got `123`") /// -pub external fn bit_string(from: Dynamic) -> Result(BitString, String) = - "gleam_stdlib" "decode_bit_string" +pub fn string(from: Dynamic) -> Result(String, String) { + erl_string(from) + |> result.then( + fn(raw) { + case bit_string.is_utf8(raw) { + True -> Ok(raw) + False -> Error("Expected a string, got a bit_string") + } + }, + ) +} -/// Check to see whether a Dynamic value is a string, and return the string if +/// Check to see whether a Dynamic value is a bit_string, and return the bit_string if /// it is. /// /// ## Examples /// -/// > string(from("Hello")) -/// Ok("Hello") +/// > bit_string(from("Hello")) == bit_string.from_string("Hello") +/// True /// -/// > string(from(123)) -/// Error("Expected a String, got `123`") +/// > bit_string(from(123)) +/// Error("Expected a BitString, got `123`") /// -pub external fn string(from: Dynamic) -> Result(String, String) = - "gleam_stdlib" "decode_string" +pub external fn bit_string(from: Dynamic) -> Result(BitString, String) = + "gleam_stdlib" "decode_bit_string" /// Check to see whether a Dynamic value is an int, and return the int if it /// is. |