summaryrefslogtreecommitdiff
path: root/crates/typst-utils
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2024-08-26 19:17:58 +0200
committerGitHub <noreply@github.com>2024-08-26 17:17:58 +0000
commit4365e18454af4f8f53fe1198182cb5dc8f3d628e (patch)
treefe37649cec71b916d5119a033028e3f620247209 /crates/typst-utils
parentcb98eec60924a41889988644e5122d2e13eccbf1 (diff)
Improve realization and page layout (#4840)
Diffstat (limited to 'crates/typst-utils')
-rw-r--r--crates/typst-utils/src/lib.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/crates/typst-utils/src/lib.rs b/crates/typst-utils/src/lib.rs
index 831b2374..79d4bb09 100644
--- a/crates/typst-utils/src/lib.rs
+++ b/crates/typst-utils/src/lib.rs
@@ -106,6 +106,18 @@ impl<T> OptionExt<T> for Option<T> {
/// Extra methods for [`[T]`](slice).
pub trait SliceExt<T> {
+ /// Returns a slice with all matching elements from the start of the slice
+ /// removed.
+ fn trim_start_matches<F>(&self, f: F) -> &[T]
+ where
+ F: FnMut(&T) -> bool;
+
+ /// Returns a slice with all matching elements from the end of the slice
+ /// removed.
+ fn trim_end_matches<F>(&self, f: F) -> &[T]
+ where
+ F: FnMut(&T) -> bool;
+
/// Split a slice into consecutive runs with the same key and yield for
/// each such run the key and the slice of elements with that key.
fn group_by_key<K, F>(&self, f: F) -> GroupByKey<'_, T, F>
@@ -115,6 +127,29 @@ pub trait SliceExt<T> {
}
impl<T> SliceExt<T> for [T] {
+ fn trim_start_matches<F>(&self, mut f: F) -> &[T]
+ where
+ F: FnMut(&T) -> bool,
+ {
+ let len = self.len();
+ let mut i = 0;
+ while i < len && f(&self[i]) {
+ i += 1;
+ }
+ &self[i..]
+ }
+
+ fn trim_end_matches<F>(&self, mut f: F) -> &[T]
+ where
+ F: FnMut(&T) -> bool,
+ {
+ let mut i = self.len();
+ while i > 0 && f(&self[i - 1]) {
+ i -= 1;
+ }
+ &self[..i]
+ }
+
fn group_by_key<K, F>(&self, f: F) -> GroupByKey<'_, T, F> {
GroupByKey { slice: self, f }
}