1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/*
 * Copyright (c) 2023 Erik Nordstrøm <erik@nordstroem.no>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

use super::WordlistSubset;

/// Base 256 decoder using EFF Short Wordlist 2.0
#[derive(Clone, Debug)]
pub struct EffDecode<I: Iterator> {
    iter: I,
    candidate_wl_subsets_remaining: Vec<WordlistSubset<'static>>,
    prev_match_len: usize,
    curr_match_len: usize,
}

impl<I> Iterator for EffDecode<I>
where
    I: Iterator<Item = Result<char, std::io::Error>>,
{
    type Item = Result<u8, std::io::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        for word_byte in self.iter.by_ref() {
            // We immediately return the error if one is encountered.
            let Ok(word_char) = word_byte else { return Some(Err(word_byte.unwrap_err())) };

            let word_chars: Vec<_> = word_char.to_lowercase().collect();

            // We skip space, newline and carriage return characters
            if word_chars == [' '] || word_chars == ['\n'] || word_chars == ['\r'] {
                continue;
            }

            self.curr_match_len += word_chars.len();
            //dbg!(self.curr_match_len);
            //dbg!(&self.candidate_wl_subsets_remaining);

            // Remove subsets that are too short from the current set of possible matches.
            let first_subset_remaining = self
                .candidate_wl_subsets_remaining
                .partition_point(|wl| wl.word_len < self.curr_match_len);
            self.candidate_wl_subsets_remaining =
                self.candidate_wl_subsets_remaining[first_subset_remaining..].to_owned();

            for subset in self.candidate_wl_subsets_remaining.iter_mut() {
                // Find first word in subset that matches so far (alternate implementation)
                for (i, word_char) in word_chars.iter().enumerate() {
                    let subset_words_idx_low = subset.words.partition_point(|entry| {
                        entry.word.chars().nth(self.prev_match_len + i).unwrap() < *word_char
                    });
                    //dbg!(subset.words);
                    subset.words = &subset.words[subset_words_idx_low..];
                    //dbg!(subset.words);
                }

                /*
                // Find first word in subset that matches so far (original implementation)
                let mut subset_words_idx_low = 0;
                for entry in subset.words {
                    let word_remainder_to_match = &entry.word[self.prev_match_len..];
                    if word_remainder_to_match.starts_with(&*word_chars) {
                        //dbg!(entry.word, &word_chars, word_remainder_to_match);
                        break;
                    }
                    subset_words_idx_low += 1;
                }
                //dbg!(subset.words);
                subset.words = &subset.words[subset_words_idx_low..];
                //dbg!(subset.words);
                 */

                // Find last word in subset that matches so far
                let subset_words_idx_high = subset.words.partition_point(|entry| {
                    let word_remainder_to_match = &entry.word[self.prev_match_len..];
                    word_remainder_to_match.starts_with(&*word_chars)
                });
                //dbg!(subset.words);
                subset.words = &subset.words[..subset_words_idx_high];
                //dbg!(subset.words);
            }

            // Remove empty subsets
            self.candidate_wl_subsets_remaining = self
                .candidate_wl_subsets_remaining
                .clone()
                .into_iter()
                .filter(|wl| !wl.words.is_empty())
                .collect();

            self.prev_match_len = self.curr_match_len;

            // No candidates remaining means input data was not valid
            if self.candidate_wl_subsets_remaining.is_empty() {
                return Some(Err(std::io::Error::from(std::io::ErrorKind::InvalidData)));
            }

            // Check for exact match
            if self.candidate_wl_subsets_remaining.len() == 1 {
                //dbg!(&self.candidate_wl_subsets_remaining);
                if self.candidate_wl_subsets_remaining[0].words.len() == 1
                    && self.curr_match_len == self.candidate_wl_subsets_remaining[0].word_len
                {
                    let ret_byte = self.candidate_wl_subsets_remaining[0].words[0].byte;

                    self.candidate_wl_subsets_remaining = super::WL_EFF_DECODE.to_vec();
                    self.prev_match_len = 0;
                    self.curr_match_len = 0;

                    return Some(Ok(ret_byte));
                }
            }
        }
        None
    }
}

impl<I: Iterator<Item = Result<char, E>>, E> crate::Decode<I, EffDecode<I>> for I {
    fn decode(self) -> EffDecode<I> {
        EffDecode {
            iter: self,
            candidate_wl_subsets_remaining: super::WL_EFF_DECODE.to_vec(),
            prev_match_len: 0,
            curr_match_len: 0,
        }
    }
}

#[cfg(test)]
mod test_cases_decode {
    use super::super::Decode;
    use super::EffDecode;
    use std::fs::File;
    use std::io::{BufReader, Cursor};
    use std::path::Path;
    use test_case::test_case;
    use utf8_chars::BufReadCharsExt;

    #[test_case("acuteness acuteness acuteness "; "words spaced")]
    #[test_case("acute  ness a cute ness acuten   ess "; "words extra space")]
    #[test_case("acutenessacutenessacuteness"; "words mushed")]
    #[test_case("acuteness acuteness \nacuteness "; "words spaced wrapped")]
    #[test_case("acutenessacut\nenessacuteness"; "words mushed wrapped")]
    #[test_case("ACUTENESS ACUTENESS ACUTENESS "; "words spaced uppercase")]
    #[test_case("Acuteness ACUTEness acuteNESS "; "words spaced mixed-case")]
    fn test_positive_eff_decoder_0x05_0x05_0x05(words: &str) {
        let mut cursor = Cursor::new(words);
        let words_chars = cursor.chars().into_iter();
        let decoded_bytes = Decode::<_, EffDecode<_>>::decode(words_chars)
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert_eq!(decoded_bytes, &[0x05u8; 3]);
    }

    #[test_case("id_ed25519.txt")]
    #[test_case("id_ed25519-fold_w_78.txt")]
    #[test_case("id_ed25519-fold_w_78_s.txt")]
    #[test_case("id_ed25519-fold_w_78_s-trimmed.txt")]
    fn test_positive_eff_decoder_sample_data_file_id_ed25519<P: AsRef<Path>>(fpath_encoded: P) {
        let fpath_original_id_ed25519 = "sample_data/original/id_ed25519";
        let expected_bytes = std::fs::read(fpath_original_id_ed25519).unwrap();

        let fpath_encoded = Path::new("sample_data/encoded/eff").join(fpath_encoded);
        let mut input_encoded = BufReader::new(File::open(fpath_encoded).unwrap());

        let decoded_bytes = Decode::<_, EffDecode<_>>::decode(input_encoded.chars())
            .collect::<Result<Vec<_>, _>>()
            .unwrap();

        assert_eq!(decoded_bytes, expected_bytes);
    }

    #[test_case("id_ed25519-fold_w_78_s.txt")]
    #[test_case("id_ed25519-fold_w_78_s-trimmed.txt")]
    fn test_negative_eff_decoder_sample_data_file_id_ed25519<P: AsRef<Path>>(fpath_encoded: P) {
        let fpath_encoded = Path::new("sample_data/encoded_corrupted/eff").join(fpath_encoded);
        let mut input_encoded = BufReader::new(File::open(fpath_encoded).unwrap());

        let decoded_bytes =
            Decode::<_, EffDecode<_>>::decode(input_encoded.chars()).collect::<Result<Vec<_>, _>>();

        assert_eq!(
            decoded_bytes.unwrap_err().kind(),
            std::io::ErrorKind::InvalidData
        );
    }
}