fluent_uri::encoding

Struct EString

source
pub struct EString<E: Encoder> { /* private fields */ }
Expand description

A percent-encoded, growable string.

The borrowed counterpart of EString is EStr. See its documentation for the meaning of the type parameter E.

§Comparison

EStrings are compared lexicographically by their byte values. Normalization is not performed prior to comparison.

§Examples

Encode key-value pairs to a query string and use it to build a URI reference:

use fluent_uri::{
    encoding::{
        encoder::{Data, Query},
        EStr, EString, Encoder, Table,
    },
    UriRef,
};

let pairs = [("name", "张三"), ("speech", "¡Olé!")];
let mut buf = EString::<Query>::new();
for (k, v) in pairs {
    if !buf.is_empty() {
        buf.push('&');
    }

    // WARNING: Absolutely do not confuse data with delimiters! Use `Data`
    // to encode data contained in a URI unless you know what you're doing!
    //
    // `Data` preserves only unreserved characters and encodes the others,
    // which is always safe to use but may be wasteful of memory because
    // usually not all reserved characters are used as delimiters and you can
    // choose to preserve some of them. See below for an example of creating
    // a custom encoder based on an existing one.
    buf.encode::<Data>(k);
    buf.push('=');
    buf.encode::<Data>(v);
}

assert_eq!(buf, "name=%E5%BC%A0%E4%B8%89&speech=%C2%A1Ol%C3%A9%21");

let uri_ref = UriRef::builder()
    .path(EStr::EMPTY)
    .query(&buf)
    .build()
    .unwrap();
assert_eq!(uri_ref.as_str(), "?name=%E5%BC%A0%E4%B8%89&speech=%C2%A1Ol%C3%A9%21");

Encode a path whose segments may contain the slash ('/') character by using a custom encoder:

use fluent_uri::encoding::{encoder::Path, EString, Encoder, Table};

struct PathSegment;

impl Encoder for PathSegment {
    const TABLE: &'static Table = &Path::TABLE.sub(&Table::new(b"/"));
}

let mut path = EString::<Path>::new();
path.push('/');
path.encode::<PathSegment>("foo/bar");

assert_eq!(path, "/foo%2Fbar");

Implementations§

source§

impl<E: Encoder> EString<E>

source

pub fn new() -> Self

Creates a new empty EString.

source

pub fn with_capacity(capacity: usize) -> Self

Creates a new empty EString with at least the specified capacity.

source

pub fn as_estr(&self) -> &EStr<E>

Coerces to an EStr slice.

source

pub fn capacity(&self) -> usize

Returns this EString’s capacity, in bytes.

source

pub fn encode<SubE: Encoder>(&mut self, s: &(impl AsRef<[u8]> + ?Sized))

Encodes a byte sequence with a sub-encoder and appends the result onto the end of this EString.

A byte will be preserved if and only if it is part of a UTF-8-encoded character that SubE::TABLE allows. It will be percent-encoded otherwise. When encoding data, make sure that SubE::TABLE does not allow the component delimiters that delimit the data.

Note that this method will not encode 0x20 (space) as U+002B (+).

§Panics

Panics at compile time if SubE is not a sub-encoder of E, or if SubE::TABLE does not allow percent-encoded octets.

source

pub fn push(&mut self, ch: char)

Appends an unencoded character onto the end of this EString.

§Panics

Panics if E::TABLE does not allow the character.

source

pub fn push_estr(&mut self, s: &EStr<E>)

Appends an EStr slice onto the end of this EString.

source

pub fn clear(&mut self)

Truncates this EString, removing all contents.

source

pub fn into_string(self) -> String

Consumes this EString and yields the underlying String.

Methods from Deref<Target = EStr<E>>§

source

pub const EMPTY: &'static Self = _

source

pub fn as_str(&self) -> &str

Yields the underlying string slice.

source

pub fn len(&self) -> usize

Returns the length of the EStr slice in bytes.

source

pub fn is_empty(&self) -> bool

Checks whether the EStr slice is empty.

source

pub fn decode(&self) -> Decode<'_>

Decodes the EStr slice.

Always split before decoding, as otherwise the data may be mistaken for component delimiters.

This method allocates only when the slice contains any percent-encoded octet.

Note that this method will not decode U+002B (+) as 0x20 (space).

§Panics

Panics at compile time if E::TABLE does not allow percent-encoded octets.

§Examples
use fluent_uri::encoding::{encoder::Path, EStr};

let dec = EStr::<Path>::new_or_panic("%C2%A1Hola%21").decode();
assert_eq!(dec.as_bytes(), &[0xc2, 0xa1, 0x48, 0x6f, 0x6c, 0x61, 0x21]);
assert_eq!(dec.into_string().unwrap(), "¡Hola!");
source

pub fn split(&self, delim: char) -> Split<'_, E>

Returns an iterator over subslices of the EStr slice separated by the given delimiter.

§Panics

Panics if the delimiter is not a reserved character.

§Examples
use fluent_uri::encoding::{encoder::Path, EStr};

