aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Whatmore <tom@whatmore.me>2020-06-19 11:21:20 +0100
committerLouis Pilfold <louis@lpil.uk>2020-06-30 12:15:19 +0100
commit341eb947b4f3f33ea2bf700f629d328444b1df3f (patch)
treea10d7ab1dc7ced900e3ac7415c48bc975f0bd051
parent82e36cf181e55194c537c12ca0824338044ce0d3 (diff)
downloadgleam_stdlib-341eb947b4f3f33ea2bf700f629d328444b1df3f.tar.gz
gleam_stdlib-341eb947b4f3f33ea2bf700f629d328444b1df3f.zip
Add utf_codepoint to stdlib
-rw-r--r--src/gleam/utf_codepoint.gleam20
-rw-r--r--test/utf_codepoint_test.gleam16
2 files changed, 36 insertions, 0 deletions
diff --git a/src/gleam/utf_codepoint.gleam b/src/gleam/utf_codepoint.gleam
new file mode 100644
index 0000000..2c3cb04
--- /dev/null
+++ b/src/gleam/utf_codepoint.gleam
@@ -0,0 +1,20 @@
+import gleam/result
+
+pub type UtfCodepoint = UtfCodepoint
+
+pub type Error {
+ Invalid
+}
+
+external fn int_to_utf8_codepoint(Int) -> UtfCodepoint =
+ "gleam_stdlib" "identity"
+
+pub fn from_int(value: Int) -> Result(UtfCodepoint, Error) {
+ case value {
+ i if i > 1114111 -> Error(Invalid)
+ i if i == 65534 -> Error(Invalid)
+ i if i == 65535 -> Error(Invalid)
+ i if i >= 55296 && i <= 57343 -> Error(Invalid)
+ i -> Ok(int_to_utf8_codepoint(i))
+ }
+}
diff --git a/test/utf_codepoint_test.gleam b/test/utf_codepoint_test.gleam
new file mode 100644
index 0000000..a3747ba
--- /dev/null
+++ b/test/utf_codepoint_test.gleam
@@ -0,0 +1,16 @@
+import gleam/should
+import gleam/utf_codepoint
+
+pub fn from_int_test() {
+ utf_codepoint.from_int(1114444)
+ |> should.be_error
+
+ utf_codepoint.from_int(65534)
+ |> should.be_error
+
+ utf_codepoint.from_int(55296)
+ |> should.be_error
+
+ assert Ok(snake) = utf_codepoint.from_int(128013)
+ should.equal(<<snake:utf8_codepoint>>, <<"🐍":utf8>>)
+}