From faf7bd0cab760582f5da0402bfaa747e2a113229 Mon Sep 17 00:00:00 2001 From: Jim Turner Date: Tue, 23 Oct 2018 18:51:05 -0400 Subject: [PATCH] Add first and first_mut methods These are useful for getting an initial value when iterating over an array (e.g. when calculating the minimum element with `fold`). --- src/impl_methods.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/impl_methods.rs b/src/impl_methods.rs index 7b788ee44..632c89a4f 100644 --- a/src/impl_methods.rs +++ b/src/impl_methods.rs @@ -191,6 +191,29 @@ impl ArrayBase where S: Data, D: Dimension } } + /// Returns a reference to the first element of the array, or `None` if it + /// is empty. + pub fn first(&self) -> Option<&A> { + if self.is_empty() { + None + } else { + Some(unsafe { &*self.as_ptr() }) + } + } + + /// Returns a mutable reference to the first element of the array, or + /// `None` if it is empty. + pub fn first_mut(&mut self) -> Option<&mut A> + where + S: DataMut, + { + if self.is_empty() { + None + } else { + Some(unsafe { &mut *self.as_mut_ptr() }) + } + } + /// Return an iterator of references to the elements of the array. /// /// Elements are visited in the *logical order* of the array, which