From a4438571c902aae659ff568419fa4af029b5c0b0 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 4 Jul 2024 21:12:09 -0700 Subject: [PATCH] Add Punctuated::get and get_mut --- src/punctuated.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/punctuated.rs b/src/punctuated.rs index 29e8dce15f..ab2e7d9879 100644 --- a/src/punctuated.rs +++ b/src/punctuated.rs @@ -92,6 +92,29 @@ impl Punctuated { self.iter_mut().next_back() } + /// Borrows the element at the given index. + pub fn get(&mut self, index: usize) -> Option<&T> { + if let Some((value, _punct)) = self.inner.get(index) { + Some(value) + } else if index == self.inner.len() { + self.last.as_deref() + } else { + None + } + } + + /// Mutably borrows the element at the given index. + pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { + let inner_len = self.inner.len(); + if let Some((value, _punct)) = self.inner.get_mut(index) { + Some(value) + } else if index == inner_len { + self.last.as_deref_mut() + } else { + None + } + } + /// Returns an iterator over borrowed syntax tree nodes of type `&T`. pub fn iter(&self) -> Iter { Iter {