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
use std::convert::TryInto;
use std::iter::{ExactSizeIterator, IntoIterator, Iterator};
use std::str;

use thin_vec::ThinVec;

/// Store any string efficiently in an immutable way.
///
/// Can store at most `u32::MAX` strings and only provides
/// `StringsNoIndexIter` and does not provide arbitary indexing.
#[derive(Debug, Default, Eq, PartialEq, Clone, Hash)]
pub struct StringsNoIndex {
    strs: ThinVec<u8>,
}

impl StringsNoIndex {
    pub fn new() -> Self {
        Self::default()
    }

    /// * `len` - number of strings
    ///
    /// NOTE that this function does nothing and is defined just to be compatible
    /// with `Strings`.
    pub fn with_capacity(_len: u32) -> Self {
        Self::new()
    }

    fn set_len(&mut self, new_len: u32) {
        self.strs[..4].copy_from_slice(&new_len.to_ne_bytes());
    }

    pub fn len(&self) -> u32 {
        if self.is_empty() {
            0
        } else {
            u32::from_ne_bytes(self.strs[..4].try_into().unwrap())
        }
    }

    pub fn is_empty(&self) -> bool {
        self.strs.is_empty()
    }

    /// * `s` - must not contain null byte.
    pub fn push(&mut self, s: &str) {
        if self.is_empty() {
            let len: u32 = 1;
            self.strs.extend_from_slice(&len.to_ne_bytes());
        } else {
            let len = self.len();

            if len == u32::MAX {
                panic!(
                    "StringsNoIndex cannot contain more than u32::MAX {} elements",
                    u32::MAX
                );
            }

            self.set_len(len + 1);
        }

        self.strs
            .extend(s.as_bytes().iter().copied().filter(|byte| *byte != b'\0'));
        self.strs.push(0);
    }

    /// Accumulate length of all strings.
    #[inline(always)]
    pub fn strs_len(&self) -> usize {
        self.strs.len()
    }

    #[inline(always)]
    pub fn reserve_strs(&mut self, cnt: usize) {
        self.strs.reserve(cnt);
    }

    pub fn shrink_to_fit(&mut self) {
        self.strs.shrink_to_fit();
    }

    #[inline(always)]
    pub fn iter(&self) -> StringsNoIndexIter<'_> {
        let slice = if self.is_empty() {
            &[]
        } else {
            &self.strs[4..]
        };
        StringsNoIndexIter::new(slice, self.len())
    }
}
impl<'a> IntoIterator for &'a StringsNoIndex {
    type Item = &'a str;
    type IntoIter = StringsNoIndexIter<'a>;

    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[derive(Clone, Debug)]
pub struct StringsNoIndexIter<'a>(&'a [u8], u32);

impl<'a> StringsNoIndexIter<'a> {
    fn new(strs: &'a [u8], len: u32) -> Self {
        Self(strs, len)
    }
}

impl<'a> Iterator for StringsNoIndexIter<'a> {
    type Item = &'a str;

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

        self.1 -= 1;

        let pos = self.0.iter().position(|byte| *byte == 0).unwrap();
        let slice = &self.0[..pos];
        self.0 = &self.0[(pos + 1)..];
        Some(unsafe { str::from_utf8_unchecked(slice) })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.1 as usize;
        (len, Some(len))
    }
}

impl ExactSizeIterator for StringsNoIndexIter<'_> {}

#[cfg(test)]
mod tests {
    use super::StringsNoIndex;

    fn assert_strs_in(strs: &StringsNoIndex, input_strs: &Vec<String>) {
        for (string, input_str) in strs.iter().zip(input_strs) {
            assert_eq!(string, input_str);
        }
    }

    #[test]
    fn test() {
        let mut strs = StringsNoIndex::new();
        let input_strs: Vec<String> = (0..256).map(|n| n.to_string()).collect();

        assert!(strs.is_empty());

        for (i, input_str) in input_strs.iter().enumerate() {
            strs.push(input_str);
            assert_eq!(strs.len() as usize, i + 1);

            assert_strs_in(&strs, &input_strs);
        }

        assert!(!strs.is_empty());

        assert!(input_strs.iter().eq(strs.iter()));
    }

    #[test]
    fn test_adding_empty_strs() {
        let mut strs = StringsNoIndex::new();

        assert!(strs.is_empty());

        for i in 0..10 {
            strs.push("");
            assert_eq!(strs.len() as usize, i + 1);
        }

        assert!(!strs.is_empty());

        strs.push("12345");

        for (i, string) in strs.iter().enumerate() {
            if i < 10 {
                assert_eq!(string, "");
            } else {
                assert_eq!(string, "12345");
            }
        }
    }
}