Skip to contentSkip to conversation

rust: alloc: use `spare_capacity_mut` to reduce unsafe

PATCH Superseded Tamir Duberstein 4 participants 11 messages Mar 17, 2025 – Mar 18, 2025

Subsystems (2)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: alloc: use `spare_capacity_mut` to reduce unsafe

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +2 -9
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
-        // SAFETY:
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);
 
         // SAFETY: We just initialised the first spare entry, so it is safe to increase the length
         // by 1. We also know that the new length is <= capacity because of the previous call to

---
base-commit: cf25bc61f8aecad9b0c45fe32697e35ea4b13378
change-id: 20250317-vec-push-use-spare-27484fd016a9

Best regards,

Signature · 1 line
Tamir Duberstein <[email protected]>
#2 lore raw
In reply to Tamir Duberstein
Quoted 18 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -1
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
-        // SAFETY:

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 10 lines
rust/kernel/alloc/kvec.rs +2 -8
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

---
Cheers,
Benno

Quoted 9 lines
rust/kernel/alloc/kvec.rs +0 -1
         // SAFETY: We just initialised the first spare entry, so it is safe to increase the length
         // by 1. We also know that the new length is <= capacity because of the previous call to
 
---

base-commit: cf25bc61f8aecad9b0c45fe32697e35ea4b13378
change-id: 20250317-vec-push-use-spare-27484fd016a9

Best regards,

#3 lore raw
Quoted 19 lines · Benno Lossin
Quoted 17 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -0
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
Quoted 14 lines

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 11 lines
rust/kernel/alloc/kvec.rs +2 -9
-        // SAFETY:
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

We could use slice::get_unchecked_mut here to retain the same guarantee of no bounds check. That would still be one fewer unsafe blocks.

maintainer
#4 lore raw
Quoted 20 lines · Tamir Duberstein
Quoted 19 lines · Benno Lossin
Quoted 17 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -0
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
Quoted 14 lines
Quoted 12 lines

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 11 lines
rust/kernel/alloc/kvec.rs +2 -9
-        // SAFETY:
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);
Quoted 2 lines

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

Yes, that was the justification to use unsafe calls instead.

(This may also justify keeping dec_len() unsafe, since otherwise it would introduce an additional boundary check for pop().)

Quoted 4 lines

We could use slice::get_unchecked_mut here to retain the same guarantee of no bounds check. That would still be one fewer unsafe blocks.

Sounds reasonable.

#5 lore raw
Quoted 35 lines · Danilo Krummrich
Quoted 19 lines · Tamir Duberstein
Quoted 18 lines · Benno Lossin
Quoted 17 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -0
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
Quoted 14 lines
Quoted 12 lines

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 11 lines
rust/kernel/alloc/kvec.rs +2 -9
-        // SAFETY:
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);
Quoted 2 lines

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

Quoted 4 lines

Yes, that was the justification to use unsafe calls instead.

(This may also justify keeping dec_len() unsafe, since otherwise it would introduce an additional boundary check for pop().)

If we use saturating_sub then we don't need a bounds check (at least on non-debug builds), right?

Quoted 5 lines
Quoted 3 lines

We could use slice::get_unchecked_mut here to retain the same guarantee of no bounds check. That would still be one fewer unsafe blocks.

Sounds reasonable.

+1

maintainer
#6 lore raw
Quoted 36 lines · Benno Lossin
Quoted 35 lines · Danilo Krummrich
Quoted 33 lines · Tamir Duberstein
Quoted 32 lines · Benno Lossin
Quoted 18 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -1
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
-        // SAFETY:

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 10 lines
rust/kernel/alloc/kvec.rs +2 -8
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

Quoted 7 lines
Quoted 4 lines

Yes, that was the justification to use unsafe calls instead.

(This may also justify keeping dec_len() unsafe, since otherwise it would introduce an additional boundary check for pop().)

If we use saturating_sub then we don't need a bounds check (at least on non-debug builds), right?

	fn dec_len(&mut self, count: usize) -> &mut [T] {
	    self.len = self.len.saturating_sub(count);

	    // Potentially broken, since maybe `count > self.len`, hence need an
	    // additional check.
	    unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
	}
