Skip to content

Commit 9789d26

Browse files
committed
Fix slice
Closes gleam-lang/gleam#3499
1 parent 1962bea commit 9789d26

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
where the `Intl` API is not supported.
2020
- Fixed a bug where the behaviour of `uri.percent_decode` would decode `+` as a
2121
space on JavaScript.
22+
- Fixed a bug where `string.slice` could return invalid values on Erlang.
2223

2324
## v0.39.0 - 2024-07-09
2425

src/gleam/string.gleam

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ pub fn slice(from string: String, at_index idx: Int, length len: Int) -> String
230230
}
231231
}
232232

233-
@external(erlang, "string", "slice")
233+
@external(erlang, "gleam_stdlib", "slice")
234234
fn do_slice(string: String, idx: Int, len: Int) -> String {
235235
string
236236
|> to_graphemes

src/gleam_stdlib.erl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
decode_tuple5/1, decode_tuple6/1, tuple_get/2, classify_dynamic/1, print/1,
1515
println/1, print_error/1, println_error/1, inspect/1, float_to_string/1,
1616
int_from_base_string/2, utf_codepoint_list_to_string/1, contains_string/2,
17-
crop_string/2, base16_decode/1, string_replace/3, regex_replace/3
17+
crop_string/2, base16_decode/1, string_replace/3, regex_replace/3, slice/3
1818
]).
1919

2020
%% Taken from OTP's uri_string module
@@ -547,3 +547,9 @@ base16_decode(String) ->
547547

548548
string_replace(String, Pattern, Replacement) ->
549549
string:replace(String, Pattern, Replacement, all).
550+
551+
slice(String, Index, Length) ->
552+
case string:slice(String, Index, Length) of
553+
X when is_binary(X) -> X;
554+
X when is_list(X) -> unicode:characters_to_binary(X)
555+
end.

test/gleam/string_test.gleam

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,13 @@ pub fn drop_left_test() {
465465
|> should.equal("gleam")
466466
}
467467

468+
pub fn drop_left_3499_test() {
469+
// https://github.com/gleam-lang/gleam/issues/3499
470+
"\r]"
471+
|> string.drop_left(1)
472+
|> should.equal("]")
473+
}
474+
468475
pub fn drop_right_test() {
469476
"gleam"
470477
|> string.drop_right(up_to: 2)

0 commit comments

Comments
 (0)