diff --git a/src/log.rs b/src/log.rs index 015dbd36..44323c55 100644 --- a/src/log.rs +++ b/src/log.rs @@ -180,6 +180,26 @@ impl Log { log } + /// Returns the first entry in the log, if any. + /// + /// Complexity: O(1) + #[inline] + pub fn first(&self) -> Option { + self.get(0) + } + + /// Returns the last entry in the log, if any. + /// + /// Complexity: O(1) + #[inline] + pub fn last(&self) -> Option { + let len = self.len(); + if len == 0 { + return None; + } + self.get(len - 1) + } + /// Initializes the log based on the contents of the provided memory trait objects. /// If the memory trait objects already contain a stable log, this function recovers it from the stable /// memory. Otherwise, this function allocates a new empty log. diff --git a/src/log/tests.rs b/src/log/tests.rs index 545ea72a..3b2df595 100644 --- a/src/log/tests.rs +++ b/src/log/tests.rs @@ -221,6 +221,25 @@ fn test_iter() { assert_eq!(log.iter().skip(usize::MAX).count(), 0); } +#[test] +fn test_first_last() { + let log = Log::::new(VectorMemory::default(), VectorMemory::default()); + assert_eq!(log.first(), None); + assert_eq!(log.last(), None); + + log.append(&"apple".to_string()).unwrap(); + assert_eq!(log.first(), Some("apple".to_string())); + assert_eq!(log.last(), Some("apple".to_string())); + + log.append(&"banana".to_string()).unwrap(); + assert_eq!(log.first(), Some("apple".to_string())); + assert_eq!(log.last(), Some("banana".to_string())); + + log.append(&"cider".to_string()).unwrap(); + assert_eq!(log.first(), Some("apple".to_string())); + assert_eq!(log.last(), Some("cider".to_string())); +} + #[allow(clippy::iter_nth_zero)] #[test] fn test_thread_local_iter() {