Struct rocket::http::RawStr[]

#[repr(transparent)]pub struct RawStr(_);

A reference to a string inside of a raw HTTP message.

A RawStr is an unsanitzed, unvalidated, and undecoded raw string from an HTTP message. It exists to separate validated string inputs, represented by the String, &str, and Cow<str> types, from unvalidated inputs, represented by &RawStr.

Validation

An &RawStr should be converted into one of the validated string input types through methods on RawStr. These methods are summarized below:

Note: Template engines like Tera and Handlebars all functions like html_escape() on all rendered template outputs by default.

Usage

A RawStr is a dynamically sized type (just like str). It is always used through a reference an as &RawStr (just like &str). You’ll likely encounter an &RawStr as a parameter via FromParam or as a form value via FromFormValue.

Implementations

impl RawStr

pub fn new<S>(string: &S) -> &RawStr where
    S: AsRef<str> + ?Sized

Constructs an &RawStr from a string-like type at no cost.

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello, world!");

// `into` can also be used; note that the type must be specified
let raw_str: &RawStr = "Hello, world!".into();

pub fn percent_decode(&self) -> Result<Cow<'_, str>, Utf8Error>

Returns a percent-decoded version of the string.

Errors

Returns an Err if the percent encoded values are not valid UTF-8.

Example

With a valid string:

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello%21");
let decoded = raw_str.percent_decode();
assert_eq!(decoded, Ok("Hello!".into()));

With an invalid string:

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);
assert!(bad_raw_str.percent_decode().is_err());

pub fn percent_decode_lossy(&self) -> Cow<'_, str>

Returns a percent-decoded version of the string. Any invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD, the replacement character.

Example

With a valid string:

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello%21");
let decoded = raw_str.percent_decode_lossy();
assert_eq!(decoded, "Hello!");

With an invalid string:

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);
assert_eq!(bad_raw_str.percent_decode_lossy(), "a=�");

pub fn url_decode(&self) -> Result<Cow<'_, str>, Utf8Error>

Returns a URL-decoded version of the string. This is identical to percent decoding except that + characters are converted into spaces. This is the encoding used by form values.

Errors

Returns an Err if the percent encoded values are not valid UTF-8.

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello%2C+world%21");
let decoded = raw_str.url_decode();
assert_eq!(decoded.unwrap(), "Hello, world!");

pub fn url_decode_lossy(&self) -> Cow<'_, str>

Returns a URL-decoded version of the string.

Any invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD, the replacement character. This is identical to lossy percent decoding except that + characters are converted into spaces. This is the encoding used by form values.

Example

With a valid string:

use rocket::http::RawStr;

let raw_str: &RawStr = "Hello%2C+world%21".into();
let decoded = raw_str.url_decode_lossy();
assert_eq!(decoded, "Hello, world!");

With an invalid string:

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);
assert_eq!(bad_raw_str.url_decode_lossy(), "a b=�");

pub fn html_escape(&self) -> Cow<'_, str>

Returns an HTML escaped version of self. Allocates only when characters need to be escaped.

The following characters are escaped: &, <, >, ", ', /, `. This suffices as long as the escaped string is not used in an execution context such as inside of <script> or <style> tags! See the OWASP XSS Prevention Rules for more information.

Example

Strings with HTML sequences are escaped:

use rocket::http::RawStr;

let raw_str: &RawStr = "<b>Hi!</b>".into();
let escaped = raw_str.html_escape();
assert_eq!(escaped, "&lt;b&gt;Hi!&lt;&#x2F;b&gt;");

let raw_str: &RawStr = "Hello, <i>world!</i>".into();
let escaped = raw_str.html_escape();
assert_eq!(escaped, "Hello, &lt;i&gt;world!&lt;&#x2F;i&gt;");

Strings without HTML sequences remain untouched:

use rocket::http::RawStr;

let raw_str: &RawStr = "Hello!".into();
let escaped = raw_str.html_escape();
assert_eq!(escaped, "Hello!");

let raw_str: &RawStr = "大阪".into();
let escaped = raw_str.html_escape();
assert_eq!(escaped, "大阪");

