rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v2] rust: str: add conversion from `CStr` to `CString`
@ 2023-05-03 14:10 Alice Ryhl
  2023-05-03 19:01 ` Martin Rodriguez Reboredo
                   ` (3 more replies)
  0 siblings, 4 replies; 9+ messages in thread
From: Alice Ryhl @ 2023-05-03 14:10 UTC (permalink / raw)
  To: Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Martin Rodriguez Reboredo, Alice Ryhl, rust-for-linux,
	linux-kernel, patches

These methods can be used to copy the data in a temporary c string into
a separate allocation, so that it can be accessed later even if the
original is deallocated.

The API in this change mirrors the standard library API for the `&str`
and `String` types. The `ToOwned` trait is not implemented because it
assumes that allocations are infallible.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/str.rs | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index b771310fa4a4..f3dc5b24ea55 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -2,6 +2,7 @@
 
 //! String representations.
 
+use alloc::alloc::AllocError;
 use alloc::vec::Vec;
 use core::fmt::{self, Write};
 use core::ops::{self, Deref, Index};
@@ -199,6 +200,12 @@ impl CStr {
     pub unsafe fn as_str_unchecked(&self) -> &str {
         unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
     }
+
+    /// Convert this [`CStr`] into a [`CString`] by allocating memory and
+    /// copying over the string data.
+    pub fn to_cstring(&self) -> Result<CString, AllocError> {
+        CString::try_from(self)
+    }
 }
 
 impl fmt::Display for CStr {
@@ -584,6 +591,21 @@ impl Deref for CString {
     }
 }
 
