Skip to main content

encode/
encode.rs

1extern crate pct_str;
2
3use pct_str::{PctString, UriReserved};
4
5struct CustomEncoder;
6
7impl pct_str::Encoder for CustomEncoder {
8	fn encode(&self, c: char) -> bool {
9		UriReserved::Any.encode(c) || c.is_uppercase()
10	}
11}
12
13fn main() {
14	// You can encode any string into a percent-encoded string
15	// using the [`PctString::encode`] function.
16	// It takes a `char` iterator and a [`Encoder`] instance deciding which
17	// characters to encode.
18	let pct_string = PctString::encode("Hello World!".chars(), UriReserved::Any);
19	// [`URIReserved`] is a predefined encoder for URI-reserved characters.
20	assert_eq!(pct_string.as_str(), "Hello World%21");
21
22	// You can create your own encoder by implementing the [`Encoder`] trait.
23	let pct_string = PctString::encode("Hello World!".chars(), CustomEncoder);
24	println!("{}", pct_string.as_str());
25	assert_eq!(pct_string.as_str(), "%48ello %57orld%21");
26
27	// You can also use any function implementing `Fn(char) -> bool`.
28	let pct_string = PctString::encode("Hello World!".chars(), char::is_uppercase);
29	assert_eq!(pct_string.as_str(), "%48ello %57orld!");
30}