pub const fn len(&self) -> usize

Returns the length of self.

This length is in bytes, not chars or graphemes. In other words, it may not be what a human considers the length of the string.

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello, world!");
assert_eq!(raw_str.len(), 13);

pub const fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello, world!");
assert!(!raw_str.is_empty());

let raw_str = RawStr::new("");
assert!(raw_str.is_empty());

pub const fn as_str(&self) -> &str

Converts self into an &str.

This method should be used sparingly. Only use this method when you are absolutely certain that doing so is safe.

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("Hello, world!");
assert_eq!(raw_str.as_str(), "Hello, world!");

pub const fn as_bytes(&self) -> &[u8]

Notable traits for &'_ [u8]

impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]

Converts self into an &[u8].

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("hi");
assert_eq!(raw_str.as_bytes(), &[0x68, 0x69]);

pub const fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

As string slices are a slice of bytes, the raw pointer points to a u8. This pointer will be pointing to the first byte of the string slice.

The caller must ensure that the returned pointer is never written to. If you need to mutate the contents of the string slice, use as_mut_ptr.

Examples

Basic usage:

use rocket::http::RawStr;

let raw_str = RawStr::new("hi");
let ptr = raw_str.as_ptr();

pub fn as_uncased_str(&self) -> &UncasedStr

Converts self into an &UncasedStr.

This method should be used sparingly. Only use this method when you are absolutely certain that doing so is safe.

Example

use rocket::http::RawStr;

let raw_str = RawStr::new("Content-Type");
assert!(raw_str.as_uncased_str() == "content-TYPE");

pub fn contains<'a, P>(&'a self, pat: P) -> bool where
    P: Pattern<'a>, 

Returns true if the given pattern matches a sub-slice of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Examples

Basic usage:

use rocket::http::RawStr;

let bananas = RawStr::new("bananas");

assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));

pub fn starts_with<'a, P>(&'a self, pat: P) -> bool where
    P: Pattern<'a>, 

Returns true if the given pattern matches a prefix of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Examples

Basic usage:

use rocket::http::RawStr;

let bananas = RawStr::new("bananas");

assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));

pub fn ends_with<'a, P>(&'a self, pat: P) -> bool where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, 

Returns true if the given pattern matches a suffix of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Examples

Basic usage:

use rocket::http::RawStr;

let bananas = RawStr::new("bananas");

assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));

pub fn find<'a, P>(&'a self, pat: P) -> Option<usize> where
    P: Pattern<'a>, 

Returns the byte index of the first character of this string slice that matches the pattern.

Returns None if the pattern doesn’t match.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Example

use rocket::http::RawStr;

let s = RawStr::new("Löwe 老虎 Léopard Gepardi");

assert_eq!(s.find('L'), Some(0));
assert_eq!(s.find('é'), Some(14));
assert_eq!(s.find("pard"), Some(17));

pub fn split<'a, P>(&'a self, pat: P) -> impl Iterator<Item = &'a RawStr> where
    P: Pattern<'a>, 

An iterator over substrings of this string slice, separated by characters matched by a pattern.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Examples

Simple patterns:

use rocket::http::RawStr;

let v: Vec<_> = RawStr::new("Mary had a little lamb")
    .split(' ')
    .map(|r| r.as_str())
    .collect();

assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

pub fn split_at_byte(&self, b: u8) -> (&RawStr, &RawStr)

Splits self into two pieces: the piece before the first byte b and the piece after (not including b). Returns the tuple (before, after). If b is not in self, or b is not an ASCII characters, returns the entire string self as before and the empty string as after.

Example

use rocket::http::RawStr;

let haystack = RawStr::new("a good boy!");

let (before, after) = haystack.split_at_byte(b'a');
assert_eq!(before, "");
assert_eq!(after, " good boy!");

let (before, after) = haystack.split_at_byte(b' ');
assert_eq!(before, "a");
assert_eq!(after, "good boy!");

let (before, after) = haystack.split_at_byte(b'o');
assert_eq!(before, "a g");
assert_eq!(after, "od boy!");

