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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

//! This module includes variable-length data types that are const-constructible for single
//! values and overflow to the heap.
//!
//! # Why?
//!
//! This module is far from the first stack-or-heap vector in the Rust ecosystem. It was created
//! with the following value proposition:
//!
//! 1. Enable safe const construction of stack collections.
//! 2. Avoid stack size penalties common with stack-or-heap collections.
//!
//! As of this writing, `heapless` and `tinyvec` don't support const construction except
//! for empty vectors, and `smallvec` supports it on unstable.
//!
//! Additionally, [`ShortBoxSlice`] has a smaller stack size than any of these:
//!
//! ```ignore
//! use core::mem::size_of;
//!
//! // NonZeroU64 has a niche that this module utilizes
//! use core::num::NonZeroU64;
//!
//! // ShortBoxSlice is the same size as `Box<[]>` for small or nichey values
//! assert_eq!(16, size_of::<shortvec::ShortBoxSlice::<NonZeroU64>>());
//!
//! // Note: SmallVec supports pushing and therefore has a capacity field
//! assert_eq!(24, size_of::<smallvec::SmallVec::<[NonZeroU64; 1]>>());
//!
//! // Note: heapless doesn't support spilling to the heap
//! assert_eq!(16, size_of::<heapless::Vec::<NonZeroU64, 1>>());
//!
//! // Note: TinyVec only supports types that implement `Default`
//! assert_eq!(24, size_of::<tinyvec::TinyVec::<[u64; 1]>>());
//! ```
//!
//! The module is `no_std` with `alloc`.

mod litemap;

use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use core::ops::Deref;
use core::ops::DerefMut;

/// A boxed slice that supports no-allocation, constant values if length 0 or 1.
/// Using ZeroOne(Option<T>) saves 8 bytes in ShortBoxSlice via niche optimization.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) enum ShortBoxSliceInner<T> {
    ZeroOne(Option<T>),
    Multi(Box<[T]>),
}

impl<T> Default for ShortBoxSliceInner<T> {
    fn default() -> Self {
        use ShortBoxSliceInner::*;
        ZeroOne(None)
    }
}

/// A boxed slice that supports no-allocation, constant values if length 0 or 1.
///
/// Supports mutation but always reallocs when mutated.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct ShortBoxSlice<T>(ShortBoxSliceInner<T>);

impl<T> Default for ShortBoxSlice<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<T> ShortBoxSlice<T> {
    /// Creates a new, empty [`ShortBoxSlice`].
    #[inline]
    pub const fn new() -> Self {
        use ShortBoxSliceInner::*;
        Self(ZeroOne(None))
    }

    /// Creates a new [`ShortBoxSlice`] containing a single element.
    #[inline]
    pub const fn new_single(item: T) -> Self {
        use ShortBoxSliceInner::*;
        Self(ZeroOne(Some(item)))
    }

    /// Pushes an element onto this [`ShortBoxSlice`].
    ///
    /// Reallocs if more than 1 item is already in the collection.
    pub fn push(&mut self, item: T) {
        use ShortBoxSliceInner::*;
        self.0 = match core::mem::replace(&mut self.0, ZeroOne(None)) {
            ZeroOne(None) => ZeroOne(Some(item)),
            ZeroOne(Some(prev_item)) => Multi(vec![prev_item, item].into_boxed_slice()),
            Multi(items) => {
                let mut items = items.into_vec();
                items.push(item);
                Multi(items.into_boxed_slice())
            }
        };
    }

    /// Gets a single element from the [`ShortBoxSlice`].
    ///
    /// Returns `None` if empty or more than one element.
    #[inline]
    pub const fn single(&self) -> Option<&T> {
        use ShortBoxSliceInner::*;
        match self.0 {
            ZeroOne(Some(ref v)) => Some(v),
            _ => None,
        }
    }

    /// Returns the number of elements in the collection.
    #[inline]
    pub fn len(&self) -> usize {
        use ShortBoxSliceInner::*;
        match self.0 {
            ZeroOne(None) => 0,
            ZeroOne(_) => 1,
            Multi(ref v) => v.len(),
        }
    }

