pct_str/encoder/mod.rs
1mod iri;
2mod uri;
3
4pub use iri::*;
5pub use uri::*;
6
7/// Encoding predicate.
8///
9/// Instances of this trait are used along with the [`encode`] function
10/// to decide which character must be percent-encoded.
11///
12/// This crate provides a simple implementation of the trait, [`UriReserved`]
13/// encoding characters reserved in the URI syntax.
14///
15/// [`encode`]: crate::PctString::encode
16///
17/// # Example
18///
19/// ```
20/// use pct_str::{PctString, UriReserved};
21///
22/// let pct_string = PctString::encode("Hello World!".chars(), UriReserved::Any);
23/// println!("{}", pct_string.as_str()); // => Hello World%21
24/// ```
25///
26/// Custom encoder implementation:
27///
28/// ```
29/// use pct_str::{PctString, UriReserved};
30///
31/// struct CustomEncoder;
32///
33/// impl pct_str::Encoder for CustomEncoder {
34/// fn encode(&self, c: char) -> bool {
35/// UriReserved::Any.encode(c) || c.is_uppercase()
36/// }
37/// }
38///
39/// let pct_string = PctString::encode("Hello World!".chars(), CustomEncoder);
40/// println!("{}", pct_string.as_str()); // => %48ello %57orld%21
41/// ```
42pub trait Encoder {
43 /// Decide if the given character must be encoded.
44 ///
45 /// Note that the character `%` is always encoded even if this method returns `false` on it.
46 fn encode(&self, c: char) -> bool;
47}
48
49impl<F: Fn(char) -> bool> Encoder for F {
50 fn encode(&self, c: char) -> bool {
51 self(c)
52 }
53}