Character Sets
Percent-encode a string
Encode an input string withpercent-encoding using theutf8_percent_encode
function from thepercent-encoding
crate. Then decodeusing thepercent_decode
function.
use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS};use std::str::Utf8Error;/// https://url.spec.whatwg.org/#fragment-percent-encode-setconst FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');fn main() -> Result<(), Utf8Error> { let input = "confident, productive systems programming"; let iter = utf8_percent_encode(input, FRAGMENT); let encoded: String = iter.collect(); assert_eq!(encoded, "confident,%20productive%20systems%20programming"); let iter = percent_decode(encoded.as_bytes()); let decoded = iter.decode_utf8()?; assert_eq!(decoded, "confident, productive systems programming"); Ok(())}
The encode set defines which bytes (in addition to non-ASCII and controls) needto be percent-encoded. The choice of this set depends on context. For example,url
encodes?
in a URL path but not in a query string.
The return value of encoding is an iterator of&str
slices which collect intoaString
.
Encode a string as application/x-www-form-urlencoded
Encodes a string intoapplication/x-www-form-urlencoded syntaxusing theform_urlencoded::byte_serialize
and subsequentlydecodes it withform_urlencoded::parse
. Both functions return iteratorsthat collect into aString
.
use url::form_urlencoded::{byte_serialize, parse};fn main() { let urlencoded: String = byte_serialize("What is ❤?".as_bytes()).collect(); assert_eq!(urlencoded, "What+is+%E2%9D%A4%3F"); println!("urlencoded:'{}'", urlencoded); let decoded: String = parse(urlencoded.as_bytes()) .map(|(key, val)| [key, val].concat()) .collect(); assert_eq!(decoded, "What is ❤?"); println!("decoded:'{}'", decoded);}
Encode and decode hex
Thedata_encoding
crate provides aHEXUPPER::encode
method whichtakes a&[u8]
and returns aString
containing the hexadecimalrepresentation of the data.
Similarly, aHEXUPPER::decode
method is provided which takes a&[u8]
andreturns aVec<u8>
if the input data is successfully decoded.
The example below converts&[u8]
data to hexadecimal equivalent. Compares thisvalue to the expected value.
use data_encoding::{HEXUPPER, DecodeError};fn main() -> Result<(), DecodeError> { let original = b"The quick brown fox jumps over the lazy dog."; let expected = "54686520717569636B2062726F776E20666F78206A756D7073206F76\ 657220746865206C617A7920646F672E"; let encoded = HEXUPPER.encode(original); assert_eq!(encoded, expected); let decoded = HEXUPPER.decode(&encoded.into_bytes())?; assert_eq!(&decoded[..], &original[..]); Ok(())}
Encode and decode base64
Encodes byte slice intobase64
String usingencode
and decodes it withdecode
.
use anyhow::Result;use std::str;use base64::{encode, decode};fn main() -> Result<()> { let hello = b"hello rustaceans"; let encoded = encode(hello); let decoded = decode(&encoded)?; println!("origin: {}", str::from_utf8(hello)?); println!("base64 encoded: {}", encoded); println!("back to origin: {}", str::from_utf8(&decoded)?); Ok(())}