Skip to main content

rsfn_file/encode/
utf16be.rs

1use crate::encode::Encode;
2
3/// Dados em UTF-16BE.
4#[derive(Debug)]
5pub struct Utf16be {}
6
7impl Utf16be {
8    /// Inicia não codificador de dados.
9    pub fn new() -> Self {
10        Self {}
11    }
12}
13
14impl Default for Utf16be {
15    fn default() -> Self {
16        Self::new()
17    }
18}
19
20impl Encode for Utf16be {
21    fn encode(&self, data: &[u8]) -> Result<Vec<u8>, String> {
22        let text = String::from_utf8(data.into())
23            .map_err(|error| format!("Falha ao ler dados como UTF-8: {error}"))?;
24        Ok(text.encode_utf16().flat_map(u16::to_be_bytes).collect())
25    }
26
27    fn decode(&self, data: &[u8]) -> Result<Vec<u8>, String> {
28        let data: Vec<_> = data
29            .chunks_exact(2)
30            .map(|bytes| {
31                u16::from_be_bytes(
32                    bytes
33                        .try_into()
34                        .expect("Tamanho de dados inválido para UTF-16BE"),
35                )
36            })
37            .collect();
38        let text = String::from_utf16(&data)
39            .map_err(|error| format!("Falha ao ler dados como UTF-16BE: {error}"))?;
40        Ok(text.bytes().collect())
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use rand::RngExt;
47
48    use super::*;
49
50    #[test]
51    fn compress_and_decompress() {
52        let mut rng = rand::rng();
53        let data: Vec<char> = (0..256).map(|_| rng.random()).collect();
54        let data = String::from_iter(data);
55        let data = data.as_bytes();
56
57        let sut = Utf16be::default();
58        let compressed = sut.encode(data).unwrap();
59
60        assert_ne!(compressed, data);
61
62        let decompressed = sut.decode(&compressed).unwrap();
63
64        assert_eq!(decompressed, data);
65    }
66}