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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//! Wrapping is compacted into a u32 to be Copy. It's copied at various places to keep track of
//! current wrapping. It's functionally equivalent to:
//!
//! ```ignore
//! struct Wrapping {
//!   inner_is_required: bool,
//!   /// Innermost to outermost.
//!   list_wrappings: VecDeque<ListWrapping>
//! }
//! ```
//!
//! Since ListWrapping has only two cases and we won't encounter absurd levels of wrapping, we
//! can bitpack it. The current structure supports up to 21 list_wrappings.
//!
//! It's structured as follows:
//!
//!```text
//!       start (5 bits)
//!       ↓               ↓ list_wrapping (1 == Required / 0 == Nullable)
//!   ┌────┐      ┌────────────────────────┐
//!  0000_0000_0000_0000_0000_0000_0000_0000
//!         └────┘
//!            ↑ end (5 bits)
//!  ↑
//!  inner_is_required flag (1 == required)
//!```
//!
//! The list_wrapping is stored from innermost to outermost and use the start and end
//! as the positions within the list_wrapping bits. Acting like a simplified fixed capacity VecDeque.
//! For simplicity of bit shifts the list wrapping is stored from right to left.
const START_MASK: u32 = 0b0111_1100_0000_0000_0000_0000_0000_0000;
const START_SHIFT: u32 = START_MASK.trailing_zeros();
const END_MASK: u32 = 0b0000_0011_1110_0000_0000_0000_0000_0000;
const END_SHIFT: u32 = END_MASK.trailing_zeros();
const LIST_WRAPPINGS_MASK: u32 = 0b0000_0000_0001_1111_1111_1111_1111_1111;
const MAX_LIST_WRAPINGS: u32 = LIST_WRAPPINGS_MASK.trailing_ones();
const INNER_IS_REQUIRED_FLAG: u32 = 0b1000_0000_0000_0000_0000_0000_0000_0000;

#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Wrapping(u32);

impl Default for Wrapping {
    fn default() -> Self {
        Self::nullable()
    }
}

impl From<Wrapping> for u32 {
    fn from(value: Wrapping) -> Self {
        value.0
    }
}

impl From<u32> for Wrapping {
    fn from(value: u32) -> Self {
        Wrapping(value)
    }
}

impl std::fmt::Debug for Wrapping {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Wrapping")
            .field("inner_is_required", &self.inner_is_required())
            .field("list_wrappings", &self.list_wrappings().collect::<Vec<_>>())
            .finish()
    }
}

impl Wrapping {
    /// Is the innermost type required?
    ///
    /// Examples:
    ///
    /// - `String` => false
    /// - `String!` => true
    /// - `[String!]` => true
    /// - `[String]!` => false
    pub fn inner_is_required(self) -> bool {
        self.0 & INNER_IS_REQUIRED_FLAG != 0
    }

    /// Innermost to outermost.
    pub fn list_wrappings(
        self,
    ) -> impl DoubleEndedIterator<Item = ListWrapping> + Copy + ExactSizeIterator<Item = ListWrapping> {
        self
    }

    pub fn is_nullable(self) -> bool {
        !self.is_required()
    }

    pub fn is_required(self) -> bool {
        self.list_wrappings()
            .next_back()
            .map(|lw| matches!(lw, ListWrapping::RequiredList))
            .unwrap_or(self.inner_is_required())
    }

    pub fn is_list(self) -> bool {
        self.list_wrappings().next().is_some()
    }

    fn start(self) -> u32 {
        (self.0 & START_MASK) >> START_SHIFT
    }

    fn inc_start(&mut self) {
        let start = self.start() + 1;
        self.0 = (self.0 & !START_MASK) | (start << START_SHIFT);
    }

    fn end(self) -> u32 {
        (self.0 & END_MASK) >> END_SHIFT
    }
    fn inc_end(&mut self) {
        let end = self.end() + 1;
        assert!(end < MAX_LIST_WRAPINGS + 1, "Too many list wrappings");
        self.0 = (self.0 & !END_MASK) | (end << END_SHIFT);
    }

    fn dec_end(&mut self) {
        let end = self.end() - 1;
        self.0 = (self.0 & !END_MASK) | (end << END_SHIFT);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ListWrapping {
    RequiredList,
    NullableList,
}

impl Iterator for Wrapping {
    type Item = ListWrapping;

    fn next(&mut self) -> Option<Self::Item> {
        let start = self.start();
        if start == self.end() {
            return None;
        }
        self.inc_start();
        let bit_mask = 1 << start;
        if self.0 & bit_mask != 0 {
            Some(ListWrapping::RequiredList)
        } else {
            Some(ListWrapping::NullableList)
        }
    }
}

impl ExactSizeIterator for Wrapping {
    fn len(&self) -> usize {
        (self.end() - self.start()) as usize
    }
}

impl DoubleEndedIterator for Wrapping {
    fn next_back(&mut self) -> Option<Self::Item> {
        let end = self.end();
        if end == self.start() {
            return None;
        }
        self.dec_end();
        // end is exclusive
        let bit_mask = 1 << (end - 1);
        if self.0 & bit_mask != 0 {
            Some(ListWrapping::RequiredList)
        } else {
            Some(ListWrapping::NullableList)
        }
    }
}

impl Wrapping {
    pub fn new(required: bool) -> Self {
        if required {
            Self::required()
        } else {
            Self::nullable()
        }
    }

    pub fn nullable() -> Self {
        Wrapping(0)
    }

    pub fn required() -> Self {
        Wrapping(INNER_IS_REQUIRED_FLAG)
    }

    #[must_use]
    pub fn wrapped_by(self, list_wrapping: ListWrapping) -> Self {
        match list_wrapping {
            ListWrapping::RequiredList => self.wrapped_by_required_list(),
            ListWrapping::NullableList => self.wrapped_by_nullable_list(),
        }
    }

    #[must_use]
    pub fn wrapped_by_nullable_list(mut self) -> Self {
        let end = self.end();
        self.inc_end();
        let bit_mask = 1 << end;
        self.0 &= !bit_mask;
        self
    }

    #[must_use]
    pub fn wrapped_by_required_list(mut self) -> Self {
        let end = self.end();
        self.inc_end();
        let bit_mask = 1 << end;
        self.0 |= bit_mask;
        self
    }

    /// Outermost wrapping
    pub fn pop_list_wrapping(&mut self) -> Option<ListWrapping> {
        self.next_back()
    }

    pub fn write_type_string(self, name: &str, mut formatter: &mut dyn std::fmt::Write) -> Result<(), std::fmt::Error> {
        for _ in 0..self.len() {
            write!(formatter, "[")?;
        }

        write!(formatter, "{name}")?;

        if self.inner_is_required() {
            write!(formatter, "!")?;
        }

        for wrapping in self {
            match wrapping {
                ListWrapping::RequiredList => write!(&mut formatter, "]!")?,
                ListWrapping::NullableList => write!(&mut formatter, "]")?,
            };
        }

        Ok(())
    }
}

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

    #[test]
    fn test_wrapping() {
        let wrapping = Wrapping::required();
        assert!(wrapping.inner_is_required());
        assert!(wrapping.is_required());
        assert!(!wrapping.is_list());
        assert_eq!(wrapping.list_wrappings().collect::<Vec<_>>(), vec![]);

        let mut wrapping = Wrapping::nullable();
        assert!(!wrapping.inner_is_required());
        assert!(!wrapping.is_required());
        assert!(!wrapping.is_list());
        assert_eq!(wrapping.list_wrappings().collect::<Vec<_>>(), vec![]);

        wrapping = wrapping.wrapped_by_nullable_list();
        assert!(!wrapping.inner_is_required());
        assert!(!wrapping.is_required());
        assert!(wrapping.is_list());
        assert_eq!(
            wrapping.list_wrappings().collect::<Vec<_>>(),
            vec![ListWrapping::NullableList]
        );

        wrapping = wrapping.wrapped_by_required_list();
        assert!(!wrapping.inner_is_required());
        assert!(wrapping.is_required());
        assert!(wrapping.is_list());
        assert_eq!(
            wrapping.list_wrappings().collect::<Vec<_>>(),
            vec![ListWrapping::NullableList, ListWrapping::RequiredList]
        );

        wrapping = wrapping.wrapped_by_nullable_list();
        assert!(!wrapping.inner_is_required());
        assert!(!wrapping.is_required());
        assert!(wrapping.is_list());
        assert_eq!(
            wrapping.list_wrappings().collect::<Vec<_>>(),
            vec![
                ListWrapping::NullableList,
                ListWrapping::RequiredList,
                ListWrapping::NullableList
            ]
        );

        assert_eq!(wrapping.pop_list_wrapping(), Some(ListWrapping::NullableList));
        assert!(!wrapping.inner_is_required());
        assert!(wrapping.is_required());
        assert!(wrapping.is_list());
        assert_eq!(
            wrapping.list_wrappings().collect::<Vec<_>>(),
            vec![ListWrapping::NullableList, ListWrapping::RequiredList]
        );

        assert_eq!(wrapping.pop_list_wrapping(), Some(ListWrapping::RequiredList));
        assert!(!wrapping.inner_is_required());
        assert!(!wrapping.is_required());
        assert!(wrapping.is_list());
        assert_eq!(
            wrapping.list_wrappings().collect::<Vec<_>>(),
            vec![ListWrapping::NullableList]
        );

        assert_eq!(wrapping.pop_list_wrapping(), Some(ListWrapping::NullableList));
        assert!(!wrapping.inner_is_required());
        assert!(!wrapping.is_required());
        assert!(!wrapping.is_list());
        assert_eq!(wrapping.list_wrappings().collect::<Vec<_>>(), vec![]);

        assert_eq!(wrapping.pop_list_wrapping(), None);
    }
}