Rust for Linux List
 help / color / mirror / Atom feed
* [PATCH] rust: introduce KVec::pop()
@ 2024-12-02  8:57 Bernhard Kauer
  2024-12-02  9:06 ` Greg KH
                   ` (3 more replies)
  0 siblings, 4 replies; 8+ messages in thread
From: Bernhard Kauer @ 2024-12-02  8:57 UTC (permalink / raw)
  To: Danilo Krummrich; +Cc: rust-for-linux, Bernhard Kauer

Provides a simple stack together with push().

Signed-off-by: Bernhard Kauer <bk@alpico.io>
---
 rust/kernel/alloc/kvec.rs | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index ae9d072741ce..ba6c265ad5c5 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -302,6 +302,34 @@ pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         Ok(())
     }
 
+    /// Removes the last element from the [`Vec`] instance.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let mut v = KVec::new();
+    /// v.push(1, GFP_KERNEL)?;
+    /// v.push(2, GFP_KERNEL)?;
+    /// assert_eq!(Some(2), v.pop());
+    /// assert_eq!(Some(1), v.pop());
+    /// assert_eq!(None, v.pop());
+    /// assert!(v.is_empty());
+    /// ```
+    pub fn pop(&mut self) -> Option<T> {
+        if self.len() == 0 {
+            return None;
+        }
+        self.len -= 1;
+
+        // SAFETY:
+        // - `ptr` is valid because there is at least one entry stored.
+        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
+
+        // SAFETY:
+        // - `ptr` is properly aligned and valid for reads.
+        Some(unsafe { core::ptr::read(ptr) })
+    }
+
     /// Creates a new [`Vec`] instance with at least the given capacity.
     ///
     /// # Examples
-- 
2.45.2


^ permalink raw reply related	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2024-12-03  2:57 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-12-02  8:57 [PATCH] rust: introduce KVec::pop() Bernhard Kauer
2024-12-02  9:06 ` Greg KH
2024-12-02  9:54   ` Bernhard Kauer
2024-12-02 10:22     ` Danilo Krummrich
2024-12-02 18:30       ` Miguel Ojeda
2024-12-02  9:54 ` Danilo Krummrich
2024-12-02 18:28 ` Miguel Ojeda
2024-12-03  2:55 ` kernel test robot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox