字符集

URL 编码字符串

url-badge cat-encoding-badge

编码一个输入字符串,编码方式为URL 编码,可通过使用来自url箱子的utf8_percent_encode函数完成。然后再使用percent_decode函数。

extern crate url;

use url::percent_encoding::{utf8_percent_encode, percent_decode, DEFAULT_ENCODE_SET};
use std::str::Utf8Error;

fn main() -> Result<(), Utf8Error> {
    let input = "confident, productive systems programming";

    let iter = utf8_percent_encode(input, DEFAULT_ENCODE_SET);
    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切片的迭代器,这能收集(collect)成一个String

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

url-badge cat-encoding-badge

将字符串,编码为application/x-www-form-urlencoded语法,通过form_urlencoded::byte_serialize,然后用form_urlencoded::parse完成。 两个函数都返回迭代器,这些迭代器能收集成一个String

extern crate url;
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箱子提供一个HEXUPPER::encode方法,它会获取一个&[u8],并返回一个String,其中包含数据的十六进制表示形式。

类似地,一个HEXUPPER::decode提供的方法,也获取一个&[u8],并如果输入数据解码成功的话,就返回一个Vec<u8>

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

extern crate data_encoding;

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

将字节切片编码为base64字符串,通过encode完成,还能用decode解码。

# #[macro_use]
# extern crate error_chain;
extern crate base64;

use std::str;
use base64::{encode, decode};
#
# error_chain! {
#     foreign_links {
#         Base64(base64::DecodeError);
#         Utf8Error(str::Utf8Error);
#     }
# }

fn run() -> 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(())
}
#
# quick_main!(run);