    /// Returns whether the collection is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        use ShortBoxSliceInner::*;
        matches!(self.0, ZeroOne(None))
    }

    /// Inserts an element at the specified index into the collection.
    ///
    /// Reallocs if more than 1 item is already in the collection.
    pub fn insert(&mut self, index: usize, elt: T) {
        use ShortBoxSliceInner::*;
        assert!(
            index <= self.len(),
            "insertion index (is {}) should be <= len (is {})",
            index,
            self.len()
        );

        self.0 = match core::mem::replace(&mut self.0, ZeroOne(None)) {
            ZeroOne(None) => ZeroOne(Some(elt)),
            ZeroOne(Some(item)) => {
                let items = if index == 0 {
                    vec![elt, item].into_boxed_slice()
                } else {
                    vec![item, elt].into_boxed_slice()
                };
                Multi(items)
            }
            Multi(items) => {
                let mut items = items.into_vec();
                items.insert(index, elt);
                Multi(items.into_boxed_slice())
            }
        }
    }

    /// Removes the element at the specified index from the collection.
    ///
    /// Reallocs if more than 2 items are in the collection.
    pub fn remove(&mut self, index: usize) -> T {
        use ShortBoxSliceInner::*;
        assert!(
            index < self.len(),
            "removal index (is {}) should be < len (is {})",
            index,
            self.len()
        );

        let (replaced, removed_item) = match core::mem::replace(&mut self.0, ZeroOne(None)) {
            ZeroOne(None) => unreachable!(),
            ZeroOne(Some(v)) => (ZeroOne(None), v),
            Multi(v) => {
                let mut v = v.into_vec();
                let removed_item = v.remove(index);
                match v.len() {
                    #[allow(clippy::unwrap_used)]
                    // we know that the vec has exactly one element left
                    1 => (ZeroOne(Some(v.pop().unwrap())), removed_item),
                    // v has at least 2 elements, create a Multi variant
                    _ => (Multi(v.into_boxed_slice()), removed_item),
                }
            }
        };
        self.0 = replaced;
        removed_item
    }

    /// Removes all elements from the collection.
    #[inline]
    pub fn clear(&mut self) {
        use ShortBoxSliceInner::*;
        let _ = core::mem::replace(&mut self.0, ZeroOne(None));
    }

    /// Retains only the elements specified by the predicate.
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        use ShortBoxSliceInner::*;
        match core::mem::take(&mut self.0) {
            ZeroOne(Some(one)) if f(&one) => self.0 = ZeroOne(Some(one)),
            ZeroOne(_) => self.0 = ZeroOne(None),
            Multi(slice) => {
                let mut vec = slice.into_vec();
                vec.retain(f);
                *self = ShortBoxSlice::from(vec)
            }
        };
    }
}

impl<T> Deref for ShortBoxSlice<T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        use ShortBoxSliceInner::*;
        match self.0 {
            ZeroOne(None) => &[],
            ZeroOne(Some(ref v)) => core::slice::from_ref(v),
            Multi(ref v) => v,
        }
    }
}

impl<T> DerefMut for ShortBoxSlice<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        use ShortBoxSliceInner::*;
        match self.0 {
            ZeroOne(None) => &mut [],
            ZeroOne(Some(ref mut v)) => core::slice::from_mut(v),
            Multi(ref mut v) => v,
        }
    }
}

impl<T> From<Vec<T>> for ShortBoxSlice<T> {
    fn from(v: Vec<T>) -> Self {
        use ShortBoxSliceInner::*;
        match v.len() {
            0 => Self(ZeroOne(None)),
            #[allow(clippy::unwrap_used)] // we know that the vec is not empty
            1 => Self(ZeroOne(Some(v.into_iter().next().unwrap()))),
            _ => Self(Multi(v.into_boxed_slice())),
        }
    }
}

impl<T> FromIterator<T> for ShortBoxSlice<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        use ShortBoxSliceInner::*;
        let mut iter = iter.into_iter();
        match (iter.next(), iter.next()) {
            (Some(first), Some(second)) => {
                // Size hint behaviour same as `Vec::extend` + 2
                let mut vec = Vec::with_capacity(iter.size_hint().0.saturating_add(3));
                vec.push(first);
                vec.push(second);
                vec.extend(iter);
                Self(Multi(vec.into_boxed_slice()))
            }
            (first, _) => Self(ZeroOne(first)),
        }
    }
}

/// An iterator that yields elements from a [`ShortBoxSlice`].
#[derive(Debug)]
pub struct ShortBoxSliceIntoIter<T>(ShortBoxSliceIntoIterInner<T>);

#[derive(Debug)]
pub(crate) enum ShortBoxSliceIntoIterInner<T> {
    ZeroOne(Option<T>),
    Multi(alloc::vec::IntoIter<T>),
}

impl<T> Iterator for ShortBoxSliceIntoIter<T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        use ShortBoxSliceIntoIterInner::*;
        match &mut self.0 {
            ZeroOne(option) => option.take(),
            Multi(into_iter) => into_iter.next(),
        }
    }
}

impl<T> IntoIterator for ShortBoxSlice<T> {
    type Item = T;
    type IntoIter = ShortBoxSliceIntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        match self.0 {
            ShortBoxSliceInner::ZeroOne(option) => {
                ShortBoxSliceIntoIter(ShortBoxSliceIntoIterInner::ZeroOne(option))
            }
            // TODO: Use a boxed slice IntoIter impl when available:
            // <https://github.com/rust-lang/rust/issues/59878>
            ShortBoxSliceInner::Multi(boxed_slice) => ShortBoxSliceIntoIter(
                ShortBoxSliceIntoIterInner::Multi(boxed_slice.into_vec().into_iter()),
            ),
        }
    }
}

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

    #[test]
    #[allow(clippy::get_first)]
    fn test_new_single_const() {
        const MY_CONST_SLICE: ShortBoxSlice<i32> = ShortBoxSlice::new_single(42);

        assert_eq!(MY_CONST_SLICE.len(), 1);
        assert_eq!(MY_CONST_SLICE.get(0), Some(&42));
    }

    #[test]
    #[allow(clippy::redundant_pattern_matching)]
    fn test_get_single() {
        let mut vec = ShortBoxSlice::new();
        assert!(matches!(vec.single(), None));

        vec.push(100);
        assert!(matches!(vec.single(), Some(_)));

        vec.push(200);
        assert!(matches!(vec.single(), None));
    }
}