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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use std::collections::HashMap;
use crate::parse_subsequence;


#[derive(Debug)]
struct KeyValueIterator<'da, 'db> {
    input: &'da [u8],
    linend: Option<&'db Vec<Vec<u8>>>,
    split_str: Option<&'db Vec<Vec<u8>>>,
    count: usize,
    curruent_count: usize,
}


impl<'da, 'db> KeyValueIterator<'da, 'db> {
    pub fn new(input: &'da [u8], _cattr: Option<&'db crate::ContainerAttrModifiers>, fattr: Option<&'db crate::FieldAttrModifiers>) -> Self {
        let mut count = 50;
        let mut linend = None;
        // let mut split_str = vec![b": ".to_vec()];
        let mut split_str = None;
    
        if let Some(fattr) = fattr {
            linend = fattr.linend_value.as_ref();
            split_str = fattr.split.as_ref();
            count = fattr.count.unwrap_or(50);
        }

        Self {
            input,
            linend,
            split_str,
            count,
            curruent_count: 0,
        }    
    }
}


impl<'da, 'db> KeyValueIterator<'da, 'db> {
    #[inline]
    pub fn parse_subsequence(&mut self, linend: &'db [u8]) -> Option<(&'da [u8], &'da [u8], &'da [u8])> {
        match parse_subsequence(self.input, linend, false) {
            Ok((input_tmp, value)) => {
                let split_default = &vec![b": ".to_vec()];
                let split_str = self.split_str.unwrap_or(split_default);
                for split in split_str {
                    if let Ok((value, key)) = parse_subsequence(value, split, false) {
                        self.input = input_tmp;
                        self.curruent_count += 1;

                        return Some((input_tmp, key, value));
                    }
                    // if let Some(index) = value.find_substring(&split[..]) {
                    //     let key = &value[..index];
                    //     let value = &value[split.len() + index..value.len() - linend.len()];
                    //     self.input = input_tmp;
                    //     self.curruent_count += 1;

                    //     return Some((input_tmp, key, value));
                    // }    
                }
            },
            Err(_e) => {
                // return None;
            },
        }

        None
    }
}


impl<'da, 'db> Iterator for KeyValueIterator<'da, 'db> {
    // (input, key, value)
    type Item = (&'da [u8], &'da [u8], &'da [u8]);

    fn next(&mut self) -> Option<Self::Item> {
        if self.input.is_empty() {
            return None;
        }

        if self.curruent_count < self.count {
            if let Some(linend) = self.linend {
                for linend in linend {
                    if let Some(value) = self.parse_subsequence(linend) {
                        return Some(value);
                    }
                }    
            }
            else if let Some(value) = self.parse_subsequence("\r\n".as_bytes()) {
                return Some(value);
            }
            else {
                return self.parse_subsequence("\r\n".as_bytes());
            }
        }

        None
    }
}


impl<'de> crate::BorrowByteDecode<'de> for HashMap<&'de [u8], &'de [u8]> {
    fn decode<'da: 'de, 'db>(input: &'da [u8], cattr: Option<&'db crate::ContainerAttrModifiers>, fattr: Option<&'db crate::FieldAttrModifiers>) -> crate::JResult<&'da [u8], Self>
    where 
        Self: Sized
    {
        let mut input = input;
        let mut hashmap = HashMap::new();
        let keyvalue_iter = KeyValueIterator::new(input, cattr, fattr);

        for (remain, key, value) in keyvalue_iter {
            hashmap.insert(key, value);
            input = remain;
        }

        Ok((input, hashmap))        
    }
}


impl<'de> crate::BorrowByteDecode<'de> for HashMap<&'de str, &'de str> {
    fn decode<'da: 'de, 'db>(input: &'da [u8], cattr: Option<&'db crate::ContainerAttrModifiers>, fattr: Option<&'db crate::FieldAttrModifiers>) -> crate::JResult<&'da [u8], Self>
    where 
        Self: Sized
    {
        let mut input = input;
        let mut hashmap = HashMap::new();
        let keyvalue_iter = KeyValueIterator::new(input, cattr, fattr);

        for (remain, key, value) in keyvalue_iter {
            let key = std::str::from_utf8(key).unwrap_or_default();
            let value = std::str::from_utf8(value).unwrap_or_default();

            hashmap.insert(key, value);
            input = remain;
        }

        Ok((input, hashmap))        
    }
}


impl<'de> crate::BorrowByteDecode<'de> for HashMap<String, String> {
    fn decode<'da: 'de, 'db>(input: &'da [u8], cattr: Option<&'db crate::ContainerAttrModifiers>, fattr: Option<&'db crate::FieldAttrModifiers>) -> crate::JResult<&'da [u8], Self>
    where 
        Self: Sized
    {
        let mut input = input;
        let mut hashmap = HashMap::new();
        let keyvalue_iter = KeyValueIterator::new(input, cattr, fattr);

        for (remain, key, value) in keyvalue_iter {
            let key = String::from_utf8_lossy(key).to_string();
            let value = String::from_utf8_lossy(value).to_string();

            hashmap.insert(key, value);
            input = remain;
        }

        Ok((input, hashmap))        
    }
}


impl crate::ByteDecode for HashMap<String, String> {
    fn decode<'da, 'db>(input: &'da [u8], cattr: Option<&'db crate::ContainerAttrModifiers>, fattr: Option<&'db crate::FieldAttrModifiers>) -> crate::JResult<&'da [u8], Self>
    where 
        Self: Sized
    {
        let mut input = input;
        let mut hashmap = HashMap::new();
        let keyvalue_iter = KeyValueIterator::new(input, cattr, fattr);

        for (remain, key, value) in keyvalue_iter {
            let key = String::from_utf8_lossy(key).to_string();
            let value = String::from_utf8_lossy(value).to_string();

            hashmap.insert(key, value);
            input = remain;
        }

        Ok((input, hashmap))        
    }
}


#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use crate::{ByteDecode, FieldAttrModifiers};

    #[test]
    fn test_impls_hashmap_decode() {
        let input = b"A1: jkc1\r\nA2: jkc2\r\nA3: \r\nabc\r\n";

        let (input, value): (&[u8], HashMap<String, String>) = ByteDecode::decode(input, None, None).unwrap();

        println!("{:?} {:?}", input, value);
        assert_eq!(input, b"abc\r\n");

        let mut hashmap_value = HashMap::new();
        hashmap_value.insert("A1".to_string(), "jkc1".to_string());
        hashmap_value.insert("A2".to_string(), "jkc2".to_string());
        hashmap_value.insert("A3".to_string(), "".to_string());

        assert_eq!(value, hashmap_value);

        let input = b"A1: jkc1\r\nA2: jkc2\r\nA3: \r\nabc\r\n";
        let fattr = FieldAttrModifiers { count: Some(2), ..Default::default() };
        let (input, value): (&[u8], HashMap<String, String>) = ByteDecode::decode(input, None, Some(&fattr)).unwrap();

        println!("{:?} {:?}", input, value);
        assert_eq!(input, b"A3: \r\nabc\r\n");

        let mut hashmap_value = HashMap::new();
        hashmap_value.insert("A1".to_string(), "jkc1".to_string());
        hashmap_value.insert("A2".to_string(), "jkc2".to_string());
        assert_eq!(value, hashmap_value);
    }
}