#7 lore raw
Quoted 45 lines · Danilo Krummrich
Quoted 36 lines · Benno Lossin
Quoted 35 lines · Danilo Krummrich
Quoted 33 lines · Tamir Duberstein
Quoted 32 lines · Benno Lossin
Quoted 18 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -1
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
-        // SAFETY:

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 10 lines
rust/kernel/alloc/kvec.rs +2 -8
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

Quoted 7 lines
Quoted 4 lines

Yes, that was the justification to use unsafe calls instead.

(This may also justify keeping dec_len() unsafe, since otherwise it would introduce an additional boundary check for pop().)

If we use saturating_sub then we don't need a bounds check (at least on non-debug builds), right?

Quoted 7 lines
	fn dec_len(&mut self, count: usize) -> &mut [T] {
	    self.len = self.len.saturating_sub(count);

	    // Potentially broken, since maybe `count > self.len`, hence need an
	    // additional check.
	    unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
	}

Ah sorry, in my mental model the function returned (). Do we need the return value?

---
Cheers,
Benno

#8 lore raw
Quoted 50 lines · Benno Lossin
Quoted 48 lines · Danilo Krummrich
Quoted 36 lines · Benno Lossin
Quoted 35 lines · Danilo Krummrich
Quoted 33 lines · Tamir Duberstein
Quoted 32 lines · Benno Lossin
Quoted 18 lines · Tamir Duberstein

Use spare_capacity_mut in the implementation of push to reduce the use of unsafe. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").

---
 rust/kernel/alloc/kvec.rs | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
rust/kernel/alloc/kvec.rs +0 -1
index ae9d072741ce..d2bc3d02179e 100644
@@ -285,15 +285,8 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
-        // SAFETY:

rust/kernel/alloc/kvec.rs pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { · line 289

Quoted 10 lines
rust/kernel/alloc/kvec.rs +2 -8
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
-
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // The call to `reserve` was successful so the spare capacity is at least 1.
+        self.spare_capacity_mut()[0].write(v);

I think the code uses unsafe to avoid a bounds check, but I'm not 100% sure. Danilo might remember more info.

Quoted 7 lines
Quoted 4 lines

Yes, that was the justification to use unsafe calls instead.

(This may also justify keeping dec_len() unsafe, since otherwise it would introduce an additional boundary check for pop().)

If we use saturating_sub then we don't need a bounds check (at least on non-debug builds), right?

      fn dec_len(&mut self, count: usize) -> &mut [T] {
          self.len = self.len.saturating_sub(count);
Quoted 7 lines
Quoted 4 lines
          // Potentially broken, since maybe `count > self.len`, hence need an
          // additional check.
          unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
      }

Ah sorry, in my mental model the function returned (). Do we need the return value?

The return value is the whole genesis of dec_len, we want to return something to let the caller know they need to drop or copy the memory.

maintainer
#9 lore raw
Quoted 9 lines · Tamir Duberstein
Quoted 9 lines
Quoted 8 lines
      fn dec_len(&mut self, count: usize) -> &mut [T] {
          self.len = self.len.saturating_sub(count);

          // Potentially broken, since maybe `count > self.len`, hence need an
          // additional check.
          unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
      }
Quoted 5 lines
Quoted 2 lines

Ah sorry, in my mental model the function returned (). Do we need the return value?

The return value is the whole genesis of dec_len, we want to return something to let the caller know they need to drop or copy the memory.

Hold on .. it returns &mut [T]. You're usually not allowed to take ownership of or drop values behind a mutable reference.

Alice

maintainer
#10 lore raw
Quoted 10 lines · Alice Ryhl
Quoted 9 lines · Tamir Duberstein
Quoted 9 lines
Quoted 8 lines
      fn dec_len(&mut self, count: usize) -> &mut [T] {
          self.len = self.len.saturating_sub(count);

          // Potentially broken, since maybe `count > self.len`, hence need an
          // additional check.
          unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
      }
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Ah sorry, in my mental model the function returned (). Do we need the return value?

The return value is the whole genesis of dec_len, we want to return something to let the caller know they need to drop or copy the memory.

Hold on .. it returns &mut [T]. You're usually not allowed to take ownership of or drop values behind a mutable reference.

I think it should be fine. dec_len(), by returning this slice, indicates to the caller what's left behind in case no action is taken.

Subsequent operations are unsafe anyways and can easily justify their validity by saying that they only take over, what otherwise would have been left behind.

Do I miss anything?