base256/encode/
eff.rs

1/*
2 * Copyright (c) 2018, 2023 Erik Nordstrøm <erik@nordstroem.no>
3 *
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17/// Base 256 encoder using EFF Short Wordlist 2.0
18#[derive(Clone, Debug)]
19pub struct EffEncode<I: Iterator> {
20    iter: I,
21}
22
23impl<I, E> Iterator for EffEncode<I>
24where
25    I: Iterator<Item = Result<u8, E>>,
26{
27    type Item = Result<&'static str, E>;
28
29    fn next(&mut self) -> Option<Self::Item> {
30        match self.iter.next()? {
31            Ok(byte) => Some(Ok(crate::WL_EFF_ENCODE[byte as usize])),
32            Err(e) => Some(Err(e)),
33        }
34    }
35}
36
37impl<I: Iterator<Item = Result<u8, E>>, E> crate::Encode<I, EffEncode<I>> for I {
38    fn encode(self) -> EffEncode<I> {
39        EffEncode { iter: self }
40    }
41}
42
43#[cfg(test)]
44mod test_cases_encode {
45    use super::super::Encode;
46    use super::EffEncode;
47    use std::io::{Cursor, Read};
48    use test_case::test_case;
49
50    #[test_case(&[0x05u8; 3], &["acuteness"; 3] ; "data 0x05 0x05 0x05")]
51    fn test_positive_eff_encoder(bytes: &[u8], expected_words: &[&str]) {
52        let bytes = Cursor::new(bytes).bytes().into_iter();
53        let encoded_words = Encode::<_, EffEncode<_>>::encode(bytes)
54            .collect::<Result<Vec<_>, _>>()
55            .unwrap();
56        assert_eq!(encoded_words, expected_words);
57    }
58}