From d8ee74f5d31c0ecfba08d375a4d5229776032eac Mon Sep 17 00:00:00 2001 From: Malo <57839069+MDLC01@users.noreply.github.com> Date: Thu, 3 Jul 2025 22:47:11 +0100 Subject: [PATCH 1/2] Add `default` argument for `str.first` and `str.last` --- crates/typst-library/src/foundations/str.rs | 26 ++++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/typst-library/src/foundations/str.rs b/crates/typst-library/src/foundations/str.rs index 23a1bd4cf..015716b94 100644 --- a/crates/typst-library/src/foundations/str.rs +++ b/crates/typst-library/src/foundations/str.rs @@ -178,25 +178,39 @@ impl Str { self.0.len() } - /// Extracts the first grapheme cluster of the string. - /// Fails with an error if the string is empty. + /// Extracts the first grapheme cluster of the string. Fails with an error + /// if the string is empty. Returns the default value if the string is empty + /// or fails with an error is no default value was specified. #[func] - pub fn first(&self) -> StrResult { + pub fn first( + &self, + /// A default value to return if the string is empty. + #[named] + default: Option, + ) -> StrResult { self.0 .graphemes(true) .next() .map(Into::into) + .or(default) .ok_or_else(string_is_empty) } - /// Extracts the last grapheme cluster of the string. - /// Fails with an error if the string is empty. + /// Extracts the last grapheme cluster of the string. Fails with an error if + /// the string is empty. Returns the default value if the string is empty or + /// fails with an error is no default value was specified. #[func] - pub fn last(&self) -> StrResult { + pub fn last( + &self, + /// A default value to return if the string is empty. + #[named] + default: Option, + ) -> StrResult { self.0 .graphemes(true) .next_back() .map(Into::into) + .or(default) .ok_or_else(string_is_empty) } From dabef054883e95bc35444af369fd6132332bc1a7 Mon Sep 17 00:00:00 2001 From: Malo <57839069+MDLC01@users.noreply.github.com> Date: Thu, 3 Jul 2025 22:47:20 +0100 Subject: [PATCH 2/2] Add tests --- tests/suite/foundations/str.typ | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/suite/foundations/str.typ b/tests/suite/foundations/str.typ index 66fb912c0..aeaa0a0af 100644 --- a/tests/suite/foundations/str.typ +++ b/tests/suite/foundations/str.typ @@ -103,6 +103,10 @@ #test("Hello".last(), "o") #test("🏳️‍🌈A🏳️‍⚧️".first(), "🏳️‍🌈") #test("🏳️‍🌈A🏳️‍⚧️".last(), "🏳️‍⚧️") +#test("hey".first(default: "d"), "h") +#test("".first(default: "d"), "d") +#test("hey".last(default: "d"), "y") +#test("".last(default: "d"), "d") --- string-first-empty --- // Error: 2-12 string is empty