From 35c62ff74a35218e4eb7eb6697f8a0286e1be796 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Wed, 7 Jun 2023 20:43:54 -0700 Subject: [PATCH] Remove use of 'unsafe' in 'RawStr' doctests. --- core/http/src/raw_str.rs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/core/http/src/raw_str.rs b/core/http/src/raw_str.rs index b22d6c88..56aef7b2 100644 --- a/core/http/src/raw_str.rs +++ b/core/http/src/raw_str.rs @@ -173,9 +173,7 @@ impl RawStr { /// # extern crate rocket; /// use rocket::http::RawStr; /// - /// // Note: Rocket should never hand you a bad `&RawStr`. - /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a=\xff") }; - /// let bad_raw_str = RawStr::new(bad_str); + /// let bad_raw_str = RawStr::new("%FF"); /// assert!(bad_raw_str.percent_decode().is_err()); /// ``` #[inline(always)] @@ -206,9 +204,7 @@ impl RawStr { /// # extern crate rocket; /// use rocket::http::RawStr; /// - /// // Note: Rocket should never hand you a bad `&RawStr`. - /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a=\xff") }; - /// let bad_raw_str = RawStr::new(bad_str); + /// let bad_raw_str = RawStr::new("a=%FF"); /// assert_eq!(bad_raw_str.percent_decode_lossy(), "a=�"); /// ``` #[inline(always)] @@ -225,6 +221,15 @@ impl RawStr { allocated = string.into(); } + // SAFETY: + // + // 1. The caller must ensure that the content of the slice is valid + // UTF-8 before the borrow ends and the underlying `str` is used. + // + // `allocated[i]` is `+` since that is what we searched for. The + // `+` char is ASCII => the character is one byte wide. ' ' is + // also one byte and ASCII => UTF-8. The replacement of `+` with + // ` ` thus yields a valid UTF-8 string. unsafe { allocated.as_bytes_mut()[i] = b' '; } } @@ -255,9 +260,7 @@ impl RawStr { /// # extern crate rocket; /// use rocket::http::RawStr; /// - /// // NOTE: Rocket will never hand you a bad `&RawStr`. - /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a=\xff") }; - /// let bad_raw_str = RawStr::new(bad_str); + /// let bad_raw_str = RawStr::new("%FF"); /// assert!(bad_raw_str.percent_decode().is_err()); /// ``` #[inline(always)] @@ -334,9 +337,7 @@ impl RawStr { /// # extern crate rocket; /// use rocket::http::RawStr; /// - /// // Note: Rocket should never hand you a bad `&RawStr`. - /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a+b=\xff") }; - /// let bad_raw_str = RawStr::new(bad_str); + /// let bad_raw_str = RawStr::new("a+b=%FF"); /// assert_eq!(bad_raw_str.url_decode_lossy(), "a b=�"); /// ``` pub fn url_decode_lossy(&self) -> Cow<'_, str> {