Skip to content

Commit 3fba873

Browse files
Darksonnjannau
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 <[email protected]> Reviewed-by: Greg Kroah-Hartman <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Danilo Krummrich <[email protected]>
1 parent bf3ab36 commit 3fba873

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
@@ -323,6 +323,37 @@ where
323323
Ok(())
324324
}
325325

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

0 commit comments

Comments
 (0)