summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMalo <57839069+MDLC01@users.noreply.github.com>2025-07-09 13:10:24 +0100
committerGitHub <noreply@github.com>2025-07-09 12:10:24 +0000
commit1dc4c248d1022dc9f3b6e3e899857404f6c680a1 (patch)
tree50112c7ef40d1904173f84458cd18e45ab5a1b41
parent9e6adb6f4577a7bfdd119163168e8c6902bd1b21 (diff)
Add `default` argument for `str.first` and `str.last` (#6554)
Co-authored-by: Laurenz <laurmaedje@gmail.com>
-rw-r--r--crates/typst-library/src/foundations/str.rs24
-rw-r--r--tests/suite/foundations/str.typ4
2 files changed, 24 insertions, 4 deletions
diff --git a/crates/typst-library/src/foundations/str.rs b/crates/typst-library/src/foundations/str.rs
index 23a1bd4c..e500b1a4 100644
--- a/crates/typst-library/src/foundations/str.rs
+++ b/crates/typst-library/src/foundations/str.rs
@@ -179,24 +179,40 @@ impl Str {
}
/// Extracts the first grapheme cluster of the string.
- /// Fails with an error if the string is empty.
+ ///
+ /// Returns the provided default value if the string is empty or fails with
+ /// an error if no default value was specified.
#[func]
- pub fn first(&self) -> StrResult<Str> {
+ pub fn first(
+ &self,
+ /// A default value to return if the string is empty.
+ #[named]
+ default: Option<Str>,
+ ) -> StrResult<Str> {
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.
+ ///
+ /// Returns the provided default value if the string is empty or fails with
+ /// an error if no default value was specified.
#[func]
- pub fn last(&self) -> StrResult<Str> {
+ pub fn last(
+ &self,
+ /// A default value to return if the string is empty.
+ #[named]
+ default: Option<Str>,
+ ) -> StrResult<Str> {
self.0
.graphemes(true)
.next_back()
.map(Into::into)
+ .or(default)
.ok_or_else(string_is_empty)
}
diff --git a/tests/suite/foundations/str.typ b/tests/suite/foundations/str.typ
index 66fb912c..aeaa0a0a 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