Skip to content

Commit f2b4dd7

Browse files
DarksonnDanilo Krummrich
authored andcommitted
rust: alloc: add Vec::pop
This introduces a basic method that our custom Vec is missing. I expect that it will be used in many places, but at the time of writing, Rust Binder has six calls to Vec::pop. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/20250502-vec-methods-v5-2-06d20ad9366f@google.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent a1e4d5c commit f2b4dd7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,37 @@ where
320320
Ok(())
321321
}
322322

323+
/// Removes the last element from a vector and returns it, or `None` if it is empty.
324+
///
325+
/// # Examples
326+
///
327+
/// ```
328+
/// let mut v = KVec::new();
329+
/// v.push(1, GFP_KERNEL)?;
330+
/// v.push(2, GFP_KERNEL)?;
331+
/// assert_eq!(&v, &[1, 2]);
332+
///
333+
/// assert_eq!(v.pop(), Some(2));
334+
/// assert_eq!(v.pop(), Some(1));
335+
/// assert_eq!(v.pop(), None);
336+
/// # Ok::<(), Error>(())
337+
/// ```
338+
pub fn pop(&mut self) -> Option<T> {
339+
if self.is_empty() {
340+
return None;
341+
}
342+
343+
let removed: *mut T = {
344+
// SAFETY: We just checked that the length is at least one.
345+
let slice = unsafe { self.dec_len(1) };
346+
// SAFETY: The argument to `dec_len` was 1 so this returns a slice of length 1.
347+
unsafe { slice.get_unchecked_mut(0) }
348+
};
349+
350+
// SAFETY: The guarantees of `dec_len` allow us to take ownership of this value.
351+
Some(unsafe { removed.read() })
352+
}
353+
323354
/// Creates a new [`Vec`] instance with at least the given capacity.
324355
///
325356
/// # Examples

0 commit comments

Comments
 (0)