pub fn encode_from_utf8(
input: &str,
encoding: Encoding,
dst: &mut Vec<u8>,
) -> Result<(), EncodeError>Expand description
Encode input into encoding, appending the resulting bytes to dst.
Encoding::Utf8 and the two UTF-16 variants can represent every Rust char (i.e. every
Unicode scalar value) and therefore never fail. Encoding::Gb18030 is almost total in the
same sense — every scalar value except U+E5E5 has a representation (see the type’s own docs
for why that one code point is excluded) — but every other encoding, including
Encoding::Latin1, Encoding::Windows1252, Encoding::Ascii, and the remaining legacy
multi-byte encodings (Encoding::Gbk, Encoding::Big5, Encoding::EucKr, and the three
legacy Japanese ones), can only represent a subset of Unicode; the first character outside that
subset is reported as an EncodeError. Characters encoded before the failing one have
already been appended to dst, so partial output is available even after an error (useful
for producing a best-effort diagnostic, or for switching strategies — e.g. falling back to a
numeric character reference — and resuming from error.position).
§Errors
Returns EncodeError if input contains a character with no representation in encoding.
§Examples
use oxixml_encoding::{encode_from_utf8, Encoding};
let mut dst = Vec::new();
encode_from_utf8("café", Encoding::Latin1, &mut dst).expect("café is representable in Latin-1");
assert_eq!(dst, b"caf\xE9");
let mut dst = Vec::new();
let err = encode_from_utf8("日本語", Encoding::Ascii, &mut dst).unwrap_err();
assert_eq!(err.character, '日');
assert_eq!(err.position, 0);