From 9c8076e445bbfef28cc8ec1a5829c67012635bbf Mon Sep 17 00:00:00 2001 From: ldev Date: Wed, 5 Mar 2025 20:27:56 +0100 Subject: [PATCH] Added into_vec() and impl From> for Vec --- build.rs | 5 ++++ src/lib.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/build.rs b/build.rs index 830bf87..b7067d5 100644 --- a/build.rs +++ b/build.rs @@ -5,4 +5,9 @@ fn main() { if version_check::is_min_version("1.36.0").unwrap_or(false) { println!("cargo:rustc-cfg=has_extern_crate_alloc"); } + + println!("cargo:rustc-check-cfg=cfg(has_relaxed_orphan_rule)"); + if version_check::is_min_version("1.41.0").unwrap_or(false) { + println!("cargo:rustc-cfg=has_relaxed_orphan_rule"); + } } diff --git a/src/lib.rs b/src/lib.rs index 2b1d408..8b6a7cb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -350,6 +350,31 @@ impl CircularQueue { let (a, b) = self.data.split_at_mut(self.insertion_index); b.iter_mut().chain(a.iter_mut()) } + + /// Converts the queue into a `Vec` going from the most recently pushed items to the oldest + /// ones. + /// + /// # Examples + /// + /// ``` + /// use circular_queue::CircularQueue; + /// + /// let mut queue = CircularQueue::with_capacity(3); + /// queue.push(1); + /// queue.push(2); + /// queue.push(3); + /// queue.push(4); + /// + /// let v = queue.into_vec(); + /// + /// assert_eq!(v, vec![4, 3, 2]); + /// ``` + #[inline] + pub fn into_vec(mut self) -> Vec { + self.data[self.insertion_index..].reverse(); // Reverse the upper part. + self.data[..self.insertion_index].reverse(); // Reverse the lower part. + self.data + } } impl PartialEq for CircularQueue { @@ -361,9 +386,19 @@ impl PartialEq for CircularQueue { impl Eq for CircularQueue {} +#[cfg(has_relaxed_orphan_rule)] +impl From> for Vec { + #[inline] + fn from(queue: CircularQueue) -> Self { + queue.into_vec() + } +} + #[cfg(test)] mod tests { use super::*; + #[cfg(has_extern_crate_alloc)] + use alloc::vec; #[test] fn zero_capacity() { @@ -628,4 +663,37 @@ mod tests { q2.push(()); assert_eq!(q1, q2); } + + #[test] + fn into_vec() { + let mut q = CircularQueue::with_capacity(4); + q.push(1); + q.push(2); + q.push(3); + + let v = q.clone().into_vec(); + assert_eq!(v, vec![3, 2, 1]); + + q.push(4); + q.push(5); + let v = q.clone().into_vec(); + assert_eq!(v, vec![5, 4, 3, 2]); + + q.push(6); + let v = q.into_vec(); + assert_eq!(v, vec![6, 5, 4, 3]); + } + + #[cfg(has_relaxed_orphan_rule)] + #[test] + fn vec_from() { + let mut q = CircularQueue::with_capacity(3); + q.push(1); + q.push(2); + q.push(3); + q.push(4); + + let v = Vec::from(q); + assert_eq!(v, vec![4, 3, 2]); + } }