All of lore.kernel.org
 help / color / mirror / Atom feed
From: ojeda@kernel.org
To: "Miguel Ojeda" <ojeda@kernel.org>,
	"Wedson Almeida Filho" <wedsonaf@gmail.com>,
	"Alex Gaynor" <alex.gaynor@gmail.com>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
	patches@lists.linux.dev
Subject: [PATCH v2 21/28] rust: str: add `CString` type
Date: Fri,  2 Dec 2022 17:14:52 +0100	[thread overview]
Message-ID: <20221202161502.385525-22-ojeda@kernel.org> (raw)
In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org>

From: Wedson Almeida Filho <wedsonaf@gmail.com>

Add the `CString` type, which is an owned string that is guaranteed
to have exactly one `NUL` byte at the end, i.e. the owned equivalent
to `CStr` introduced earlier.

It is used for interoperability with kernel APIs that take C strings.

In order to do so, implement the `RawFormatter::new()` constructor
and the `RawFormatter::bytes_written()` method as well.

Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
[Reworded, adapted for upstream and applied latest changes]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
---
 rust/kernel/str.rs | 91 +++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 89 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index ce207d1b3d2a..17dc8d273302 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -2,6 +2,7 @@
 
 //! String representations.
 
+use alloc::vec::Vec;
 use core::fmt::{self, Write};
 use core::ops::{self, Deref, Index};
 
@@ -384,13 +385,22 @@ mod tests {
 /// is less than `end`.
 pub(crate) struct RawFormatter {
     // Use `usize` to use `saturating_*` functions.
-    #[allow(dead_code)]
     beg: usize,
     pos: usize,
     end: usize,
 }
 
 impl RawFormatter {
+    /// Creates a new instance of [`RawFormatter`] with an empty buffer.
+    fn new() -> Self {
+        // INVARIANT: The buffer is empty, so the region that needs to be writable is empty.
+        Self {
+            beg: 0,
+            pos: 0,
+            end: 0,
+        }
+    }
+
     /// Creates a new instance of [`RawFormatter`] with the given buffer pointers.
     ///
     /// # Safety
@@ -429,6 +439,11 @@ impl RawFormatter {
     pub(crate) fn pos(&self) -> *mut u8 {
         self.pos as _
     }
+
+    /// Return the number of bytes written to the formatter.
+    pub(crate) fn bytes_written(&self) -> usize {
+        self.pos - self.beg
+    }
 }
 
 impl fmt::Write for RawFormatter {
@@ -469,7 +484,6 @@ impl Formatter {
     ///
     /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
     /// for the lifetime of the returned [`Formatter`].
-    #[allow(dead_code)]
     pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
         // SAFETY: The safety requirements of this function satisfy those of the callee.
         Self(unsafe { RawFormatter::from_buffer(buf, len) })
@@ -496,3 +510,76 @@ impl fmt::Write for Formatter {
         }
     }
 }
+
+/// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
+///
+/// Used for interoperability with kernel APIs that take C strings.
+///
+/// # Invariants
+///
+/// The string is always `NUL`-terminated and contains no other `NUL` bytes.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::str::CString;
+///
+/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap();
+/// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes());
+///
+/// let tmp = "testing";
+/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap();
+/// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes());
+///
+/// // This fails because it has an embedded `NUL` byte.
+/// let s = CString::try_from_fmt(fmt!("a\0b{}", 123));
+/// assert_eq!(s.is_ok(), false);
+/// ```
+pub struct CString {
+    buf: Vec<u8>,
+}
+
+impl CString {
+    /// Creates an instance of [`CString`] from the given formatted arguments.
+    pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
+        // Calculate the size needed (formatted string plus `NUL` terminator).
+        let mut f = RawFormatter::new();
+        f.write_fmt(args)?;
+        f.write_str("\0")?;
+        let size = f.bytes_written();
+
+        // Allocate a vector with the required number of bytes, and write to it.
+        let mut buf = Vec::try_with_capacity(size)?;
+        // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
+        let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
+        f.write_fmt(args)?;
+        f.write_str("\0")?;
+
+        // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is
+        // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`.
+        unsafe { buf.set_len(f.bytes_written()) };
+
+        // Check that there are no `NUL` bytes before the end.
+        // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size`
+        // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator)
+        // so `f.bytes_written() - 1` doesn't underflow.
+        let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) };
+        if !ptr.is_null() {
+            return Err(EINVAL);
+        }
+
+        // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes
+        // exist in the buffer.
+        Ok(Self { buf })
+    }
+}
+
+impl Deref for CString {
+    type Target = CStr;
+
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no
+        // other `NUL` bytes exist.
+        unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
+    }
+}
-- 
2.38.1


  parent reply	other threads:[~2022-12-02 16:16 UTC|newest]