let (before, after) = haystack.split_at_byte(b'!');
assert_eq!(before, "a good boy");
assert_eq!(after, "");

let (before, after) = haystack.split_at_byte(b'?');
assert_eq!(before, "a good boy!");
assert_eq!(after, "");

let haystack = RawStr::new("");
let (before, after) = haystack.split_at_byte(b' ');
assert_eq!(before, "");
assert_eq!(after, "");

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err> where
    F: FromStr

Parses this string slice into another type.

Because parse is so general, it can cause problems with type inference. As such, parse is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: ::<>. This helps the inference algorithm understand specifically which type you’re trying to parse into.

parse can parse any type that implements the [FromStr] trait.

Errors

Will return Err if it’s not possible to parse this string slice into the desired type.

Examples

Basic usage

use rocket::http::RawStr;

let four: u32 = RawStr::new("4").parse().unwrap();

assert_eq!(4, four);

Trait Implementations

impl AsRef<[u8]> for RawStr

impl AsRef<Key> for RawStr[src]

impl AsRef<Name> for RawStr[src]

impl AsRef<str> for RawStr

impl<'_> Borrow<RawStr> for &'_ str

impl Borrow<str> for RawStr

impl Debug for RawStr

impl<'de, 'a> Deserialize<'de> for &'a RawStr where
    'de: 'a, 

impl Display for RawStr

impl Eq for RawStr

impl<'a> From<&'a str> for &'a RawStr

impl<'r> FromData<'r> for &'r RawStr[src]

type Error = <Capped<Self> as FromData<'r>>::Error

The associated error to be returned when the guard fails.

impl Hash for RawStr

impl<I> Index<I> for RawStr where
    I: SliceIndex<str, Output = str>, 

type Output = RawStr

The returned type after indexing.

impl Ord for RawStr

impl<'_, '_> PartialEq<&'_ &'_ str> for RawStr

impl<'_> PartialEq<&'_ RawStr> for str

impl<'_> PartialEq<&'_ RawStr> for RawStr

impl<'_> PartialEq<&'_ str> for RawStr

impl<'_, '_> PartialEq<Cow<'_, str>> for &'_ RawStr

impl<'_> PartialEq<Cow<'_, str>> for RawStr

impl PartialEq<RawStr> for str

impl<'_> PartialEq<RawStr> for &'_ str

impl<'_> PartialEq<RawStr> for &'_ RawStr

impl PartialEq<RawStr> for RawStr

impl PartialEq<String> for RawStr

impl<'_> PartialEq<String> for &'_ RawStr

impl PartialEq<str> for RawStr

impl<'_> PartialEq<str> for &'_ RawStr

impl<'_, '_> PartialOrd<&'_ &'_ str> for RawStr

impl<'_> PartialOrd<&'_ RawStr> for RawStr

impl<'_> PartialOrd<&'_ RawStr> for str

impl<'_> PartialOrd<&'_ str> for RawStr

impl<'_> PartialOrd<Cow<'_, str>> for RawStr

impl<'_, '_> PartialOrd<Cow<'_, str>> for &'_ RawStr

impl PartialOrd<RawStr> for RawStr

impl<'_> PartialOrd<RawStr> for &'_ str

impl PartialOrd<RawStr> for str

impl<'_> PartialOrd<RawStr> for &'_ RawStr

impl PartialOrd<String> for RawStr

impl<'_> PartialOrd<String> for &'_ RawStr

impl PartialOrd<str> for RawStr

impl<'_> PartialOrd<str> for &'_ RawStr

impl RefCast for RawStr

type From = str

impl Serialize for RawStr

impl StructuralEq for RawStr

impl StructuralPartialEq for RawStr

Auto Trait Implementations

impl RefUnwindSafe for RawStr

impl Send for RawStr

impl !Sized for RawStr

impl Sync for RawStr

impl Unpin for RawStr

impl UnwindSafe for RawStr

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> AsUncased for T where
    T: AsRef<str> + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<Q, K> Equivalent<K> for Q where
    K: Borrow<Q> + ?Sized,
    Q: Eq + ?Sized
[src]

impl<T> ToString for T where
    T: Display + ?Sized
[src]