Skip to main content

encode_checked

Function encode_checked 

Source
pub fn encode_checked(text: &str) -> (Cow<'_, [u8]>, bool)
Expand description

Encodes text with the configured encoding, reporting whether anything was lost on the way.

Encoding is not always possible: Windows-1252 has no Cyrillic, Windows-1251 has no ç, and no 8-bit code page has an emoji. encoding_rs substitutes what it cannot represent — a ?, or an HTML numeric reference — and says nothing, so a player named Ковальски becomes ????? on a Western server with the plugin none the wiser.

The returned flag is that warning. Pair it with unmappable_chars when it is true to say in the log which characters were lost.

set_default_encoding(WINDOWS_1252);
let (bytes, lost) = encode_checked("cafe");
assert!(!lost);
assert_eq!(bytes.as_ref(), b"cafe");

let (_, lost) = encode_checked("Привет");
assert!(lost, "Cyrillic does not fit in Windows-1252");