Thread overview: 46+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2022-12-02 16:14 [PATCH v2 00/28] Rust core additions ojeda
2022-12-02 16:14 ` [PATCH v2 01/28] rust: prelude: split re-exports into groups ojeda
2022-12-02 16:14 ` [PATCH v2 02/28] rust: print: add more `pr_*!` levels ojeda
2022-12-02 16:14 ` [PATCH v2 03/28] rust: print: add `pr_cont!` macro ojeda
2022-12-02 16:14 ` [PATCH v2 04/28] rust: samples: add `rust_print` example ojeda
2022-12-02 16:14 ` [PATCH v2 05/28] rust: macros: add `concat_idents!` proc macro ojeda
2022-12-04  0:20   ` Gary Guo
2022-12-02 16:14 ` [PATCH v2 06/28] rust: macros: add `#[vtable]` " ojeda
2022-12-06 12:49   ` Finn Behrens
2022-12-06 15:44     ` Miguel Ojeda
2022-12-02 16:14 ` [PATCH v2 07/28] rust: macros: take string literals in `module!` ojeda
2022-12-02 16:14 ` [PATCH v2 08/28] rust: error: declare errors using macro ojeda
2022-12-02 16:14 ` [PATCH v2 09/28] rust: error: add codes from `errno-base.h` ojeda
2022-12-06 12:52   ` Finn Behrens
2022-12-02 16:14 ` [PATCH v2 10/28] rust: error: add `From` implementations for `Error` ojeda
2022-12-02 16:14 ` [PATCH v2 11/28] rust: prelude: add `error::code::*` constant items ojeda
2022-12-02 16:14 ` [PATCH v2 12/28] rust: alloc: add `RawVec::try_with_capacity_in()` constructor ojeda
2022-12-02 16:14 ` [PATCH v2 13/28] rust: alloc: add `Vec::try_with_capacity{,_in}()` constructors ojeda
2022-12-06 12:55   ` Finn Behrens
2022-12-02 16:14 ` [PATCH v2 14/28] rust: str: add `BStr` type ojeda
2022-12-02 16:14 ` [PATCH v2 15/28] rust: str: add `b_str!` macro ojeda
2022-12-02 16:14 ` [PATCH v2 16/28] rust: str: add `CStr` type ojeda
2022-12-02 16:14 ` [PATCH v2 17/28] rust: str: implement several traits for `CStr` ojeda
2022-12-02 16:14 ` [PATCH v2 18/28] rust: str: add `CStr` unit tests ojeda
2022-12-02 16:14 ` [PATCH v2 19/28] rust: str: add `c_str!` macro ojeda
2022-12-02 16:14 ` [PATCH v2 20/28] rust: str: add `Formatter` type ojeda
2022-12-04 15:41   ` Dr. David Alan Gilbert
2022-12-04 17:26     ` Wedson Almeida Filho
2022-12-04 18:05       ` Dr. David Alan Gilbert
2022-12-02 16:14 ` ojeda [this message]
2022-12-02 16:14 ` [PATCH v2 22/28] rust: str: add `fmt!` macro ojeda
2022-12-02 16:14 ` [PATCH v2 23/28] rust: std_vendor: add `dbg!` macro based on `std`'s one ojeda
2022-12-02 16:14 ` [PATCH v2 24/28] rust: static_assert: add `static_assert!` macro ojeda
2022-12-02 16:14 ` [PATCH v2 25/28] rust: add `build_error` crate ojeda
2022-12-02 18:31   ` Wei Liu
2022-12-02 16:14 ` [PATCH v2 26/28] rust: build_assert: add `build_{error,assert}!` macros ojeda
2022-12-02 18:32   ` Wei Liu
2022-12-02 16:14 ` [PATCH v2 27/28] rust: types: add `Either` type ojeda
2022-12-02 23:41   ` Josh Triplett
2022-12-04  0:58     ` Miguel Ojeda
2022-12-04 10:31     ` Gary Guo
2022-12-04 17:36       ` Wedson Almeida Filho
2022-12-05 13:53         ` Miguel Ojeda
2022-12-05 23:00         ` Josh Triplett
2022-12-02 16:14 ` [PATCH v2 28/28] rust: types: add `Opaque` type ojeda
2022-12-04  1:05 ` [PATCH v2 00/28] Rust core additions Miguel Ojeda

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20221202161502.385525-22-ojeda@kernel.org \
    --to=ojeda@kernel.org \
    --cc=alex.gaynor@gmail.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=gary@garyguo.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=patches@lists.linux.dev \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=wedsonaf@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.