From 74863e1dbbc0f6c4c210d4674ea30886b9f42989 Mon Sep 17 00:00:00 2001 From: sun-jacobi Date: Tue, 30 Jul 2024 10:30:45 +0200 Subject: [PATCH] Add List::split_first and List::split_last --- libspecr/src/list/func.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/libspecr/src/list/func.rs b/libspecr/src/list/func.rs index 9e7506f..9115b22 100644 --- a/libspecr/src/list/func.rs +++ b/libspecr/src/list/func.rs @@ -106,6 +106,28 @@ impl List { List(GcCow::new(v)) } + /// Returns the first element and the rest of the list. + /// Returns `None` if the list is empty. + pub fn split_first(&self) -> Option<(T, List)> { + if let Some(first) = self.first() { + let rest = self.subslice_with_length(Int::ONE, self.len() - Int::ONE); + Some((first, rest)) + } else { + None + } + } + + /// Returns the last element and the rest of the list. + /// Returns `None` if the list is empty. + pub fn split_last(&self) -> Option<(T, List)> { + if let Some(last) = self.last() { + let rest = self.subslice_with_length(Int::ZERO, self.len() - Int::ONE); + Some((last, rest)) + } else { + None + } + } + /// Conceptually equivalent to `self[start..src.len()] = src;` pub fn write_subslice_at_index(&mut self, start: Int, src: List) { // exclusive end