rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Alice Ryhl <aliceryhl@google.com>
To: yutaro.ono.418@gmail.com
Cc: a.hindborg@samsung.com, alex.gaynor@gmail.com,
	aliceryhl@google.com,  armavica@ulminfo.fr,
	benno.lossin@proton.me, bjorn3_gh@protonmail.com,
	 boqun.feng@gmail.com, gary@garyguo.net, ojeda@kernel.org,
	 rust-for-linux@vger.kernel.org, wedsonaf@gmail.com
Subject: Re: [PATCH V2] rust: str: implement `Display` and `Debug` for `BStr`
Date: Mon, 29 Jan 2024 12:18:59 +0000	[thread overview]
Message-ID: <20240129121859.1099000-1-aliceryhl@google.com> (raw)
In-Reply-To: <ZbSDkm65LML4OWKX@ohnotp>

Yutaro Ohno <yutaro.ono.418@gmail.com> writes:
> Currently, `BStr` is just a type alias of `[u8]`, limiting its
> representation to a byte list rather than a character list, which is not
> ideal for printing and debugging.
> 
> Implement `Display` and `Debug` traits for `BStr` to facilitate easier
> printing and debugging.
> 
> Also, for this purpose, change `BStr` from a type alias of `[u8]` to a
> struct wrapper of `[u8]`.
> 
> Co-developed-by: Virgile Andreani <armavica@ulminfo.fr>
> Signed-off-by: Virgile Andreani <armavica@ulminfo.fr>
> Signed-off-by: Yutaro Ohno <yutaro.ono.418@gmail.com>
>
> [...]
>
> +impl fmt::Display for BStr {
> +    /// Formats printable ASCII characters, escaping the rest.
> +    ///
> +    /// ```
> +    /// # use kernel::{fmt, b_str, str::{BStr, CString}};
> +    /// let ascii = b_str!("Hello, BStr!");
> +    /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
> +    /// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes());
> +    ///
> +    /// let non_ascii = b_str!("🦀");
> +    /// let s = CString::try_from_fmt(fmt!("{}", non_ascii)).unwrap();
> +    /// assert_eq!(s.as_bytes(), "\\xf0\\x9f\\xa6\\x80".as_bytes());
> +    /// ```
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        for &b in &self.0 {
> +            match b {
> +                // Printable characters.
> +                0x20..=0x7e => f.write_char(b as char)?,
> +                _ => write!(f, "\\x{:02x}", b)?,
> +            }
> +        }
> +        Ok(())
> +    }
> +}

What about newlines and tabs? Those are printable.

If you are intentionally excluding them, please add a comment saying that.

> +impl fmt::Debug for BStr {
> +    /// Formats printable ASCII characters with a double quote on either end,
> +    /// escaping the rest.
> +    ///
> +    /// ```
> +    /// # use kernel::{fmt, b_str, str::{BStr, CString}};
> +    /// // Embedded double quotes are escaped.
> +    /// let ascii = b_str!("Hello, \"BStr\"!");
> +    /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
> +    /// assert_eq!(s.as_bytes(), "\"Hello, \\\"BStr\\\"!\"".as_bytes());
> +    ///
> +    /// let non_ascii = b_str!("😺");
> +    /// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii)).unwrap();
> +    /// assert_eq!(s.as_bytes(), "\"\\xf0\\x9f\\x98\\xba\"".as_bytes());
> +    /// ```
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        f.write_str("\"")?;
> +        for &b in &self.0 {
> +            match b {
> +                // Printable characters.
> +                b'\"' => f.write_str("\\\"")?,
> +                0x20..=0x7e => f.write_char(b as char)?,
> +                _ => write!(f, "\\x{:02x}", b)?,
> +            }
> +        }
> +        f.write_str("\"")
> +    }
> +}

This escapes quotes, but what about backslashes?

Also, perhaps `write_char('"')` makes more sense than `write_str("\"")`?

>  macro_rules! b_str {
>      ($str:literal) => {{
>          const S: &'static str = $str;
> -        const C: &'static $crate::str::BStr = S.as_bytes();
> +        const C: &'static $crate::str::BStr = BStr::from_bytes(S.as_bytes());
>          C
>      }};
>  }

This should use the full path both times:

const C: &'static $crate::str::BStr = $crate::str::BStr::from_bytes(S.as_bytes());

Alice

  reply	other threads:[~2024-01-29 12:19 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-01-27  4:16 [PATCH V2] rust: str: implement `Display` and `Debug` for `BStr` Yutaro Ohno
2024-01-29 12:18 ` Alice Ryhl [this message]
2024-01-29 17:26   ` Miguel Ojeda
2024-01-31  4:58   ` Yutaro Ohno

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=20240129121859.1099000-1-aliceryhl@google.com \
    --to=aliceryhl@google.com \
    --cc=a.hindborg@samsung.com \
    --cc=alex.gaynor@gmail.com \
    --cc=armavica@ulminfo.fr \
    --cc=benno.lossin@proton.me \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=gary@garyguo.net \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=wedsonaf@gmail.com \
    --cc=yutaro.ono.418@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 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).