[PATCH 4/4] rust: alloc: implement `Borrow` and `BorrowMut` for `CString`

Alexandre Courbot posted 4 patches 8 months, 1 week ago
There is a newer version of this series
[PATCH 4/4] rust: alloc: implement `Borrow` and `BorrowMut` for `CString`
Posted by Alexandre Courbot 8 months, 1 week ago
Implement these two common traits, which allow generic types to store
either an owned value or a reference to it, leveraging the `Deref`
implementation.

Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
 rust/kernel/str.rs | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index a927db8e079c3597860880947a03959e1d6d712e..f5da512ebcfef6c8d5227e8177ae32f6194ecffb 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -3,6 +3,7 @@
 //! String representations.
 
 use crate::alloc::{flags::*, AllocError, KVec};
+use core::borrow::{Borrow, BorrowMut};
 use core::fmt::{self, Write};
 use core::ops::{self, Deref, DerefMut, Index};
 
@@ -911,6 +912,18 @@ fn deref_mut(&mut self) -> &mut Self::Target {
     }
 }
 
+impl Borrow<CStr> for CString {
+    fn borrow(&self) -> &CStr {
+        self.deref()
+    }
+}
+
+impl BorrowMut<CStr> for CString {
+    fn borrow_mut(&mut self) -> &mut CStr {
+        self.deref_mut()
+    }
+}
+
 impl<'a> TryFrom<&'a CStr> for CString {
     type Error = AllocError;
 

-- 
2.49.0