Skip to content

Commit 725e96b

Browse files
tomwhatmorelpil
authored andcommitted
Move UtfCodepoint functionality into string module
1 parent c3c2284 commit 725e96b

File tree

4 files changed

+35
-38
lines changed

4 files changed

+35
-38
lines changed

src/gleam/string.gleam

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ import gleam/result
1010
pub type String =
1111
String
1212

13+
/// A UtfCodepoint is the integer representation of a valid UTF codepoint
14+
pub type UtfCodepoint =
15+
UtfCodepoint
16+
1317
/// Determine if a string is empty.
1418
///
1519
/// ## Examples
@@ -451,3 +455,20 @@ pub fn to_graphemes(string: String) -> List(String) {
451455
_ -> []
452456
}
453457
}
458+
459+
external fn int_to_utf_codepoint(Int) -> UtfCodepoint =
460+
"gleam_stdlib" "identity"
461+
462+
/// Convert an integer to a UtfCodepoint
463+
///
464+
/// Returns an error if the integer does not represent a valid UTF codepoint.
465+
///
466+
pub fn utf_codepoint(value: Int) -> Result(UtfCodepoint, Nil) {
467+
case value {
468+
i if i > 1114111 -> Error(Nil)
469+
i if i == 65534 -> Error(Nil)
470+
i if i == 65535 -> Error(Nil)
471+
i if i >= 55296 && i <= 57343 -> Error(Nil)
472+
i -> Ok(int_to_utf_codepoint(i))
473+
}
474+
}

src/gleam/utf_codepoint.gleam

Lines changed: 0 additions & 22 deletions
This file was deleted.

test/gleam/string_test.gleam

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,3 +295,17 @@ pub fn to_graphemes_test() {
295295
|> string.to_graphemes()
296296
|> should.equal([])
297297
}
298+
299+
pub fn utf_codepoint_test() {
300+
string.utf_codepoint(1114444)
301+
|> should.be_error
302+
303+
string.utf_codepoint(65534)
304+
|> should.be_error
305+
306+
string.utf_codepoint(55296)
307+
|> should.be_error
308+
309+
assert Ok(snake) = string.utf_codepoint(128013)
310+
should.equal(<<snake:utf8_codepoint>>, <<"🐍":utf8>>)
311+
}

test/utf_codepoint_test.gleam

Lines changed: 0 additions & 16 deletions
This file was deleted.

0 commit comments

Comments
 (0)