assert!(EStr::<Path>::new_or_panic("a,b,c").split(',').eq(["a", "b", "c"]));
assert!(EStr::<Path>::new_or_panic(",").split(',').eq(["", ""]));
assert!(EStr::<Path>::EMPTY.split(',').eq([""]));
source

pub fn split_once(&self, delim: char) -> Option<(&Self, &Self)>

Splits the EStr slice on the first occurrence of the given delimiter and returns prefix before delimiter and suffix after delimiter.

Returns None if the delimiter is not found.

§Panics

Panics if the delimiter is not a reserved character.

§Examples
use fluent_uri::encoding::{encoder::Path, EStr};

assert_eq!(
    EStr::<Path>::new_or_panic("foo;bar;baz").split_once(';'),
    Some((EStr::new_or_panic("foo"), EStr::new_or_panic("bar;baz")))
);

assert_eq!(EStr::<Path>::new_or_panic("foo").split_once(';'), None);
source

pub fn rsplit_once(&self, delim: char) -> Option<(&Self, &Self)>

Splits the EStr slice on the last occurrence of the given delimiter and returns prefix before delimiter and suffix after delimiter.

Returns None if the delimiter is not found.

§Panics

Panics if the delimiter is not a reserved character.

§Examples
use fluent_uri::encoding::{encoder::Path, EStr};

assert_eq!(
    EStr::<Path>::new_or_panic("foo;bar;baz").rsplit_once(';'),
    Some((EStr::new_or_panic("foo;bar"), EStr::new_or_panic("baz")))
);

assert_eq!(EStr::<Path>::new_or_panic("foo").rsplit_once(';'), None);
source

pub fn is_absolute(&self) -> bool

Checks whether the path is absolute, i.e., starting with '/'.

source

pub fn is_rootless(&self) -> bool

Checks whether the path is rootless, i.e., not starting with '/'.

source

pub fn segments_if_absolute(&self) -> Option<Split<'_, E>>

Returns an iterator over the path segments, separated by '/'.

Returns None if the path is rootless. Use split instead if you need to split a rootless path on occurrences of '/'.

Note that the path can be empty when authority is present, in which case this method will return None.

§Examples
use fluent_uri::Uri;

// Segments are separated by '/'.
// The empty string before a leading '/' is not a segment.
// However, segments can be empty in the other cases.
let path = Uri::parse("file:///path/to//dir/")?.path();
assert_eq!(path, "/path/to//dir/");
assert!(path.segments_if_absolute().unwrap().eq(["path", "to", "", "dir", ""]));

let path = Uri::parse("foo:bar/baz")?.path();
assert_eq!(path, "bar/baz");
assert!(path.segments_if_absolute().is_none());

let path = Uri::parse("http://example.com")?.path();
assert!(path.is_empty());
assert!(path.segments_if_absolute().is_none());

Trait Implementations§

source§

impl<E: Encoder> AsRef<EStr<E>> for EString<E>

source§

fn as_ref(&self) -> &EStr<E>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<E: Encoder> AsRef<str> for EString<E>

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<E: Encoder> Borrow<EStr<E>> for EString<E>

source§

fn borrow(&self) -> &EStr<E>

Immutably borrows from an owned value. Read more
source§

impl<E: Clone + Encoder> Clone for EString<E>

source§

fn clone(&self) -> EString<E>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<E: Encoder> Debug for EString<E>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<E: Default + Encoder> Default for EString<E>

source§

fn default() -> EString<E>

Returns the “default value” for a type. Read more
source§

impl<E: Encoder> Deref for EString<E>

source§

type Target = EStr<E>

The resulting type after dereferencing.
source§

fn deref(&self) -> &EStr<E>

Dereferences the value.
source§

impl<E: Encoder> Display for EString<E>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<E: Encoder> From<&EStr<E>> for EString<E>

source§

fn from(s: &EStr<E>) -> Self

Converts to this type from the input type.
source§

impl<E: Encoder> Hash for EString<E>

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<E: Encoder> Ord for EString<E>

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
source§

impl<E: Encoder> PartialEq<&EStr<E>> for EString<E>

source§

fn eq(&self, other: &&EStr<E>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<&str> for EString<E>

source§

fn eq(&self, other: &&str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<EStr<E>> for EString<E>

source§

fn eq(&self, other: &EStr<E>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<EString<E>> for &EStr<E>

source§

fn eq(&self, other: &EString<E>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<EString<E>> for &str

source§

fn eq(&self, other: &EString<E>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<EString<E>> for EStr<E>

source§

fn eq(&self, other: &EString<E>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<EString<E>> for str

source§

fn eq(&self, other: &EString<E>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq<str> for EString<E>

source§

fn eq(&self, other: &str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialEq for EString<E>

source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<E: Encoder> PartialOrd for EString<E>

source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<E: Encoder> Eq for EString<E>

Auto Trait Implementations§

§

impl<E> Freeze for EString<E>

§

impl<E> RefUnwindSafe for EString<E>
where E: RefUnwindSafe,

§

impl<E> Send for EString<E>
where E: Send,

§

impl<E> Sync for EString<E>
where E: Sync,

§

impl<E> Unpin for EString<E>
where E: Unpin,

§

impl<E> UnwindSafe for EString<E>
where E: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.