diff options
author | Peter Saxton <peterhsaxton@gmail.com> | 2020-07-01 07:45:05 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2020-07-01 18:52:36 +0100 |
commit | 70f29008bc77c97c71cacf3914de2596d6f97f18 (patch) | |
tree | c2935529defa36681b7f40d4f401ba1cdd98fc99 /src | |
parent | ca533234fc4b36029cd42b4cf6f7b716b961965c (diff) | |
download | gleam_stdlib-70f29008bc77c97c71cacf3914de2596d6f97f18.tar.gz gleam_stdlib-70f29008bc77c97c71cacf3914de2596d6f97f18.zip |
add cast
Diffstat (limited to 'src')
-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. |