Coverage Report

Created: 2026-12-01 06:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/zerovec-0.11.8/src/varzerovec/components.rs
Line
Count
Source
1
// This file is part of ICU4X. For terms of use, please see the file
2
// called LICENSE at the top level of the ICU4X source tree
3
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5
#![allow(unused_qualifications)]
6
7
use super::VarZeroVecFormatError;
8
use crate::ule::*;
9
use core::cmp::Ordering;
10
use core::convert::TryFrom;
11
use core::marker::PhantomData;
12
use core::ops::Range;
13
14
/// This trait allows switching between different possible internal
15
/// representations of [`VarZeroVec`](super::VarZeroVec).
16
///
17
/// Currently this crate supports three formats: [`Index8`], [`Index16`] and [`Index32`],
18
/// with [`Index16`] being the default for all [`VarZeroVec`](super::VarZeroVec)
19
/// types unless explicitly specified otherwise.
20
///
21
/// Do not implement this trait, its internals may be changed in the future,
22
/// and all of its associated items are hidden from the docs.
23
pub trait VarZeroVecFormat: 'static + Sized {
24
    /// The type to use for the indexing array
25
    ///
26
    /// Safety: must be a ULE for which all byte sequences are allowed
27
    #[doc(hidden)]
28
    type Index: IntegerULE;
29
    /// The type to use for the length segment
30
    ///
31
    /// Safety: must be a ULE for which all byte sequences are allowed
32
    #[doc(hidden)]
33
    type Len: IntegerULE;
34
}
35
36
/// This trait represents various ULE types that can be used to represent an integer
37
///
38
/// Do not implement this trait, its internals may be changed in the future,
39
/// and all of its associated items are hidden from the docs.
40
#[doc(hidden)]
41
pub unsafe trait IntegerULE: ULE {
42
    /// The error to show when unable to construct a vec
43
    #[doc(hidden)]
44
    const TOO_LARGE_ERROR: &'static str;
45
46
    /// Safety: must be sizeof(self)
47
    #[doc(hidden)]
48
    const SIZE: usize;
49
50
    /// Safety: must be maximum integral value represented here
51
    #[doc(hidden)]
52
    const MAX_VALUE: u32;
53
54
    /// Safety: Must roundtrip with from_usize and represent the correct
55
    /// integral value
56
    #[doc(hidden)]
57
    fn iule_to_usize(self) -> usize;
58
59
    #[doc(hidden)]
60
    fn iule_from_usize(x: usize) -> Option<Self>;
61
62
    /// Safety: Should always convert a buffer into an array of Self with the correct length
63
    #[doc(hidden)]
64
    #[cfg(feature = "alloc")]
65
    fn iule_from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut [Self];
66
}
67
68
/// This is a [`VarZeroVecFormat`] that stores u8s in the index array, and a u8 for a length.
69
///
70
/// Will have a smaller data size, but it's *extremely* likely for larger arrays
71
/// to be unrepresentable (and error on construction). Should probably be used
72
/// for known-small arrays, where all but the last field are known-small.
73
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
74
#[allow(clippy::exhaustive_structs)] // marker
75
pub struct Index8;
76
77
/// This is a [`VarZeroVecFormat`] that stores u16s in the index array, and a u16 for a length.
78
///
79
/// Will have a smaller data size, but it's more likely for larger arrays
80
/// to be unrepresentable (and error on construction)
81
///
82
/// This is the default index size used by all [`VarZeroVec`](super::VarZeroVec) types.
83
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
84
#[allow(clippy::exhaustive_structs)] // marker
85
pub struct Index16;
86
87
/// This is a [`VarZeroVecFormat`] that stores u32s in the index array, and a u32 for a length.
88
/// Will have a larger data size, but will support large arrays without
89
/// problems.
90
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
91
#[allow(clippy::exhaustive_structs)] // marker
92
pub struct Index32;
93
94
impl VarZeroVecFormat for Index8 {
95
    type Index = u8;
96
    type Len = u8;
97
}
98
99
impl VarZeroVecFormat for Index16 {
100
    type Index = RawBytesULE<2>;
101
    type Len = RawBytesULE<2>;
102
}
103
104
impl VarZeroVecFormat for Index32 {
105
    type Index = RawBytesULE<4>;
106
    type Len = RawBytesULE<4>;
107
}
108
109
unsafe impl IntegerULE for u8 {
110
    const TOO_LARGE_ERROR: &'static str = "Attempted to build VarZeroVec out of elements that \
111
                                     cumulatively are larger than a u8 in size";
112
    const SIZE: usize = size_of::<Self>();
113
    const MAX_VALUE: u32 = u8::MAX as u32;
114
    #[inline]
115
0
    fn iule_to_usize(self) -> usize {
116
0
        self as usize
117
0
    }
118
    #[inline]
119
0
    fn iule_from_usize(u: usize) -> Option<Self> {
120
0
        u8::try_from(u).ok()
121
0
    }
122
    #[inline]
123
    #[cfg(feature = "alloc")]
124
0
    fn iule_from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut [Self] {
125
0
        bytes
126
0
    }
127
}
128
129
unsafe impl IntegerULE for RawBytesULE<2> {
130
    const TOO_LARGE_ERROR: &'static str = "Attempted to build VarZeroVec out of elements that \
131
                                     cumulatively are larger than a u16 in size";
132
    const SIZE: usize = size_of::<Self>();
133
    const MAX_VALUE: u32 = u16::MAX as u32;
134
    #[inline]
135
0
    fn iule_to_usize(self) -> usize {
136
0
        self.as_unsigned_int() as usize
137
0
    }
Unexecuted instantiation: <zerovec::ule::plain::RawBytesULE<2> as zerovec::varzerovec::components::IntegerULE>::iule_to_usize
Unexecuted instantiation: <zerovec::ule::plain::RawBytesULE<2> as zerovec::varzerovec::components::IntegerULE>::iule_to_usize
Unexecuted instantiation: <zerovec::ule::plain::RawBytesULE<2> as zerovec::varzerovec::components::IntegerULE>::iule_to_usize
138
    #[inline]
139
0
    fn iule_from_usize(u: usize) -> Option<Self> {
140
0
        u16::try_from(u).ok().map(u16::to_unaligned)
141
0
    }
Unexecuted instantiation: <zerovec::ule::plain::RawBytesULE<2> as zerovec::varzerovec::components::IntegerULE>::iule_from_usize
Unexecuted instantiation: <zerovec::ule::plain::RawBytesULE<2> as zerovec::varzerovec::components::IntegerULE>::iule_from_usize
142
    #[inline]
143
    #[cfg(feature = "alloc")]
144
0
    fn iule_from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut [Self] {
145
0
        Self::from_bytes_unchecked_mut(bytes)
146
0
    }
147
}
148
149
unsafe impl IntegerULE for RawBytesULE<4> {
150
    const TOO_LARGE_ERROR: &'static str = "Attempted to build VarZeroVec out of elements that \
151
                                     cumulatively are larger than a u32 in size";
152
    const SIZE: usize = size_of::<Self>();
153
    const MAX_VALUE: u32 = u32::MAX;
154
    #[inline]
155
0
    fn iule_to_usize(self) -> usize {
156
0
        self.as_unsigned_int() as usize
157
0
    }
158
    #[inline]
159
0
    fn iule_from_usize(u: usize) -> Option<Self> {
160
0
        u32::try_from(u).ok().map(u32::to_unaligned)
161
0
    }
162
    #[inline]
163
    #[cfg(feature = "alloc")]
164
0
    fn iule_from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut [Self] {
165
0
        Self::from_bytes_unchecked_mut(bytes)
166
0
    }
167
}
168
169
/// A more parsed version of [`VarZeroSlice`](super::VarZeroSlice). This type is where most of the[ `VarZeroVec`](super::VarZeroVec)
170
/// internal representation code lies.
171
///
172
/// This is *basically* an `&'a [u8]` to a zero copy buffer, but split out into
173
/// the buffer components. Logically this is capable of behaving as
174
/// a `&'a [T::VarULE]`, but since `T::VarULE` is unsized that type does not actually
175
/// exist.
176
///
177
/// See [`VarZeroVecComponents::parse_bytes()`] for information on the internal invariants involved
178
#[derive(Debug)]
179
pub struct VarZeroVecComponents<'a, T: ?Sized, F> {
180
    /// The number of elements
