Skip to content

Commit 341eb94

Browse files
tomwhatmorelpil
authored andcommitted
Add utf_codepoint to stdlib
1 parent 82e36cf commit 341eb94

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/gleam/utf_codepoint.gleam

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import gleam/result
2+
3+
pub type UtfCodepoint = UtfCodepoint
4+
5+
pub type Error {
6+
Invalid
7+
}
8+
9+
external fn int_to_utf8_codepoint(Int) -> UtfCodepoint =
10+
"gleam_stdlib" "identity"
11+
12+
pub fn from_int(value: Int) -> Result(UtfCodepoint, Error) {
13+
case value {
14+
i if i > 1114111 -> Error(Invalid)
15+
i if i == 65534 -> Error(Invalid)
16+
i if i == 65535 -> Error(Invalid)
17+
i if i >= 55296 && i <= 57343 -> Error(Invalid)
18+
i -> Ok(int_to_utf8_codepoint(i))
19+
}
20+
}

test/utf_codepoint_test.gleam

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import gleam/should
2+
import gleam/utf_codepoint
3+
4+
pub fn from_int_test() {
5+
utf_codepoint.from_int(1114444)
6+
|> should.be_error
7+
8+
utf_codepoint.from_int(65534)
9+
|> should.be_error
10+
11+
utf_codepoint.from_int(55296)
12+
|> should.be_error
13+
14+
assert Ok(snake) = utf_codepoint.from_int(128013)
15+
should.equal(<<snake:utf8_codepoint>>, <<"🐍":utf8>>)
16+
}

0 commit comments

Comments
 (0)