+impl<'a> TryFrom<&'a CStr> for CString {
+    type Error = AllocError;
+
+    fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
+        let mut buf = Vec::new();
+
+        buf.try_extend_from_slice(cstr.as_bytes_with_nul())
+            .map_err(|_| AllocError)?;
+
+        // INVARIANT: The `CStr` and `CString` types have the same invariants for
+        // the string data, and we copied it over without changes.
+        Ok(CString { buf })
+    }
+}
+
 /// A convenience alias for [`core::format_args`].
 #[macro_export]
 macro_rules! fmt {

base-commit: ea76e08f4d901a450619831a255e9e0a4c0ed162
-- 
2.40.1.521.gf1e218fcd8-goog


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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-03 14:10 [PATCH v2] rust: str: add conversion from `CStr` to `CString` Alice Ryhl
@ 2023-05-03 19:01 ` Martin Rodriguez Reboredo
  2023-05-08 11:41 ` Gary Guo
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 9+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-05-03 19:01 UTC (permalink / raw)
  To: Alice Ryhl, Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	rust-for-linux, linux-kernel, patches

On 5/3/23 11:10, Alice Ryhl wrote:
> These methods can be used to copy the data in a temporary c string into
> a separate allocation, so that it can be accessed later even if the
> original is deallocated.
> 
> The API in this change mirrors the standard library API for the `&str`
> and `String` types. The `ToOwned` trait is not implemented because it
> assumes that allocations are infallible.
> 
> Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
>   rust/kernel/str.rs | 22 ++++++++++++++++++++++
>   1 file changed, 22 insertions(+)
> 
> diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> index b771310fa4a4..f3dc5b24ea55 100644
> --- a/rust/kernel/str.rs
> +++ b/rust/kernel/str.rs
> @@ -2,6 +2,7 @@
>   
>   //! String representations.
>   
> +use alloc::alloc::AllocError;
>   use alloc::vec::Vec;
>   use core::fmt::{self, Write};
>   use core::ops::{self, Deref, Index};
> @@ -199,6 +200,12 @@ impl CStr {
>       pub unsafe fn as_str_unchecked(&self) -> &str {
>           unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
>       }
> +
> +    /// Convert this [`CStr`] into a [`CString`] by allocating memory and
> +    /// copying over the string data.
> +    pub fn to_cstring(&self) -> Result<CString, AllocError> {
> +        CString::try_from(self)
> +    }
>   }
>   
>   impl fmt::Display for CStr {
> @@ -584,6 +591,21 @@ impl Deref for CString {
>       }
>   }
>   
> +impl<'a> TryFrom<&'a CStr> for CString {
> +    type Error = AllocError;
> +
> +    fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
> +        let mut buf = Vec::new();
> +
> +        buf.try_extend_from_slice(cstr.as_bytes_with_nul())
> +            .map_err(|_| AllocError)?;
> +
> +        // INVARIANT: The `CStr` and `CString` types have the same invariants for
> +        // the string data, and we copied it over without changes.
> +        Ok(CString { buf })
> +    }
> +}
> +
>   /// A convenience alias for [`core::format_args`].
>   #[macro_export]
>   macro_rules! fmt {
> 
> base-commit: ea76e08f4d901a450619831a255e9e0a4c0ed162

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-03 14:10 [PATCH v2] rust: str: add conversion from `CStr` to `CString` Alice Ryhl
  2023-05-03 19:01 ` Martin Rodriguez Reboredo
@ 2023-05-08 11:41 ` Gary Guo
  2023-05-08 20:29   ` Alice Ryhl
  2023-05-15 18:36 ` Andreas Hindborg
  2023-05-31 17:09 ` Miguel Ojeda
  3 siblings, 1 reply; 9+ messages in thread
From: Gary Guo @ 2023-05-08 11:41 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Martin Rodriguez Reboredo,
	rust-for-linux, linux-kernel, patches

On Wed,  3 May 2023 14:10:16 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> These methods can be used to copy the data in a temporary c string into
> a separate allocation, so that it can be accessed later even if the
> original is deallocated.
> 
> The API in this change mirrors the standard library API for the `&str`
> and `String` types. The `ToOwned` trait is not implemented because it
> assumes that allocations are infallible.

How about add a `TryToOwned` trait to the kernel crate and implement
that trait for `CStr` instead?

Best,
Gary

> 
> Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
>  rust/kernel/str.rs | 22 ++++++++++++++++++++++
>  1 file changed, 22 insertions(+)
> 
> diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> index b771310fa4a4..f3dc5b24ea55 100644
> --- a/rust/kernel/str.rs
> +++ b/rust/kernel/str.rs
> @@ -2,6 +2,7 @@
>  
>  //! String representations.
>  
> +use alloc::alloc::AllocError;
>  use alloc::vec::Vec;
>  use core::fmt::{self, Write};
>  use core::ops::{self, Deref, Index};
> @@ -199,6 +200,12 @@ impl CStr {
>      pub unsafe fn as_str_unchecked(&self) -> &str {
>          unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
>      }
> +
> +    /// Convert this [`CStr`] into a [`CString`] by allocating memory and
> +    /// copying over the string data.
> +    pub fn to_cstring(&self) -> Result<CString, AllocError> {
> +        CString::try_from(self)
> +    }
>  }
>  
>  impl fmt::Display for CStr {
> @@ -584,6 +591,21 @@ impl Deref for CString {
>      }
>  }
>  
> +impl<'a> TryFrom<&'a CStr> for CString {
> +    type Error = AllocError;
> +
> +    fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
> +        let mut buf = Vec::new();
> +
> +        buf.try_extend_from_slice(cstr.as_bytes_with_nul())
> +            .map_err(|_| AllocError)?;
> +
> +        // INVARIANT: The `CStr` and `CString` types have the same invariants for
> +        // the string data, and we copied it over without changes.
> +        Ok(CString { buf })
> +    }
> +}
> +
>  /// A convenience alias for [`core::format_args`].
>  #[macro_export]
>  macro_rules! fmt {
> 
> base-commit: ea76e08f4d901a450619831a255e9e0a4c0ed162


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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-08 11:41 ` Gary Guo
@ 2023-05-08 20:29   ` Alice Ryhl
  2023-05-15 18:12     ` Andreas Hindborg
  0 siblings, 1 reply; 9+ messages in thread
From: Alice Ryhl @ 2023-05-08 20:29 UTC (permalink / raw)
  To: Gary Guo
  Cc: Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Martin Rodriguez Reboredo,
	rust-for-linux, linux-kernel, patches

On 5/8/23 13:41, Gary Guo wrote:
> On Wed,  3 May 2023 14:10:16 +0000
> Alice Ryhl <aliceryhl@google.com> wrote:
> 
>> These methods can be used to copy the data in a temporary c string into
>> a separate allocation, so that it can be accessed later even if the
>> original is deallocated.
>>
>> The API in this change mirrors the standard library API for the `&str`
>> and `String` types. The `ToOwned` trait is not implemented because it
>> assumes that allocations are infallible.
> 
> How about add a `TryToOwned` trait to the kernel crate and implement
> that trait for `CStr` instead?

Eh, I don't think it's worth it. It doesn't give anything new to the 
CStr api, and I think it's rather unlikely that someone will actually 
need to be generic over such a trait any time soon.

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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-08 20:29   ` Alice Ryhl
@ 2023-05-15 18:12     ` Andreas Hindborg
  2023-05-16 11:12       ` Alice Ryhl
  0 siblings, 1 reply; 9+ messages in thread
From: Andreas Hindborg @ 2023-05-15 18:12 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: Gary Guo, Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor,
	Boqun Feng, Björn Roy Baron, Benno Lossin,
	Martin Rodriguez Reboredo, rust-for-linux, linux-kernel, patches


Alice Ryhl <alice@ryhl.io> writes:

> On 5/8/23 13:41, Gary Guo wrote:
>> On Wed,  3 May 2023 14:10:16 +0000
>> Alice Ryhl <aliceryhl@google.com> wrote:
>> 
>>> These methods can be used to copy the data in a temporary c string into
>>> a separate allocation, so that it can be accessed later even if the
>>> original is deallocated.
>>>
>>> The API in this change mirrors the standard library API for the `&str`
>>> and `String` types. The `ToOwned` trait is not implemented because it
>>> assumes that allocations are infallible.
>> How about add a `TryToOwned` trait to the kernel crate and implement
>> that trait for `CStr` instead?
>
> Eh, I don't think it's worth it. It doesn't give anything new to the CStr api,
> and I think it's rather unlikely that someone will actually need to be generic
> over such a trait any time soon.

It is just as valid as having `From<&str>` and `ToOwned<&str>`. While it
does not add anything in terms of function, it carries intention. I
think we should consider adding it at some point.

BR Andreas

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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-03 14:10 [PATCH v2] rust: str: add conversion from `CStr` to `CString` Alice Ryhl
  2023-05-03 19:01 ` Martin Rodriguez Reboredo
  2023-05-08 11:41 ` Gary Guo
@ 2023-05-15 18:36 ` Andreas Hindborg
  2023-05-31 17:09 ` Miguel Ojeda
  3 siblings, 0 replies; 9+ messages in thread
From: Andreas Hindborg @ 2023-05-15 18:36 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin,
	Martin Rodriguez Reboredo, rust-for-linux, linux-kernel, patches,
	Andreas Hindborg


Alice Ryhl <aliceryhl@google.com> writes:

> These methods can be used to copy the data in a temporary c string into
> a separate allocation, so that it can be accessed later even if the
> original is deallocated.
>
> The API in this change mirrors the standard library API for the `&str`
> and `String` types. The `ToOwned` trait is not implemented because it
> assumes that allocations are infallible.
>
> Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---

Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com>


>  rust/kernel/str.rs | 22 ++++++++++++++++++++++
>  1 file changed, 22 insertions(+)
>
> diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> index b771310fa4a4..f3dc5b24ea55 100644
> --- a/rust/kernel/str.rs
> +++ b/rust/kernel/str.rs
> @@ -2,6 +2,7 @@
>  
>  //! String representations.
>  
> +use alloc::alloc::AllocError;
>  use alloc::vec::Vec;
>  use core::fmt::{self, Write};
>  use core::ops::{self, Deref, Index};
> @@ -199,6 +200,12 @@ impl CStr {
>      pub unsafe fn as_str_unchecked(&self) -> &str {
>          unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
>      }
> +
> +    /// Convert this [`CStr`] into a [`CString`] by allocating memory and
> +    /// copying over the string data.
> +    pub fn to_cstring(&self) -> Result<CString, AllocError> {
> +        CString::try_from(self)
> +    }
>  }
>  
>  impl fmt::Display for CStr {
> @@ -584,6 +591,21 @@ impl Deref for CString {
>      }
>  }
>  
> +impl<'a> TryFrom<&'a CStr> for CString {
> +    type Error = AllocError;
> +
> +    fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
> +        let mut buf = Vec::new();
> +
> +        buf.try_extend_from_slice(cstr.as_bytes_with_nul())
> +            .map_err(|_| AllocError)?;
> +
> +        // INVARIANT: The `CStr` and `CString` types have the same invariants for
> +        // the string data, and we copied it over without changes.
> +        Ok(CString { buf })
> +    }
> +}
> +
>  /// A convenience alias for [`core::format_args`].
>  #[macro_export]
>  macro_rules! fmt {
>
> base-commit: ea76e08f4d901a450619831a255e9e0a4c0ed162


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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-15 18:12     ` Andreas Hindborg
@ 2023-05-16 11:12       ` Alice Ryhl
  2023-05-17 18:09         ` Gary Guo
  0 siblings, 1 reply; 9+ messages in thread
From: Alice Ryhl @ 2023-05-16 11:12 UTC (permalink / raw)
  To: nmi
  Cc: alex.gaynor, alice, benno.lossin, bjorn3_gh, boqun.feng, gary,
	linux-kernel, ojeda, patches, rust-for-linux, wedsonaf, yakoyoku

Andreas Hindborg <nmi@metaspace.dk> writes:
> Alice Ryhl <alice@ryhl.io> writes:
>> On 5/8/23 13:41, Gary Guo wrote:
>>> On Wed,  3 May 2023 14:10:16 +0000
>>> Alice Ryhl <aliceryhl@google.com> wrote:
>>>> These methods can be used to copy the data in a temporary c string into
>>>> a separate allocation, so that it can be accessed later even if the
>>>> original is deallocated.
>>>>
>>>> The API in this change mirrors the standard library API for the `&str`
>>>> and `String` types. The `ToOwned` trait is not implemented because it
>>>> assumes that allocations are infallible.
>>> How about add a `TryToOwned` trait to the kernel crate and implement
>>> that trait for `CStr` instead?
>>
>> Eh, I don't think it's worth it. It doesn't give anything new to the CStr api,
>> and I think it's rather unlikely that someone will actually need to be generic
>> over such a trait any time soon.
> 
> It is just as valid as having `From<&str>` and `ToOwned<&str>`. While it
> does not add anything in terms of function, it carries intention. I
> think we should consider adding it at some point.
> 
> BR Andreas

Sure, I think its quite reasonable to add new traits, I just don't think
it should be part of this patch. Adding new traits makes it a
significantly bigger change IMO, and my changes have an actual user down
the road.

Alice

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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-16 11:12       ` Alice Ryhl
@ 2023-05-17 18:09         ` Gary Guo
  0 siblings, 0 replies; 9+ messages in thread
From: Gary Guo @ 2023-05-17 18:09 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: nmi, alex.gaynor, alice, benno.lossin, bjorn3_gh, boqun.feng,
	linux-kernel, ojeda, patches, rust-for-linux, wedsonaf, yakoyoku

On Tue, 16 May 2023 11:12:02 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> Andreas Hindborg <nmi@metaspace.dk> writes:
> > Alice Ryhl <alice@ryhl.io> writes:  
> >> On 5/8/23 13:41, Gary Guo wrote:  
> >>> On Wed,  3 May 2023 14:10:16 +0000
> >>> Alice Ryhl <aliceryhl@google.com> wrote:  
> >>>> These methods can be used to copy the data in a temporary c string into
> >>>> a separate allocation, so that it can be accessed later even if the
> >>>> original is deallocated.
> >>>>
> >>>> The API in this change mirrors the standard library API for the `&str`
> >>>> and `String` types. The `ToOwned` trait is not implemented because it
> >>>> assumes that allocations are infallible.  
> >>> How about add a `TryToOwned` trait to the kernel crate and implement
> >>> that trait for `CStr` instead?  
> >>
> >> Eh, I don't think it's worth it. It doesn't give anything new to the CStr api,
> >> and I think it's rather unlikely that someone will actually need to be generic
> >> over such a trait any time soon.  
> > 
> > It is just as valid as having `From<&str>` and `ToOwned<&str>`. While it
> > does not add anything in terms of function, it carries intention. I
> > think we should consider adding it at some point.
> > 
> > BR Andreas  
> 
> Sure, I think its quite reasonable to add new traits, I just don't think
> it should be part of this patch. Adding new traits makes it a
> significantly bigger change IMO, and my changes have an actual user down
> the road.
> 
> Alice

Personally I think `CStr` to `CString` conversion should be implemented
on top of `[u8]` to `Vec<u8>` conversion. Now we have two
conversions that fit in the concept of `TryToOwned`, so a trait is
warranted.

Best,
Gary

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

* Re: [PATCH v2] rust: str: add conversion from `CStr` to `CString`
  2023-05-03 14:10 [PATCH v2] rust: str: add conversion from `CStr` to `CString` Alice Ryhl
                   ` (2 preceding siblings ...)
  2023-05-15 18:36 ` Andreas Hindborg
@ 2023-05-31 17:09 ` Miguel Ojeda
  3 siblings, 0 replies; 9+ messages in thread
From: Miguel Ojeda @ 2023-05-31 17:09 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: Miguel Ojeda, Wedson Almeida Filho, Alex Gaynor, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin,
	Martin Rodriguez Reboredo, rust-for-linux, linux-kernel, patches

On Wed, May 3, 2023 at 4:10 PM Alice Ryhl <aliceryhl@google.com> wrote:
>
> These methods can be used to copy the data in a temporary c string into
> a separate allocation, so that it can be accessed later even if the
> original is deallocated.
>
> The API in this change mirrors the standard library API for the `&str`
> and `String` types. The `ToOwned` trait is not implemented because it
> assumes that allocations are infallible.
>
> Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Applied to `rust-next` -- thanks everyone!

Cheers,
Miguel

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

end of thread, other threads:[~2023-05-31 17:10 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-05-03 14:10 [PATCH v2] rust: str: add conversion from `CStr` to `CString` Alice Ryhl
2023-05-03 19:01 ` Martin Rodriguez Reboredo
2023-05-08 11:41 ` Gary Guo
2023-05-08 20:29   ` Alice Ryhl
2023-05-15 18:12     ` Andreas Hindborg
2023-05-16 11:12       ` Alice Ryhl
2023-05-17 18:09         ` Gary Guo
2023-05-15 18:36 ` Andreas Hindborg
2023-05-31 17:09 ` Miguel Ojeda

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).