181
    len: u32,
182
    /// The list of indices into the `things` slice
183
    /// Since the first element is always at things[0], the first element of the indices array is for the *second* element
184
    indices: &'a [u8],
185
    /// The contiguous list of `T::VarULE`s
186
    things: &'a [u8],
187
    marker: PhantomData<(&'a T, F)>,
188
}
189
190
// #[derive()] won't work here since we do not want it to be
191
// bound on T: Copy
192
impl<'a, T: ?Sized, F> Copy for VarZeroVecComponents<'a, T, F> {}
193
impl<'a, T: ?Sized, F> Clone for VarZeroVecComponents<'a, T, F> {
194
0
    fn clone(&self) -> Self {
195
0
        *self
196
0
    }
197
}
198
199
impl<'a, T: VarULE + ?Sized, F> Default for VarZeroVecComponents<'a, T, F> {
200
    #[inline]
201
0
    fn default() -> Self {
202
0
        Self::new()
203
0
    }
204
}
205
206
impl<'a, T: VarULE + ?Sized, F> VarZeroVecComponents<'a, T, F> {
207
    #[inline]
208
0
    pub fn new() -> Self {
209
0
        Self {
210
0
            len: 0,
211
0
            indices: &[],
212
0
            things: &[],
213
0
            marker: PhantomData,
214
0
        }
215
0
    }
216
}
217
impl<'a, T: VarULE + ?Sized, F: VarZeroVecFormat> VarZeroVecComponents<'a, T, F> {
218
    /// Construct a new [`VarZeroVecComponents`], checking invariants about the overall buffer size:
219
    ///
220
    /// - There must be either zero or at least four bytes (if four, this is the "length" parsed as a usize)
221
    /// - There must be at least `4*(length - 1) + 4` bytes total, to form the array `indices` of indices
222
    /// - `0..indices[0]` must index into a valid section of
223
    ///   `things` (the data after `indices`), such that it parses to a `T::VarULE`
224
    /// - `indices[i - 1]..indices[i]` must index into a valid section of
225
    ///   `things` (the data after `indices`), such that it parses to a `T::VarULE`
226
    /// - `indices[len - 2]..things.len()` must index into a valid section of
227
    ///   `things`, such that it parses to a `T::VarULE`
228
    #[inline]
229
0
    pub fn parse_bytes(slice: &'a [u8]) -> Result<Self, VarZeroVecFormatError> {
230
        // The empty VZV is special-cased to the empty slice
231
0
        if slice.is_empty() {
232
0
            return Ok(VarZeroVecComponents {
233
0
                len: 0,
234
0
                indices: &[],
235
0
                things: &[],
236
0
                marker: PhantomData,
237
0
            });
238
0
        }
239
0
        let len_bytes = slice
240
0
            .get(0..F::Len::SIZE)
241
0
            .ok_or(VarZeroVecFormatError::Metadata)?;
242
0
        let len_ule =
243
0
            F::Len::parse_bytes_to_slice(len_bytes).map_err(|_| VarZeroVecFormatError::Metadata)?;
244
245
0
        let len = len_ule
246
0
            .first()
247
0
            .ok_or(VarZeroVecFormatError::Metadata)?
248
0
            .iule_to_usize();
249
250
0
        let rest = slice
251
0
            .get(F::Len::SIZE..)
252
0
            .ok_or(VarZeroVecFormatError::Metadata)?;
253
0
        let len_u32 = u32::try_from(len).map_err(|_| VarZeroVecFormatError::Metadata);
254
        // We pass down the rest of the invariants
255
0
        Self::parse_bytes_with_length(len_u32?, rest)
256
0
    }
257
258
    /// Construct a new [`VarZeroVecComponents`], checking invariants about the overall buffer size:
259
    ///
260
    /// - There must be at least `4*len` bytes total, to form the array `indices` of indices.
261
    /// - `indices[i]..indices[i+1]` must index into a valid section of
262
    ///   `things` (the data after `indices`), such that it parses to a `T::VarULE`
263
    /// - `indices[len - 1]..things.len()` must index into a valid section of
264
    ///   `things`, such that it parses to a `T::VarULE`
265
    #[inline]
266
0
    pub fn parse_bytes_with_length(
267
0
        len: u32,
268
0
        slice: &'a [u8],
269
0
    ) -> Result<Self, VarZeroVecFormatError> {
270
0
        let len_minus_one = len.checked_sub(1);
271
        // The empty VZV is special-cased to the empty slice
272
0
        let Some(len_minus_one) = len_minus_one else {
273
0
            return Ok(VarZeroVecComponents {
274
0
                len: 0,
275
0
                indices: &[],
276
0
                things: &[],
277
0
                marker: PhantomData,
278
0
            });
279
        };
280
        // The indices array is one element shorter since the first index is always 0,
281
        // so we use len_minus_one
282
        //
283
        // We do the math in u32 space so that we can be sure that VZVs constructed
284
        // on 64 bit computers can still be used on 32 bit ones.
285
0
        let indices_len = u32::try_from(F::Index::SIZE)
286
0
            .ok()
287
0
            .and_then(|x| x.checked_mul(len_minus_one))
288
0
            .and_then(|x| usize::try_from(x).ok())
289
0
            .ok_or(VarZeroVecFormatError::Metadata)?;
290
0
        let indices_bytes = slice
291
0
            .get(..indices_len)
292
0
            .ok_or(VarZeroVecFormatError::Metadata)?;
293
0
        let things = slice
294
0
            .get(indices_len..)
295
0
            .ok_or(VarZeroVecFormatError::Metadata)?;
296
297
0
        let borrowed = VarZeroVecComponents {
298
0
            len,
299
0
            indices: indices_bytes,
300
0
            things,
301
0
            marker: PhantomData,
302
0
        };
303
304
0
        borrowed.check_indices_and_things()?;
305
306
0
        Ok(borrowed)
307
0
    }
308
309
    /// Construct a [`VarZeroVecComponents`] from a byte slice that has previously
310
    /// successfully returned a [`VarZeroVecComponents`] when passed to
311
    /// [`VarZeroVecComponents::parse_bytes()`]. Will return the same
312
    /// object as one would get from calling [`VarZeroVecComponents::parse_bytes()`].
313
    ///
314
    /// # Safety
315
    /// The bytes must have previously successfully run through
316
    /// [`VarZeroVecComponents::parse_bytes()`]
317
0
    pub unsafe fn from_bytes_unchecked(slice: &'a [u8]) -> Self {
318
        // The empty VZV is special-cased to the empty slice
319
0
        if slice.is_empty() {
320
0
            return VarZeroVecComponents {
321
0
                len: 0,
322
0
                indices: &[],
323
0
                things: &[],
324
0
                marker: PhantomData,
325
0
            };
326
0
        }
327
0
        let (len_bytes, data_bytes) = unsafe { slice.split_at_unchecked(F::Len::SIZE) };
328
        // Safety: F::Len allows all byte sequences
329
0
        let len_ule = F::Len::slice_from_bytes_unchecked(len_bytes);
330
331
0
        let len = len_ule.get_unchecked(0).iule_to_usize();
332
0
        let len_u32 = len as u32;
333
0
        debug_assert_eq!(len, len_u32 as usize);
334
335
        // Safety: This method requires the bytes to have passed through `parse_bytes()`
336
        // whereas we're calling something that asks for `parse_bytes_with_length()`.
337
        // The two methods perform similar validation, with parse_bytes() validating an additional
338
        // 4-byte `length` header.
339
0
        Self::from_bytes_unchecked_with_length(len_u32, data_bytes)
340
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::from_bytes_unchecked
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::from_bytes_unchecked
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::from_bytes_unchecked
341
342
    /// Construct a [`VarZeroVecComponents`] from a byte slice that has previously
343
    /// successfully returned a [`VarZeroVecComponents`] when passed to
344
    /// [`VarZeroVecComponents::parse_bytes()`]. Will return the same
345
    /// object as one would get from calling [`VarZeroVecComponents::parse_bytes()`].
346
    ///
347
    /// # Safety
348
    /// The len,bytes must have previously successfully run through
349
    /// [`VarZeroVecComponents::parse_bytes_with_length()`]
350
0
    pub unsafe fn from_bytes_unchecked_with_length(len: u32, slice: &'a [u8]) -> Self {
351
0
        let len_minus_one = len.checked_sub(1);
352
        // The empty VZV is special-cased to the empty slice
353
0
        let Some(len_minus_one) = len_minus_one else {
354
0
            return VarZeroVecComponents {
355
0
                len: 0,
356
0
                indices: &[],
357
0
                things: &[],
358
0
                marker: PhantomData,
359
0
            };
360
        };
361
        // The indices array is one element shorter since the first index is always 0,
362
        // so we use len_minus_one
363
0
        let indices_len = F::Index::SIZE.wrapping_mul(len_minus_one as usize);
364
0
        debug_assert!(F::Index::SIZE.checked_mul(len_minus_one as usize).is_some());
365
0
        let indices_bytes = slice.get_unchecked(..indices_len);
366
0
        let things = slice.get_unchecked(indices_len..);
367
368
0
        VarZeroVecComponents {
369
0
            len,
370
0
            indices: indices_bytes,
371
0
            things,
372
0
            marker: PhantomData,
373
0
        }
374
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::from_bytes_unchecked_with_length
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<[u8], zerovec::varzerovec::components::Index16>>::from_bytes_unchecked_with_length
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::from_bytes_unchecked_with_length
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::from_bytes_unchecked_with_length
375
376
    /// Get the number of elements in this vector
377
    #[inline]
378
0
    pub fn len(self) -> usize {
379
0
        self.len as usize
380
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::len
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<[u8], zerovec::varzerovec::components::Index16>>::len
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::len
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::len
381
382
    /// Returns `true` if the vector contains no elements.
383
    #[inline]
384
0
    pub fn is_empty(self) -> bool {
385
0
        self.len == 0
386
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::is_empty
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::is_empty
387
388
    /// Get the idx'th element out of this slice. Returns `None` if out of bounds.
389
    #[inline]
390
0
    pub fn get(self, idx: usize) -> Option<&'a T> {
391
0
        if idx >= self.len() {
392
0
            return None;
393
0
        }
394
0
        Some(unsafe { self.get_unchecked(idx) })
395
0
    }
396
397
    /// Get the idx'th element out of this slice. Does not bounds check.
398
    ///
399
    /// Safety:
400
    /// - `idx` must be in bounds (`idx < self.len()`)
401
    #[inline]
402
0
    pub(crate) unsafe fn get_unchecked(self, idx: usize) -> &'a T {
403
0
        let range = self.get_things_range(idx);
404
0
        let things_slice = self.things.get_unchecked(range);
405
0
        T::from_bytes_unchecked(things_slice)
406
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::get_unchecked
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<[u8], zerovec::varzerovec::components::Index16>>::get_unchecked
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::get_unchecked
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::get_unchecked
407
408
    /// Get the range in `things` for the element at `idx`. Does not bounds check.
409
    ///
410
    /// Safety:
411
    /// - `idx` must be in bounds (`idx < self.len()`)
412
    #[inline]
413
0
    pub(crate) unsafe fn get_things_range(self, idx: usize) -> Range<usize> {
414
0
        let start = if let Some(idx_minus_one) = idx.checked_sub(1) {
415
0
            self.indices_slice()
416
0
                .get_unchecked(idx_minus_one)
417
0
                .iule_to_usize()
418
        } else {
419
0
            0
420
        };
421
0
        let end = if idx + 1 == self.len() {
422
0
            self.things.len()
423
        } else {
424
0
            self.indices_slice().get_unchecked(idx).iule_to_usize()
425
        };
426
0
        debug_assert!(start <= end);
427
0
        start..end
428
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::get_things_range
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<[u8], zerovec::varzerovec::components::Index16>>::get_things_range
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::get_things_range
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::get_things_range
429
430
    /// Get the size, in bytes, of the indices array
431
0
    pub(crate) unsafe fn get_indices_size(self) -> usize {
432
0
        self.indices.len()
433
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<[u8], zerovec::varzerovec::components::Index16>>::get_indices_size
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::get_indices_size
434
435
    /// Check the internal invariants of [`VarZeroVecComponents`]:
436
    ///
437
    /// - `indices[i]..indices[i+1]` must index into a valid section of
438
    ///   `things`, such that it parses to a `T::VarULE`
439
    /// - `indices[len - 1]..things.len()` must index into a valid section of
440
    ///   `things`, such that it parses to a `T::VarULE`
441
    /// - `indices` is monotonically increasing
442
    ///
443
    /// This method is NOT allowed to call any other methods on [`VarZeroVecComponents`] since all other methods
444
    /// assume that the slice has been passed through [`Self::check_indices_and_things`]
445
    #[inline]
446
    #[expect(clippy::len_zero)] // more explicit to enforce safety invariants
447
0
    fn check_indices_and_things(self) -> Result<(), VarZeroVecFormatError> {
448
0
        if self.len() == 0 {
449
0
            if self.things.len() > 0 {
450
0
                return Err(VarZeroVecFormatError::Metadata);
451
            } else {
452
0
                return Ok(());
453
            }
454
0
        }
455
0
        let indices_slice = self.indices_slice();
456
0
        assert_eq!(self.len(), indices_slice.len() + 1);
457
        // Safety: i is in bounds (assertion above)
458
0
        let mut start = 0;
459
0
        for i in 0..self.len() {
460
            // The indices array is offset by 1: indices[0] is the end of the first
461
            // element and the start of the next, since the start of the first element
462
            // is always things[0]. So to get the end we get element `i`.
463
0
            let end = if let Some(end) = indices_slice.get(i) {
464
0
                end.iule_to_usize()
465
            } else {
466
                // This only happens at i = self.len() - 1 = indices_slice.len() + 1 - 1
467
                // = indices_slice.len(). This is the last `end`, which is always the size of
468
                // `things` and thus never stored in the array
469
0
                self.things.len()
470
            };
471
472
0
            if start > end {
473
0
                return Err(VarZeroVecFormatError::Metadata);
474
0
            }
475
0
            if end > self.things.len() {
476
0
                return Err(VarZeroVecFormatError::Metadata);
477
0
            }
478
            // Safety: start..end is a valid range in self.things
479
0
            let bytes = unsafe { self.things.get_unchecked(start..end) };
480
0
            T::parse_bytes(bytes).map_err(VarZeroVecFormatError::Values)?;
481
0
            start = end;
482
        }
483
0
        Ok(())
484
0
    }
485
486
    /// Create an iterator over the Ts contained in [`VarZeroVecComponents`]
487
    #[inline]
488
0
    pub fn iter(self) -> VarZeroSliceIter<'a, T, F> {
489
0
        VarZeroSliceIter::new(self)
490
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::iter
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::iter
491
492
    #[cfg(feature = "alloc")]
493
0
    pub fn to_vec(self) -> alloc::vec::Vec<alloc::boxed::Box<T>> {
494
0
        self.iter().map(T::to_boxed).collect()
495
0
    }
496
497
    #[inline]
498
0
    fn indices_slice(&self) -> &'a [F::Index] {
499
0
        unsafe { F::Index::slice_from_bytes_unchecked(self.indices) }
500
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::indices_slice
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<[u8], zerovec::varzerovec::components::Index16>>::indices_slice
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::indices_slice
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::indices_slice
501
502
    // Dump a debuggable representation of this type
503
    #[allow(unused)] // useful for debugging
504
    #[cfg(feature = "alloc")]
505
0
    pub(crate) fn dump(&self) -> alloc::string::String {
506
0
        let indices = self
507
0
            .indices_slice()
508
0
            .iter()
509
0
            .copied()
510
0
            .map(IntegerULE::iule_to_usize)
511
0
            .collect::<alloc::vec::Vec<_>>();
512
0
        alloc::format!("VarZeroVecComponents {{ indices: {indices:?} }}")
513
0
    }
514
}
515
516
/// An iterator over [`VarZeroSlice`](super::VarZeroSlice)
517
#[derive(Debug)]
518
pub struct VarZeroSliceIter<'a, T: ?Sized, F = Index16> {
519
    components: VarZeroVecComponents<'a, T, F>,
520
    index: usize,
521
    // Safety invariant: must be a valid index into the data segment of `components`, or an index at the end
522
    // i.e. start_index <= components.things.len()
523
    //
524
    // It must be a valid index into the `things` array of components, coming from `components.indices_slice()`
525
    start_index: usize,
526
}
527
528
impl<'a, T: VarULE + ?Sized, F: VarZeroVecFormat> Clone for VarZeroSliceIter<'a, T, F> {
529
0
    fn clone(&self) -> Self {
530
0
        Self {
531
0
            components: self.components,
532
0
            index: self.index,
533
0
            start_index: self.start_index,
534
0
        }
535
0
    }
536
}
537
538
impl<'a, T: VarULE + ?Sized, F: VarZeroVecFormat> VarZeroSliceIter<'a, T, F> {
539
0
    fn new(c: VarZeroVecComponents<'a, T, F>) -> Self {
540
0
        Self {
541
0
            components: c,
542
0
            index: 0,
543
0
            // Invariant upheld, 0 is always a valid index-or-end
544
0
            start_index: 0,
545
0
        }
546
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroSliceIter<str>>::new
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroSliceIter<_, _>>::new
547
}
548
impl<'a, T: VarULE + ?Sized, F: VarZeroVecFormat> Iterator for VarZeroSliceIter<'a, T, F> {
549
    type Item = &'a T;
550
551
0
    fn next(&mut self) -> Option<Self::Item> {
552
        // Note: the indices array doesn't contain 0 or len, we need to specially handle those edges. The 0 is handled
553
        // by start_index, and the len is handled by the code for `end`.
554
555
0
        if self.index >= self.components.len() {
556
0
            return None;
557
0
        }
558
559
        // Invariant established: self.index is in bounds for self.components.len(),
560
        // which means it is in bounds for self.components.indices_slice() since that has the same length
561
562
0
        let end = if self.index + 1 == self.components.len() {
563
            // We don't store the end index since it is computable, so the last element should use self.components.things.len()
564
0
            self.components.things.len()
565
        } else {
566
            // Safety: self.index was known to be in bounds from the bounds check above.
567
            unsafe {
568
0
                self.components
569
0
                    .indices_slice()
570
0
                    .get_unchecked(self.index)
571
0
                    .iule_to_usize()
572
            }
573
        };
574
        // Invariant established: end has the same invariant as self.start_index since it comes from indices_slice, which is guaranteed
575
        // to only contain valid indexes
576
577
0
        let item = unsafe {
578
            // Safety: self.start_index and end both have in-range invariants, plus they are valid indices from indices_slice
579
            // which means we can treat this data as a T
580
0
            T::from_bytes_unchecked(self.components.things.get_unchecked(self.start_index..end))
581
        };
582
0
        self.index += 1;
583
        // Invariant upheld: end has the same invariant as self.start_index
584
0
        self.start_index = end;
585
0
        Some(item)
586
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroSliceIter<str> as core::iter::traits::iterator::Iterator>::next
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroSliceIter<_, _> as core::iter::traits::iterator::Iterator>::next
587
588
0
    fn size_hint(&self) -> (usize, Option<usize>) {
589
0
        let remainder = self.components.len() - self.index;
590
0
        (remainder, Some(remainder))
591
0
    }
592
}
593
594
impl<'a, T: VarULE + ?Sized, F: VarZeroVecFormat> ExactSizeIterator for VarZeroSliceIter<'a, T, F> {
595
0
    fn len(&self) -> usize {
596
0
        self.components.len() - self.index
597
0
    }
598
}
599
600
impl<'a, T, F> VarZeroVecComponents<'a, T, F>
601
where
602
    T: VarULE,
603
    T: ?Sized,
604
    T: Ord,
605
    F: VarZeroVecFormat,
606
{
607
    /// Binary searches a sorted `VarZeroVecComponents<T>` for the given element. For more information, see
608
    /// the primitive function [`binary_search`](slice::binary_search).
609
0
    pub fn binary_search(&self, needle: &T) -> Result<usize, usize> {
610
0
        self.binary_search_by(|probe| probe.cmp(needle))
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search::{closure#0}
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::binary_search::{closure#0}
611
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::binary_search
612
613
0
    pub fn binary_search_in_range(
614
0
        &self,
615
0
        needle: &T,
616
0
        range: Range<usize>,
617
0
    ) -> Option<Result<usize, usize>> {
618
0
        self.binary_search_in_range_by(|probe| probe.cmp(needle), range)
619
0
    }
620
}
621
622
impl<'a, T, F> VarZeroVecComponents<'a, T, F>
623
where
624
    T: VarULE,
625
    T: ?Sized,
626
    F: VarZeroVecFormat,
627
{
628
    /// Binary searches a sorted `VarZeroVecComponents<T>` for the given predicate. For more information, see
629
    /// the primitive function [`binary_search_by`](slice::binary_search_by).
630
0
    pub fn binary_search_by(&self, predicate: impl FnMut(&T) -> Ordering) -> Result<usize, usize> {
631
        // Safety: 0 and len are in range
632
0
        unsafe { self.binary_search_in_range_unchecked(predicate, 0..self.len()) }
633
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::binary_search_by::<<icu_locale_fallback::LocaleFallbackIteratorInner>::get_explicit_parent::{closure#0}>
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search_by::<<icu_collections::codepointinvliststringlist::CodePointInversionListAndStringList>::contains_utf8::{closure#0}>
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search_by::<<zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search::{closure#0}>
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::binary_search_by::<_>
634
635
    // Binary search within a range.
636
    // Values returned are relative to the range start!
637
0
    pub fn binary_search_in_range_by(
638
0
        &self,
639
0
        predicate: impl FnMut(&T) -> Ordering,
640
0
        range: Range<usize>,
641
0
    ) -> Option<Result<usize, usize>> {
642
0
        if range.end > self.len() {
643
0
            return None;
644
0
        }
645
0
        if range.end < range.start {
646
0
            return None;
647
0
        }
648
        // Safety: We bounds checked above: end is in-bounds or len, and start is <= end
649
0
        let range_absolute =
650
0
            unsafe { self.binary_search_in_range_unchecked(predicate, range.clone()) };
651
        // The values returned are relative to the range start
652
        Some(
653
0
            range_absolute
654
0
                .map(|o| o - range.start)
655
0
                .map_err(|e| e - range.start),
656
        )
657
0
    }
658
659
    /// Safety: range must be in range for the slice (start <= len, end <= len, start <= end)
660
0
    unsafe fn binary_search_in_range_unchecked(
661
0
        &self,
662
0
        mut predicate: impl FnMut(&T) -> Ordering,
663
0
        range: Range<usize>,
664
0
    ) -> Result<usize, usize> {
665
        // Function invariant: size is always end - start
666
0
        let mut start = range.start;
667
0
        let mut end = range.end;
668
        let mut size;
669
670
        // Loop invariant: 0 <= start < end <= len
671
        // This invariant is initialized by the function safety invariants and the loop condition
672
0
        while start < end {
673
0
            size = end - start;
674
            // This establishes mid < end (which implies mid < len)
675
            // size is end - start. start + size is end (which is <= len).
676
            // mid = start + size/2 will be less than end
677
0
            let mid = start + size / 2;
678
679
            // Safety: mid is < end <= len, so in-range
680
0
            let cmp = predicate(self.get_unchecked(mid));
681
682
0
            match cmp {
683
0
                Ordering::Less => {
684
0
                    // This retains the loop invariant since it
685
0
                    // increments start, and we already have 0 <= start
686
0
                    // start < end is enforced by the loop condition
687
0
                    start = mid + 1;
688
0
                }
689
0
                Ordering::Greater => {
690
0
                    // mid < end, so this decreases end.
691
0
                    // This means end <= len is still true, and
692
0
                    // end > start is enforced by the loop condition
693
0
                    end = mid;
694
0
                }
695
0
                Ordering::Equal => return Ok(mid),
696
            }
697
        }
698
0
        Err(start)
699
0
    }
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<potential_utf::ustr::PotentialUtf8, zerovec::varzerovec::components::Index16>>::binary_search_in_range_unchecked::<<icu_locale_fallback::LocaleFallbackIteratorInner>::get_explicit_parent::{closure#0}>
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search_in_range_unchecked::<<icu_collections::codepointinvliststringlist::CodePointInversionListAndStringList>::contains_utf8::{closure#0}>
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search_in_range_unchecked::<<zerovec::varzerovec::components::VarZeroVecComponents<str, zerovec::varzerovec::components::Index16>>::binary_search::{closure#0}>
Unexecuted instantiation: <zerovec::varzerovec::components::VarZeroVecComponents<_, _>>::binary_search_in_range_unchecked::<_>
700
}
701
702
/// Collects the bytes for a [`VarZeroSlice`](super::VarZeroSlice) into a [`Vec`].
703
#[cfg(feature = "alloc")]
704
0
pub fn get_serializable_bytes_non_empty<T, A, F>(elements: &[A]) -> Option<alloc::vec::Vec<u8>>
705
0
where
706
0
    T: VarULE + ?Sized,
707
0
    A: EncodeAsVarULE<T>,
708
0
    F: VarZeroVecFormat,
709
{
710
0
    debug_assert!(!elements.is_empty());
711
0
    let len = compute_serializable_len::<T, A, F>(elements)?;
712
0
    debug_assert!(
713
0
        len >= F::Len::SIZE as u32,
714
0
        "Must have at least F::Len::SIZE bytes to hold the length of the vector"
715
    );
716
0
    let mut output = alloc::vec![0u8; len as usize];
717
0
    write_serializable_bytes::<T, A, F>(elements, &mut output);
718
0
    Some(output)
719
0
}
720
721
/// Writes the bytes for a [`VarZeroLengthlessSlice`](super::lenghtless::VarZeroLengthlessSlice) into an output buffer.
722
/// Usable for a [`VarZeroSlice`](super::VarZeroSlice) if you first write the length bytes.
723
///
724
/// Every byte in the buffer will be initialized after calling this function.
725
///
726
/// # Panics
727
///
728
/// Panics if the buffer is not exactly the correct length.
729
0
pub fn write_serializable_bytes_without_length<T, A, F>(elements: &[A], output: &mut [u8])
730
0
where
731
0
    T: VarULE + ?Sized,
732
0
    A: EncodeAsVarULE<T>,
733
0
    F: VarZeroVecFormat,
734
{
735
0
    assert!(elements.len() <= F::Len::MAX_VALUE as usize);
736
0
    if elements.is_empty() {
737
0
        return;
738
0
    }
739
740
    // idx_offset = offset from the start of the buffer for the next index
741
0
    let mut idx_offset: usize = 0;
742
    // first_dat_offset = offset from the start of the buffer of the first data block
743
    #[expect(
744
        clippy::expect_used,
745
        reason = "Function contract allows panicky behavior"
746
    )]
747
0
    let indices_size = F::Index::SIZE
748
0
        .checked_mul(elements.len() - 1)
749
0
        .expect(F::Index::TOO_LARGE_ERROR);
750
0
    let first_dat_offset: usize = idx_offset + indices_size;
751
    // dat_offset = offset from the start of the buffer of the next data block
752
0
    let mut dat_offset: usize = first_dat_offset;
753
754
0
    for (i, element) in elements.iter().enumerate() {
755
0
        let element_len = element.encode_var_ule_len();
756
757
        // The first index is always 0. We don't write it, or update the idx offset.
758
0
        if i != 0 {
759
0
            let idx_limit = idx_offset + F::Index::SIZE;
760
            #[expect(clippy::indexing_slicing)] // Function contract allows panicky behavior
761
0
            let idx_slice = &mut output[idx_offset..idx_limit];
762
            // VZV expects data offsets to be stored relative to the first data block
763
0
            let idx = dat_offset - first_dat_offset;
764
0
            assert!(idx <= F::Index::MAX_VALUE as usize);
765
            #[expect(clippy::expect_used)] // this function is explicitly panicky
766
0
            let bytes_to_write = F::Index::iule_from_usize(idx).expect(F::Index::TOO_LARGE_ERROR);
767
0
            idx_slice.copy_from_slice(ULE::slice_as_bytes(&[bytes_to_write]));
768
769
0
            idx_offset = idx_limit;
770
0
        }
771
772
0
        let dat_limit = dat_offset + element_len;
773
        #[expect(
774
            clippy::indexing_slicing,
775
            reason = "Function contract allows panicky behavior"
776
        )]
777
0
        let dat_slice = &mut output[dat_offset..dat_limit];
778
0
        element.encode_var_ule_write(dat_slice);
779
0
        debug_assert_eq!(T::validate_bytes(dat_slice), Ok(()));
780
0
        dat_offset = dat_limit;
781
    }
782
783
    #[expect(
784
        clippy::expect_used,
785
        reason = "Function contract allows panicky behavior"
786
    )]
787
0
    let indices_size = F::Index::SIZE
788
0
        .checked_mul(elements.len() - 1)
789
0
        .expect(F::Index::TOO_LARGE_ERROR);
790
0
    debug_assert_eq!(idx_offset, indices_size);
791
0
    assert_eq!(dat_offset, output.len());
792
0
}
Unexecuted instantiation: zerovec::varzerovec::components::write_serializable_bytes_without_length::<[u8], zerovec::ule::multi::BlankSliceEncoder, zerovec::varzerovec::components::Index16>
Unexecuted instantiation: zerovec::varzerovec::components::write_serializable_bytes_without_length::<_, _, _>
793
794
/// Writes the bytes for a [`VarZeroSlice`](super::VarZeroSlice) into an output buffer.
795
///
796
/// Every byte in the buffer will be initialized after calling this function.
797
///
798
/// # Panics
799
///
800
/// Panics if the buffer is not exactly the correct length.
801
0
pub fn write_serializable_bytes<T, A, F>(elements: &[A], output: &mut [u8])
802
0
where
803
0
    T: VarULE + ?Sized,
804
0
    A: EncodeAsVarULE<T>,
805
0
    F: VarZeroVecFormat,
806
{
807
0
    if elements.is_empty() {
808
0
        return;
809
0
    }
810
0
    assert!(elements.len() <= F::Len::MAX_VALUE as usize);
811
    #[expect(clippy::expect_used)] // This function is explicitly panicky
812
0
    let num_elements_ule = F::Len::iule_from_usize(elements.len()).expect(F::Len::TOO_LARGE_ERROR);
813
    #[expect(clippy::indexing_slicing)] // Function contract allows panicky behavior
814
0
    output[0..F::Len::SIZE].copy_from_slice(ULE::slice_as_bytes(&[num_elements_ule]));
815
816
    #[expect(clippy::indexing_slicing)] // Function contract allows panicky behavior
817
0
    write_serializable_bytes_without_length::<T, A, F>(elements, &mut output[F::Len::SIZE..]);
818
0
}
819
820
0
pub fn compute_serializable_len_without_length<T, A, F>(elements: &[A]) -> Option<u32>
821
0
where
822
0
    T: VarULE + ?Sized,
823
0
    A: EncodeAsVarULE<T>,
824
0
    F: VarZeroVecFormat,
825
{
826
0
    let elements_len = elements.len();
827
0
    let Some(elements_len_minus_one) = elements_len.checked_sub(1) else {
828
        // Empty vec is optimized to an empty byte representation
829
0
        return Some(0);
830
    };
831
0
    let idx_len: u32 = u32::try_from(elements_len_minus_one)
832
0
        .ok()?
833
0
        .checked_mul(F::Index::SIZE as u32)?;
834
0
    let data_len: u32 = elements
835
0
        .iter()
836
0
        .map(|v| u32::try_from(v.encode_var_ule_len()).ok())
Unexecuted instantiation: zerovec::varzerovec::components::compute_serializable_len_without_length::<[u8], zerovec::ule::multi::BlankSliceEncoder, zerovec::varzerovec::components::Index16>::{closure#0}
Unexecuted instantiation: zerovec::varzerovec::components::compute_serializable_len_without_length::<_, _, _>::{closure#0}
837
0
        .try_fold(0u32, |s, v| s.checked_add(v?))?;
Unexecuted instantiation: zerovec::varzerovec::components::compute_serializable_len_without_length::<[u8], zerovec::ule::multi::BlankSliceEncoder, zerovec::varzerovec::components::Index16>::{closure#1}
Unexecuted instantiation: zerovec::varzerovec::components::compute_serializable_len_without_length::<_, _, _>::{closure#1}
838
0
    let ret = idx_len.checked_add(data_len);
839
0
    if let Some(r) = ret {
840
0
        if r >= F::Index::MAX_VALUE {
841
0
            return None;
842
0
        }
843
0
    }
844
0
    ret
845
0
}
Unexecuted instantiation: zerovec::varzerovec::components::compute_serializable_len_without_length::<[u8], zerovec::ule::multi::BlankSliceEncoder, zerovec::varzerovec::components::Index16>
Unexecuted instantiation: zerovec::varzerovec::components::compute_serializable_len_without_length::<_, _, _>
846
847
0
pub fn compute_serializable_len<T, A, F>(elements: &[A]) -> Option<u32>
848
0
where
849
0
    T: VarULE + ?Sized,
850
0
    A: EncodeAsVarULE<T>,
851
0
    F: VarZeroVecFormat,
852
{
853
0
    compute_serializable_len_without_length::<T, A, F>(elements).map(|x| x + F::Len::SIZE as u32)
854
0
}