字符集

百分比编码(URL 编码)字符串

percent-encoding-badge cat-encoding-badge

使用 percent-encoding crate 中的 utf8_percent_encode 函数对输入字符串进行百分比编码(URL 编码)。解码使用 percent_decode 函数。

use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS};
use std::str::Utf8Error;

/// https://url.spec.whatwg.org/#fragment-percent-encode-set
const 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(())
}

编码集定义哪些字节(除了非 ASCII 字节和控制键之外)需要进行百分比编码(URL 编码),这个集合的选择取决于上下文。例如,url 对 URL 路径中的 ? 编码,而不对查询字符串中的 ? 编码。

编码的返回值是 &str 切片的迭代器,然后聚集为一个字符串 String

将字符串编码为 application/x-www-form-urlencoded

url-badge cat-encoding-badge

如下实例使用 form_urlencoded::byte_serialize 将字符串编码为 application/x-www-form-urlencoded 表单语法,随后使用 form_urlencoded::parse 对其进行解码。这两个函数都返回迭代器,然后这些迭代器聚集为 String

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);
}

编码和解码十六进制

data-encoding-badge cat-encoding-badge

data_encoding crate 提供了 HEXUPPER::encode 方法,该方法接受 &[u8] 参数并返回十六进制数据的字符串 String

类似地,data_encoding crate 提供了 HEXUPPER::decode 方法,该方法接受 &[u8] 参数。如果输入数据被成功解码,则返回 Vec<u8>

下面的实例将 &[u8] 数据转换为等效的十六进制数据,然后将此值与预期值进行比较。

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(())
}

编码和解码 base64

base64-badge cat-encoding-badge

使用 encode 将字节切片编码为 base64 字符串,对 base64 字符串解码使用 decode

use error_chain::error_chain;

use std::str;
use base64::{encode, decode};

error_chain! {
    foreign_links {
        Base64(base64::DecodeError);
        Utf8Error(str::Utf8Error);
    }
}

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(())
}