将 ISO-8859-1 / Latin-1 转换为字符串 (UTF-8) 有哪些选项?

What are the options to convert ISO-8859-1 / Latin-1 to a String (UTF-8)?

我扫描了 Rust 文档以寻找在字符编码之间进行转换的某种方法,但没有找到任何东西。我错过了什么吗?

Rust 语言及其标准库是否(直接或间接)支持它,甚至计划在不久的将来支持它?

作为答案之一,有一个简单的解决方案,因为 u8 可以转换为 (Unicode) chars。 Unicode 是 ISO-8859-1 代码点的超集,这是一个 1:1 映射,它编码为 UTF-8 中的多个字节,UTF-8 是 Rust 中 Strings 的内部编码。

fn main() {
    println!("{}", 196u8 as char);
    println!("{}", (196u8 as char) as u8);
    println!("{}", 'Ä' as u8);
    println!("{:?}", 'Ä'.to_string().as_bytes());
    println!("{:?}", "Ä".as_bytes());
    println!("{}",'Ä' == 196u8 as char);
}

给出:

Ä
196
196
[195, 132]
[195, 132]
true

我什至没有考虑过工作!

标准库没有任何 API 来处理编码。编码,如日期和时间,很难正确处理并且需要大量工作,因此它们不存在于 std.

目前处理编码的 crate 是 rust-encoding。你几乎肯定会在那里找到你需要的一切。

Rust 中的字符串是 unicode (UTF-8),unicode 代码点是 iso-8859-1 字符的超集。这种特定的转换实际上是微不足道的。

fn latin1_to_string(s: &[u8]) -> String {
    s.iter().map(|&c| c as char).collect()
}

我们将每个字节解释为一个 unicode 代码点,然后从这些代码点构建一个字符串。