Skip to main content

arrow_buffer/buffer/
offset.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::buffer::ScalarBuffer;
6use crate::{ArrowNativeType, MutableBuffer, NullBuffer, OffsetBufferBuilder, OverflowError};
7use std::ops::Deref;
8
9/// A non-empty buffer of monotonically increasing, positive integers.
10///
11/// [`OffsetBuffer`] are used to represent ranges of offsets. An
12/// `OffsetBuffer` of `N+1` items contains `N` such ranges. The start
13/// offset for element `i` is `offsets[i]` and the end offset is
14/// `offsets[i+1]`. Equal offsets represent an empty range.
15///
16/// # Example
17///
18/// This example shows how 5 distinct ranges, are represented using a
19/// 6 entry `OffsetBuffer`. The first entry `(0, 3)` represents the
20/// three offsets `0, 1, 2`. The entry `(3,3)` represent no offsets
21/// (e.g. an empty list).
22///
23/// ```text
24///   ┌───────┐                ┌───┐
25///   │ (0,3) │                │ 0 │
26///   ├───────┤                ├───┤
27///   │ (3,3) │                │ 3 │
28///   ├───────┤                ├───┤
29///   │ (3,4) │                │ 3 │
30///   ├───────┤                ├───┤
31///   │ (4,5) │                │ 4 │
32///   ├───────┤                ├───┤
33///   │ (5,7) │                │ 5 │
34///   └───────┘                ├───┤
35///                            │ 7 │
36///                            └───┘
37///
38///                        Offsets Buffer
39///    Logical
40///    Offsets
41///
42///  (offsets[i],
43///   offsets[i+1])
44/// ```
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct OffsetBuffer<O: ArrowNativeType>(ScalarBuffer<O>);
47
48impl<O: ArrowNativeType> OffsetBuffer<O> {
49    /// Create a new [`OffsetBuffer`] from the provided [`ScalarBuffer`]
50    ///
51    /// # Panics
52    ///
53    /// Panics if `buffer` is not a non-empty buffer containing
54    /// monotonically increasing values greater than or equal to zero
55    pub fn new(buffer: ScalarBuffer<O>) -> Self {
56        assert!(!buffer.is_empty(), "offsets cannot be empty");
57        assert!(
58            buffer[0] >= O::usize_as(0),
59            "offsets must be greater than 0"
60        );
61        assert!(
62            buffer.windows(2).all(|w| w[0] <= w[1]),
63            "offsets must be monotonically increasing"
64        );
65        Self(buffer)
66    }
67
68    /// Create a new [`OffsetBuffer`] from the provided [`ScalarBuffer`]
69    ///
70    /// # Safety
71    ///
72    /// `buffer` must be a non-empty buffer containing monotonically increasing
73    /// values greater than or equal to zero
74    pub unsafe fn new_unchecked(buffer: ScalarBuffer<O>) -> Self {
75        if cfg!(feature = "force_validate") {
76            return Self::new(buffer);
77        }
78        Self(buffer)
79    }
80
81    /// Create a new [`OffsetBuffer`] containing a single 0 value
82    ///
83    /// # Panics
84    ///
85    /// Panics if allocation fails. Use [`Self::try_new_empty`] for a fallible version.
86    pub fn new_empty() -> Self {
87        let buffer = MutableBuffer::from_len_zeroed(std::mem::size_of::<O>());
88        Self(buffer.into_buffer().into())
89    }
90
91    /// Fallible version of [`Self::new_empty`].
92    pub fn try_new_empty() -> Result<Self, OverflowError> {
93        Self::try_new_zeroed(0)
94    }
95
96    /// Create a new [`OffsetBuffer`] containing `len + 1` `0` values
97    ///
98    /// # Panics
99    ///
100    /// Panics if `(len + 1) * size_of::<O>()` overflows `usize` or if the
101    /// required buffer cannot be allocated.
102    /// Use [`Self::try_new_zeroed`] for a fallible version.
103    pub fn new_zeroed(len: usize) -> Self {
104        Self::try_new_zeroed(len).unwrap_or_else(|err| panic!("{err}"))
105    }
106
107    /// Create a new [`OffsetBuffer`] containing `len + 1` `0` values
108    ///
109    /// # Errors
110    ///
111    /// Errors if `(len + 1) * size_of::<O>()` overflows `usize` or if the
112    /// required buffer cannot be allocated.
113    pub fn try_new_zeroed(len: usize) -> Result<Self, OverflowError> {
114        let len_bytes = len
115            .checked_add(1)
116            .and_then(|o| o.checked_mul(std::mem::size_of::<O>()))
117            .ok_or_else(|| OverflowError::new::<usize>("buffer length"))?;
118        let buffer = MutableBuffer::try_from_len_zeroed(len_bytes)
119            .map_err(|_| OverflowError::new::<usize>("buffer length"))?;
120        Ok(Self(buffer.into_buffer().into()))
121    }
122
123    /// Create a new [`OffsetBuffer`] from the iterator of slice lengths
124    ///
125    /// ```
126    /// # use arrow_buffer::OffsetBuffer;
127    /// let offsets = OffsetBuffer::<i32>::from_lengths([1, 3, 5]);
128    /// assert_eq!(offsets.as_ref(), &[0, 1, 4, 9]);
129    /// ```
130    ///
131    /// If you want to create an [`OffsetBuffer`] where all lengths are the same,
132    /// consider using the faster [`OffsetBuffer::from_repeated_length`] instead.
133    ///
134    /// # Panics
135    ///
136    /// Panics on overflow. Use [`Self::try_from_lengths`] for a fallible version.
137    pub fn from_lengths<I>(lengths: I) -> Self
138    where
139        I: IntoIterator<Item = usize>,
140    {
141        Self::try_from_lengths(lengths).unwrap_or_else(|err| panic!("{err}"))
142    }
143
144    /// Create a new [`OffsetBuffer`] from the iterator of slice lengths
145    ///
146    /// ```
147    /// # use arrow_buffer::OffsetBuffer;
148    /// let offsets = OffsetBuffer::<i32>::try_from_lengths([1, 3, 5]).unwrap();
149    /// assert_eq!(offsets.as_ref(), &[0, 1, 4, 9]);
150    /// ```
151    ///
152    /// # Errors
153    ///
154    /// Errors if the total length overflows `usize` or `O`, e.g. if the lengths
155    /// add up to more than `i32::MAX` for a `OffsetBuffer<i32>`.
156    pub fn try_from_lengths<I>(lengths: I) -> Result<Self, OverflowError>
157    where
158        I: IntoIterator<Item = usize>,
159    {
160        let iter = lengths.into_iter();
161        let mut out = Vec::with_capacity(iter.size_hint().0 + 1);
162        out.push(O::usize_as(0));
163
164        let mut acc = 0_usize;
165        for length in iter {
166            acc = acc
167                .checked_add(length)
168                .ok_or_else(|| OverflowError::new::<usize>("total length"))?;
169            out.push(O::usize_as(acc))
170        }
171        // Check for overflow
172        O::from_usize(acc).ok_or_else(|| OverflowError::new::<O>("offset").with_value(acc))?;
173        Ok(Self(out.into()))
174    }
175
176    /// Create a new [`OffsetBuffer`] where each slice has the same length
177    /// `length`, repeated `n` times.
178    ///
179    ///
180    /// Example
181    /// ```
182    /// # use arrow_buffer::OffsetBuffer;
183    /// let offsets = OffsetBuffer::<i32>::from_repeated_length(4, 3);
184    /// assert_eq!(offsets.as_ref(), &[0, 4, 8, 12]);
185    /// ```
186    ///
187    /// # Panics
188    ///
189    /// Panics on overflow or allocation failure.
190    /// Use [`Self::try_from_repeated_length`] for a fallible version.
191    pub fn from_repeated_length(length: usize, n: usize) -> Self {
192        Self::try_from_repeated_length(length, n).unwrap_or_else(|err| panic!("{err}"))
193    }
194
195    /// Create a new [`OffsetBuffer`] where each slice has the same length
196    /// `length`, repeated `n` times.
197    ///
198    /// ```
199    /// # use arrow_buffer::OffsetBuffer;
200    /// let offsets = OffsetBuffer::<i32>::try_from_repeated_length(4, 3).unwrap();
201    /// assert_eq!(offsets.as_ref(), &[0, 4, 8, 12]);
202    /// ```
203    ///
204    /// # Errors
205    ///
206    /// Errors if `length * n` overflows `usize` or `O`, or if the buffer cannot be allocated.
207    pub fn try_from_repeated_length(length: usize, n: usize) -> Result<Self, OverflowError> {
208        if n == 0 {
209            return Self::try_new_empty();
210        }
211
212        if length == 0 {
213            return Self::try_new_zeroed(n);
214        }
215
216        // Making sure we don't overflow usize or O when calculating the total length
217        let total_length = length
218            .checked_mul(n)
219            .ok_or_else(|| OverflowError::new::<usize>("total length"))?;
220
221        O::from_usize(total_length)
222            .ok_or_else(|| OverflowError::new::<O>("offset").with_value(total_length))?;
223
224        let len_bytes = n
225            .checked_add(1)
226            .and_then(|o| o.checked_mul(std::mem::size_of::<O>()))
227            .ok_or_else(|| OverflowError::new::<usize>("buffer length"))?;
228
229        let mut buffer = MutableBuffer::try_with_capacity(len_bytes)
230            .map_err(|_| OverflowError::new::<usize>("buffer length"))?;
231
232        for index in 0..=n {
233            // SAFETY: buffer capacity was allocated for `(n + 1) * size_of::<O>()` bytes.
234            unsafe {
235                buffer.push_unchecked(O::usize_as(index * length));
236            }
237        }
238
239        Ok(Self(buffer.into_buffer().into()))
240    }
241
242    /// The first offset, i.e. the start of the first range.
243    ///
244    /// An [`OffsetBuffer`] is never empty, so this always returns an offset.
245    ///
246    /// ```
247    /// # use arrow_buffer::OffsetBuffer;
248    /// let offsets = OffsetBuffer::<i32>::from_lengths([1, 3, 5]);
249    /// assert_eq!(offsets.first(), 0);
250    /// assert_eq!(OffsetBuffer::<i32>::new_empty().first(), 0);
251    /// ```
252    #[inline]
253    pub fn first(&self) -> O {
254        self.0
255            .first()
256            .copied()
257            .expect("An `OffsetBuffer` is never empty")
258    }
259
260    /// The last offset, i.e. the end of the last range.
261    ///
262    /// An [`OffsetBuffer`] is never empty, so this always returns an offset.
263    ///
264    /// ```
265    /// # use arrow_buffer::OffsetBuffer;
266    /// let offsets = OffsetBuffer::<i32>::from_lengths([1, 3, 5]);
267    /// assert_eq!(offsets.last(), 9);
268    /// assert_eq!(OffsetBuffer::<i32>::new_empty().last(), 0);
269    /// ```
270    #[inline]
271    pub fn last(&self) -> O {
272        self.0
273            .last()
274            .copied()
275            .expect("An `OffsetBuffer` is never empty")
276    }
277
278    /// Get an Iterator over the lengths of this [`OffsetBuffer`]
279    ///
280    /// ```
281    /// # use arrow_buffer::{OffsetBuffer, ScalarBuffer};
282    /// let offsets = OffsetBuffer::<_>::new(ScalarBuffer::<i32>::from(vec![0, 1, 4, 9]));
283    /// assert_eq!(offsets.lengths().collect::<Vec<usize>>(), vec![1, 3, 5]);
284    /// ```
285    ///
286    /// Empty [`OffsetBuffer`] will return an empty iterator
287    /// ```
288    /// # use arrow_buffer::OffsetBuffer;
289    /// let offsets = OffsetBuffer::<i32>::new_empty();
290    /// assert_eq!(offsets.lengths().count(), 0);
291    /// ```
292    ///
293    /// This can be used to merge multiple [`OffsetBuffer`]s to one
294    /// ```
295    /// # use arrow_buffer::{OffsetBuffer, ScalarBuffer};
296    ///
297    /// let buffer1 = OffsetBuffer::<i32>::from_lengths([2, 6, 3, 7, 2]);
298    /// let buffer2 = OffsetBuffer::<i32>::from_lengths([1, 3, 5, 7, 9]);
299    ///
300    /// let merged = OffsetBuffer::<i32>::from_lengths(
301    ///     vec![buffer1, buffer2].iter().flat_map(|x| x.lengths())
302    /// );
303    ///
304    /// assert_eq!(merged.lengths().collect::<Vec<_>>(), &[2, 6, 3, 7, 2, 1, 3, 5, 7, 9]);
305    /// ```
306    pub fn lengths(&self) -> impl ExactSizeIterator<Item = usize> + '_ {
307        self.0.windows(2).map(|x| x[1].as_usize() - x[0].as_usize())
308    }
309
310    /// Free up unused memory.
311    pub fn shrink_to_fit(&mut self) {
312        self.0.shrink_to_fit();
313    }
314
315    /// Returns the inner [`ScalarBuffer`]
316    pub fn inner(&self) -> &ScalarBuffer<O> {
317        &self.0
318    }
319
320    /// Returns the inner [`ScalarBuffer`], consuming self
321    pub fn into_inner(self) -> ScalarBuffer<O> {
322        self.0
323    }
324
325    /// Claim memory used by this buffer in the provided memory pool.
326    #[cfg(feature = "pool")]
327    pub fn claim(&self, pool: &dyn crate::MemoryPool) {
328        self.0.claim(pool);
329    }
330
331    /// Returns a zero-copy slice of this buffer with length `len` and starting at `offset`
332    ///
333    /// # Panics
334    ///
335    /// Panics if `offset + len > self.len()`
336    pub fn slice(&self, offset: usize, len: usize) -> Self {
337        Self(self.0.slice(offset, len.saturating_add(1)))
338    }
339
340    /// Returns true if this [`OffsetBuffer`] is equal to `other`, using pointer comparisons
341    /// to determine buffer equality. This is cheaper than `PartialEq::eq` but may
342    /// return false when the arrays are logically equal
343    #[inline]
344    pub fn ptr_eq(&self, other: &Self) -> bool {
345        self.0.ptr_eq(&other.0)
346    }
347
348    /// Check if any null positions in the `null_buffer` correspond to
349    /// non-empty ranges in this [`OffsetBuffer`].
350    ///
351    /// In variable-length array types (e.g., `StringArray`, `ListArray`),
352    /// null entries may or may not have empty offset ranges. This method
353    /// detects cases where a null entry has a non-empty range
354    /// (i.e., `offsets[i] != offsets[i+1]`), which means the underlying
355    /// data buffer contains data behind nulls.
356    ///
357    /// This matters because unwrapping (flattening) a list array exposes
358    /// the child values, including those behind null entries. If null
359    /// entries point to non-empty ranges, the unwrapped values will
360    /// contain data that may not be meaningful to operate on and could
361    /// cause errors (e.g., division by zero in the child values).
362    ///
363    /// Returns `false` if `null_buffer` is `None` or contains no nulls.
364    ///
365    /// # Example
366    ///
367    /// ```
368    /// # use arrow_buffer::{OffsetBuffer, ScalarBuffer, NullBuffer};
369    /// // Offsets where null at index 1 has an empty range (3..3)
370    /// let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 3, 6]));
371    /// let nulls = NullBuffer::from(vec![true, false, true]);
372    /// assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
373    ///
374    /// // Offsets where null at index 1 has a non-empty range (3..7)
375    /// let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 7, 10]));
376    /// let nulls = NullBuffer::from(vec![true, false, true]);
377    /// assert!(offsets.has_non_empty_nulls(Some(&nulls)));
378    /// ```
379    ///
380    /// # Panics
381    ///
382    /// Panics if the length of the `null_buffer` does not equal `self.len() - 1`.
383    pub fn has_non_empty_nulls(&self, null_buffer: Option<&NullBuffer>) -> bool {
384        let Some(null_buffer) = null_buffer else {
385            return false;
386        };
387
388        assert_eq!(
389            self.len() - 1,
390            null_buffer.len(),
391            "The length of the offsets should be 1 more than the length of the null buffer"
392        );
393
394        if null_buffer.null_count() == 0 {
395            return false;
396        }
397
398        // Offsets always have at least 1 value
399        let initial_offset = self[0];
400        let last_offset = self[self.len() - 1];
401
402        // If all the values are null (offsets have 1 more value than the length of the array)
403        if null_buffer.null_count() == self.len() - 1 {
404            return last_offset != initial_offset;
405        }
406
407        let mut valid_slices_iter = null_buffer.valid_slices();
408
409        // This is safe as we validated that are at least 1 valid value in the array
410        let (start, end) = valid_slices_iter.next().unwrap();
411
412        // If the nulls before have length greater than 0
413        if self[start] != initial_offset {
414            return true;
415        }
416
417        // End is exclusive, so it already point to the last offset value
418        // This is valid as the length of the array is always 1 less than the length of the offsets
419        let mut end_offset_of_last_valid_value = self[end];
420
421        for (start, end) in valid_slices_iter {
422            // If there is a null value that point to a non-empty value than the start offset of the valid value
423            // will be different that the end offset of the last valid value
424            if self[start] != end_offset_of_last_valid_value {
425                return true;
426            }
427
428            // End is exclusive, so it already point to the last offset value
429            // This is valid as the length of the array is always 1 less than the length of the offsets
430            end_offset_of_last_valid_value = self[end];
431        }
432
433        end_offset_of_last_valid_value != last_offset
434    }
435
436    /// Subtract `rhs` from all offsets
437    /// This will try to reuse the existing allocation as much as possible
438    ///
439    /// # Panics
440    ///
441    /// Panics if `rhs` > the first offset or if `rhs` will lead to overflow (when `rhs` is negative)
442    ///
443    /// # Example
444    ///
445    /// ```
446    /// # use arrow_buffer::OffsetBuffer;
447    /// let offsets = OffsetBuffer::<i32>::from_lengths(vec![4, 1, 5, 6]);
448    /// assert_eq!(offsets.as_ref(), &[0, 4, 5, 10, 16]);
449    ///
450    /// let sliced_offsets = offsets.slice(1, 2);
451    /// assert_eq!(sliced_offsets.as_ref(), &[4, 5, 10]);
452    ///
453    /// let shifted_offsets = sliced_offsets.subtract(4);
454    /// assert_eq!(shifted_offsets.as_ref(), &[0, 1, 6]);
455    /// ```
456    ///
457    pub fn subtract(self, rhs: O) -> Self
458    where
459        O: std::ops::Sub<Output = O> + std::cmp::PartialOrd + num_traits::CheckedSub,
460    {
461        if rhs == O::usize_as(0) {
462            return self;
463        }
464
465        let len = self.len();
466
467        // Offset buffer is guaranteed to be non-empty
468        assert!(
469            self[0] >= rhs,
470            "shifted offsets will become negative which is not allowed"
471        );
472
473        // If negative, make sure that this will not create an overflow
474        if rhs < O::usize_as(0) {
475            self[len - 1].checked_sub(&rhs).expect("must not overflow");
476        }
477
478        // try and reuse buffer
479        let shifted_offsets: Vec<O> = match self.into_inner().into_inner().into_vec() {
480            // If we can reuse the buffer, update in place
481            Ok(mut v) => {
482                for offset in &mut v {
483                    *offset = *offset - rhs;
484                }
485                v
486            }
487            // otherwise, buffer is shared so we need a copy
488            Err(buffer) => {
489                let offsets = ScalarBuffer::<O>::from(buffer);
490                offsets.iter().map(|offset| *offset - rhs).collect()
491            }
492        };
493        let shifted_buffer = ScalarBuffer::from(shifted_offsets);
494        // Safety: offsets are valid as they are coming from a valid
495        // offset buffer and we checked overflow above, and we
496        // subtracted the same value from all offsets, thus keeping the
497        // same properties as the input buffer
498        unsafe { Self::new_unchecked(shifted_buffer) }
499    }
500}
501
502impl<T: ArrowNativeType> Deref for OffsetBuffer<T> {
503    type Target = [T];
504
505    #[inline]
506    fn deref(&self) -> &Self::Target {
507        &self.0
508    }
509}
510
511impl<T: ArrowNativeType> AsRef<[T]> for OffsetBuffer<T> {
512    #[inline]
513    fn as_ref(&self) -> &[T] {
514        self
515    }
516}
517
518impl<O: ArrowNativeType> From<OffsetBufferBuilder<O>> for OffsetBuffer<O> {
519    fn from(value: OffsetBufferBuilder<O>) -> Self {
520        value.finish()
521    }
522}
523
524impl<O: ArrowNativeType> Default for OffsetBuffer<O> {
525    fn default() -> Self {
526        Self::new_empty()
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    #[test]
535    #[should_panic(expected = "offsets cannot be empty")]
536    fn empty_offsets() {
537        OffsetBuffer::new(Vec::<i32>::new().into());
538    }
539
540    #[test]
541    #[should_panic(expected = "offsets must be greater than 0")]
542    fn negative_offsets() {
543        OffsetBuffer::new(vec![-1, 0, 1].into());
544    }
545
546    #[test]
547    fn try_from_lengths_overflow() {
548        // Fits in an i64, but not in an i32:
549        let lengths = [u32::MAX as usize, 1];
550
551        let err = OffsetBuffer::<i32>::try_from_lengths(lengths).unwrap_err();
552        assert_eq!(
553            err.to_string(),
554            "offset overflow: 4294967296 does not fit in i32"
555        );
556        assert!(OffsetBuffer::<i64>::try_from_lengths(lengths).is_ok());
557
558        let err = OffsetBuffer::<i32>::try_from_lengths([usize::MAX, 1]).unwrap_err();
559        assert_eq!(
560            err.to_string(),
561            "total length overflow: does not fit in usize"
562        );
563
564        // The panicking version agrees:
565        assert!(std::panic::catch_unwind(|| OffsetBuffer::<i32>::from_lengths(lengths)).is_err());
566    }
567
568    #[test]
569    fn try_from_repeated_length_overflow() {
570        assert_eq!(
571            OffsetBuffer::<i32>::try_from_repeated_length(2, usize::MAX)
572                .unwrap_err()
573                .to_string(),
574            "total length overflow: does not fit in usize"
575        );
576        assert_eq!(
577            OffsetBuffer::<i32>::try_from_repeated_length(u32::MAX as usize, 2)
578                .unwrap_err()
579                .to_string(),
580            "offset overflow: 8589934590 does not fit in i32"
581        );
582        assert_eq!(
583            OffsetBuffer::<i32>::try_from_repeated_length(4, 3)
584                .unwrap()
585                .as_ref(),
586            &[0, 4, 8, 12]
587        );
588    }
589
590    #[test]
591    fn try_new_zeroed_overflow() {
592        assert_eq!(
593            OffsetBuffer::<i64>::try_new_zeroed(usize::MAX)
594                .unwrap_err()
595                .to_string(),
596            "buffer length overflow: does not fit in usize"
597        );
598        let max_layout_len = isize::MAX as usize / std::mem::size_of::<i64>();
599        assert!(OffsetBuffer::<i64>::try_new_zeroed(max_layout_len).is_err());
600        assert_eq!(
601            OffsetBuffer::<i32>::try_new_zeroed(3).unwrap().as_ref(),
602            &[0; 4]
603        );
604    }
605
606    #[test]
607    fn offsets() {
608        OffsetBuffer::new(vec![0, 1, 2, 3].into());
609
610        let offsets = OffsetBuffer::<i32>::new_zeroed(3);
611        assert_eq!(offsets.as_ref(), &[0; 4]);
612
613        let offsets = OffsetBuffer::<i32>::new_zeroed(0);
614        assert_eq!(offsets.as_ref(), &[0; 1]);
615    }
616
617    #[test]
618    #[should_panic(expected = "overflow")]
619    fn offsets_new_zeroed_overflow() {
620        OffsetBuffer::<i32>::new_zeroed(usize::MAX);
621    }
622
623    #[test]
624    #[should_panic(expected = "offsets must be monotonically increasing")]
625    fn non_monotonic_offsets() {
626        OffsetBuffer::new(vec![1, 2, 0].into());
627    }
628
629    #[test]
630    #[should_panic(expected = "offsets must be monotonically increasing")]
631    #[cfg(feature = "force_validate")]
632    fn non_monotonic_offsets_unchecked_force_validate() {
633        unsafe { OffsetBuffer::<i32>::new_unchecked(vec![0, 2, 1, 3].into()) };
634    }
635
636    #[test]
637    fn from_lengths() {
638        let buffer = OffsetBuffer::<i32>::from_lengths([2, 6, 3, 7, 2]);
639        assert_eq!(buffer.as_ref(), &[0, 2, 8, 11, 18, 20]);
640
641        let half_max = i32::MAX / 2;
642        let buffer = OffsetBuffer::<i32>::from_lengths([half_max as usize, half_max as usize]);
643        assert_eq!(buffer.as_ref(), &[0, half_max, half_max * 2]);
644    }
645
646    #[test]
647    #[should_panic(expected = "offset overflow")]
648    fn from_lengths_offset_overflow() {
649        OffsetBuffer::<i32>::from_lengths([i32::MAX as usize, 1]);
650    }
651
652    #[test]
653    #[should_panic(expected = "total length overflow: does not fit in usize")]
654    fn from_lengths_usize_overflow() {
655        OffsetBuffer::<i32>::from_lengths([usize::MAX, 1]);
656    }
657
658    #[test]
659    #[should_panic(expected = "offset overflow")]
660    fn from_repeated_lengths_offset_length_overflow() {
661        OffsetBuffer::<i32>::from_repeated_length(i32::MAX as usize / 4, 5);
662    }
663
664    #[test]
665    #[should_panic(expected = "offset overflow")]
666    fn from_repeated_lengths_offset_repeat_overflow() {
667        OffsetBuffer::<i32>::from_repeated_length(1, i32::MAX as usize + 1);
668    }
669
670    #[test]
671    #[should_panic(expected = "offset overflow")]
672    fn from_repeated_lengths_usize_length_overflow() {
673        OffsetBuffer::<i32>::from_repeated_length(usize::MAX, 1);
674    }
675
676    #[test]
677    #[should_panic(expected = "total length overflow: does not fit in usize")]
678    fn from_repeated_lengths_usize_length_usize_overflow() {
679        OffsetBuffer::<i32>::from_repeated_length(usize::MAX, 2);
680    }
681
682    #[test]
683    #[should_panic(expected = "offset overflow")]
684    fn from_repeated_lengths_usize_repeat_overflow() {
685        OffsetBuffer::<i32>::from_repeated_length(1, usize::MAX);
686    }
687
688    #[test]
689    fn get_lengths() {
690        let offsets = OffsetBuffer::<i32>::new(ScalarBuffer::<i32>::from(vec![0, 1, 4, 9]));
691        assert_eq!(offsets.lengths().collect::<Vec<usize>>(), vec![1, 3, 5]);
692    }
693
694    #[test]
695    fn get_lengths_should_be_with_fixed_size() {
696        let offsets = OffsetBuffer::<i32>::new(ScalarBuffer::<i32>::from(vec![0, 1, 4, 9]));
697        let iter = offsets.lengths();
698        assert_eq!(iter.size_hint(), (3, Some(3)));
699        assert_eq!(iter.len(), 3);
700    }
701
702    #[test]
703    fn get_lengths_from_empty_offset_buffer_should_be_empty_iterator() {
704        let offsets = OffsetBuffer::<i32>::new_empty();
705        assert_eq!(offsets.lengths().collect::<Vec<usize>>(), vec![]);
706    }
707
708    #[test]
709    fn impl_eq() {
710        fn are_equal<T: Eq>(a: &T, b: &T) -> bool {
711            a.eq(b)
712        }
713
714        assert!(
715            are_equal(
716                &OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 1, 4, 9])),
717                &OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 1, 4, 9]))
718            ),
719            "OffsetBuffer should implement Eq."
720        );
721    }
722
723    #[test]
724    fn impl_default() {
725        let default = OffsetBuffer::<i32>::default();
726        assert_eq!(default.as_ref(), &[0]);
727    }
728
729    #[test]
730    fn try_new_empty() {
731        let buffer = OffsetBuffer::<i32>::try_new_empty().unwrap();
732        assert_eq!(buffer.as_ref(), &[0]);
733    }
734
735    #[test]
736    fn from_repeated_length_basic() {
737        // Basic case with length 4, repeated 3 times
738        let buffer = OffsetBuffer::<i32>::from_repeated_length(4, 3);
739        assert_eq!(buffer.as_ref(), &[0, 4, 8, 12]);
740
741        // Verify the lengths are correct
742        let lengths: Vec<usize> = buffer.lengths().collect();
743        assert_eq!(lengths, vec![4, 4, 4]);
744    }
745
746    #[test]
747    fn from_repeated_length_single_repeat() {
748        // Length 5, repeated once
749        let buffer = OffsetBuffer::<i32>::from_repeated_length(5, 1);
750        assert_eq!(buffer.as_ref(), &[0, 5]);
751
752        let lengths: Vec<usize> = buffer.lengths().collect();
753        assert_eq!(lengths, vec![5]);
754    }
755
756    #[test]
757    fn from_repeated_length_zero_repeats() {
758        let buffer = OffsetBuffer::<i32>::from_repeated_length(10, 0);
759        assert_eq!(buffer, OffsetBuffer::<i32>::new_empty());
760    }
761
762    #[test]
763    fn from_repeated_length_zero_length() {
764        // Zero length, repeated 5 times (all zeros)
765        let buffer = OffsetBuffer::<i32>::from_repeated_length(0, 5);
766        assert_eq!(buffer.as_ref(), &[0, 0, 0, 0, 0, 0]);
767
768        // All lengths should be 0
769        let lengths: Vec<usize> = buffer.lengths().collect();
770        assert_eq!(lengths, vec![0, 0, 0, 0, 0]);
771    }
772
773    #[test]
774    fn from_repeated_length_large_values() {
775        // Test with larger values that don't overflow
776        let buffer = OffsetBuffer::<i32>::from_repeated_length(1000, 100);
777        assert_eq!(buffer[0], 0);
778
779        // Verify all lengths are 1000
780        let lengths: Vec<usize> = buffer.lengths().collect();
781        assert_eq!(lengths.len(), 100);
782        assert!(lengths.iter().all(|&len| len == 1000));
783    }
784
785    #[test]
786    fn from_repeated_length_unit_length() {
787        // Length 1, repeated multiple times
788        let buffer = OffsetBuffer::<i32>::from_repeated_length(1, 10);
789        assert_eq!(buffer.as_ref(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
790
791        let lengths: Vec<usize> = buffer.lengths().collect();
792        assert_eq!(lengths, vec![1; 10]);
793    }
794
795    #[test]
796    fn from_repeated_length_max_safe_values() {
797        // Test with maximum safe values for i32
798        // i32::MAX / 3 ensures we don't overflow when repeated twice
799        let third_max = (i32::MAX / 3) as usize;
800        let buffer = OffsetBuffer::<i32>::from_repeated_length(third_max, 2);
801        assert_eq!(
802            buffer.as_ref(),
803            &[0, third_max as i32, (third_max * 2) as i32]
804        );
805    }
806
807    // ---------------------------------------------------------------
808    // Tests for has_non_empty_nulls
809    // ---------------------------------------------------------------
810
811    #[test]
812    fn has_non_empty_nulls_none_null_buffer() {
813        // No null buffer at all -> false
814        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 5, 8]));
815        assert!(!offsets.has_non_empty_nulls(None));
816    }
817
818    #[test]
819    fn has_non_empty_nulls_all_valid() {
820        // Null buffer with zero nulls -> false (early return via filter)
821        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 5, 8]));
822        let nulls = NullBuffer::new_valid(3);
823        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
824    }
825
826    #[test]
827    fn has_non_empty_nulls_all_null_empty_offsets() {
828        // All values are null and all offsets are equal (no data behind nulls) -> false
829        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 0, 0]));
830        let nulls = NullBuffer::new_null(3);
831        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
832    }
833
834    #[test]
835    fn has_non_empty_nulls_all_null_non_empty_offsets() {
836        // All values are null but offsets span data -> true
837        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 2, 5, 7]));
838        let nulls = NullBuffer::new_null(3);
839        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
840    }
841
842    #[test]
843    fn has_non_empty_nulls_all_null_nonzero_but_equal_offsets() {
844        // All null, offsets start at non-zero but are all equal -> false
845        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![5, 5, 5]));
846        let nulls = NullBuffer::new_null(2);
847        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
848    }
849
850    #[test]
851    fn has_non_empty_nulls_leading_nulls_with_data() {
852        // Nulls at the beginning that point to non-empty ranges -> true
853        // offsets: [0, 3, 5, 8]  nulls: [false, true, true]
854        // Index 0 is null with range 0..3 (non-empty)
855        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 5, 8]));
856        let nulls = NullBuffer::from(vec![false, true, true]);
857        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
858    }
859
860    #[test]
861    fn has_non_empty_nulls_leading_nulls_without_data() {
862        // Nulls at the beginning with empty ranges -> continue checking
863        // offsets: [0, 0, 3, 6]  nulls: [false, true, true]
864        // Index 0 is null with range 0..0 (empty)
865        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 3, 6]));
866        let nulls = NullBuffer::from(vec![false, true, true]);
867        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
868    }
869
870    #[test]
871    fn has_non_empty_nulls_only_trailing_null_has_data() {
872        // Only the trailing null region has data, everything else is clean
873        // offsets: [0, 0, 3, 6, 8]  nulls: [false, true, true, false]
874        // Null at 0 (0..0 empty), valid at 1,2 (0..3, 3..6), null at 3 (6..8 non-empty)
875        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 3, 6, 8]));
876        let nulls = NullBuffer::from(vec![false, true, true, false]);
877        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
878    }
879
880    #[test]
881    fn has_non_empty_nulls_trailing_nulls_without_data() {
882        // Nulls at the end with empty ranges -> false
883        // offsets: [0, 3, 6, 6]  nulls: [true, true, false]
884        // Index 2 is null with range 6..6 (empty)
885        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 6, 6]));
886        let nulls = NullBuffer::from(vec![true, true, false]);
887        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
888    }
889
890    #[test]
891    fn has_non_empty_nulls_middle_nulls_with_data() {
892        // Null in the middle with non-empty range -> true
893        // offsets: [0, 3, 7, 10]  nulls: [true, false, true]
894        // Index 1 is null with range 3..7 (non-empty)
895        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 7, 10]));
896        let nulls = NullBuffer::from(vec![true, false, true]);
897        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
898    }
899
900    #[test]
901    fn has_non_empty_nulls_middle_nulls_without_data() {
902        // Null in the middle with empty range -> false
903        // offsets: [0, 3, 3, 6]  nulls: [true, false, true]
904        // Index 1 is null with range 3..3 (empty)
905        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 3, 6]));
906        let nulls = NullBuffer::from(vec![true, false, true]);
907        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
908    }
909
910    #[test]
911    fn has_non_empty_nulls_alternating_null_valid_all_empty() {
912        // Alternating null/valid where every null has an empty range -> false.
913
914        // Ends with null
915        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 3, 3, 6, 6]));
916        let nulls = NullBuffer::from(vec![false, true, false, true, false]);
917        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
918
919        // Ends with valid
920        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 3, 3, 6, 6, 9]));
921        let nulls = NullBuffer::from(vec![false, true, false, true, false, true]);
922        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
923    }
924
925    #[test]
926    fn has_non_empty_nulls_multiple_null_regions_second_has_data() {
927        // Two null regions: first empty, second non-empty -> true
928        // offsets: [0, 0, 3, 5, 6]  nulls: [false, true, false, true]
929        // Null at index 0 (0..0 empty), null at index 2 (3..5 non-empty)
930        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 3, 5, 6]));
931        let nulls = NullBuffer::from(vec![false, true, false, true]);
932        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
933    }
934
935    #[test]
936    fn has_non_empty_nulls_multiple_null_regions_later_gap_has_data() {
937        // Three null regions: first two empty, third non-empty -> true
938        // offsets: [0, 0, 3, 3, 6, 8, 10]  nulls: [false, true, false, true, false, true]
939        // valid_slices: (1,2), (3,4), (5,6)
940        // first slice: start=1, self[1]=0 == initial_offset=0 OK, end_offset=self[2]=3
941        // loop iter 1: start=3, self[3]=3 == 3 OK (first gap empty), end_offset=self[4]=6
942        // loop iter 2: start=5, self[5]=8 != 6 -> true (second gap has data)
943        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0, 3, 3, 6, 8, 10]));
944        let nulls = NullBuffer::from(vec![false, true, false, true, false, true]);
945        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
946    }
947
948    #[test]
949    fn has_non_empty_nulls_single_element_null_empty() {
950        // Single element, null with empty range -> false
951        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 0]));
952        let nulls = NullBuffer::new_null(1);
953        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
954    }
955
956    #[test]
957    fn has_non_empty_nulls_single_element_null_non_empty() {
958        // Single element, null with non-empty range -> true
959        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 5]));
960        let nulls = NullBuffer::new_null(1);
961        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
962    }
963
964    #[test]
965    fn has_non_empty_nulls_single_element_valid() {
966        // Single element, valid -> false (no nulls at all)
967        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 5]));
968        let nulls = NullBuffer::new_valid(1);
969        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
970    }
971
972    #[test]
973    fn has_non_empty_nulls_consecutive_nulls_between_valid_slices() {
974        // Multiple consecutive nulls between valid regions
975        // offsets: [0, 2, 2, 2, 5, 8]  nulls: [true, false, false, true, true]
976        // Valid: [0], nulls: [1,2], valid: [3,4]
977        // Null region [1,2] has offsets 2..2..2 (empty) -> false
978        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 2, 2, 2, 5, 8]));
979        let nulls = NullBuffer::from(vec![true, false, false, true, true]);
980        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
981    }
982
983    #[test]
984    fn has_non_empty_nulls_consecutive_nulls_between_valid_slices_with_data() {
985        // Multiple consecutive nulls between valid regions, nulls have data
986        // offsets: [0, 2, 3, 4, 5, 8]  nulls: [true, false, false, true, true]
987        // valid_slices: (0,1), (3,5)
988        // first slice: start=0, end=1 -> self[0]=0 == initial_offset=0 OK
989        //   end_offset_of_last_valid_value = self[1] = 2
990        // second slice: start=3, end=5 -> self[3]=4 != 2 -> true
991        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 2, 3, 4, 5, 8]));
992        let nulls = NullBuffer::from(vec![true, false, false, true, true]);
993        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
994    }
995
996    #[test]
997    fn has_non_empty_nulls_nonzero_initial_offset_all_null_equal() {
998        // Non-zero starting offset, all null, all offsets equal -> false
999        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![10, 10, 10]));
1000        let nulls = NullBuffer::new_null(2);
1001        assert!(!offsets.has_non_empty_nulls(Some(&nulls)));
1002    }
1003
1004    #[test]
1005    fn has_non_empty_nulls_nonzero_initial_offset_with_data() {
1006        // Non-zero starting offset, null has data
1007        // offsets: [10, 15, 20]  nulls: [false, true]
1008        // Null at index 0 with range 10..15 (non-empty) -> true
1009        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![10, 15, 20]));
1010        let nulls = NullBuffer::from(vec![false, true]);
1011        assert!(offsets.has_non_empty_nulls(Some(&nulls)));
1012    }
1013
1014    #[test]
1015    fn has_non_empty_nulls_sliced_no_nulls_in_null_region() {
1016        // Original: [0, 3, 3, 6, 6, 9]  -> slice(1, 3) -> [3, 3, 6, 6]
1017        // initial_offset=3, last_offset=6
1018        // nulls: [false, true, false]  (null at index 0 has range 3..3 = empty)
1019        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 3, 6, 6, 9]));
1020        let sliced = offsets.slice(1, 3);
1021        let nulls = NullBuffer::from(vec![false, true, false]);
1022        assert!(!sliced.has_non_empty_nulls(Some(&nulls)));
1023    }
1024
1025    #[test]
1026    fn has_non_empty_nulls_sliced_null_has_data() {
1027        // Original: [0, 3, 7, 10, 15]  -> slice(1, 2) -> [3, 7, 10]
1028        // initial_offset=3, last_offset=10
1029        // nulls: [false, true]  (null at index 0 has range 3..7 = non-empty)
1030        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 7, 10, 15]));
1031        let sliced = offsets.slice(1, 2);
1032        let nulls = NullBuffer::from(vec![false, true]);
1033        assert!(sliced.has_non_empty_nulls(Some(&nulls)));
1034    }
1035
1036    #[test]
1037    #[should_panic(
1038        expected = "The length of the offsets should be 1 more than the length of the null buffer"
1039    )]
1040    fn has_non_empty_nulls_all_valid_mismatched_lengths_too_short() {
1041        // All-valid null buffer with wrong length should still panic
1042        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 5, 8]));
1043        let nulls = NullBuffer::new_valid(2); // expects 3
1044        offsets.has_non_empty_nulls(Some(&nulls));
1045    }
1046
1047    #[test]
1048    #[should_panic(
1049        expected = "The length of the offsets should be 1 more than the length of the null buffer"
1050    )]
1051    fn has_non_empty_nulls_all_valid_mismatched_lengths_too_long() {
1052        // All-valid null buffer with wrong length should still panic
1053        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 5, 8]));
1054        let nulls = NullBuffer::new_valid(5); // expects 3
1055        offsets.has_non_empty_nulls(Some(&nulls));
1056    }
1057
1058    #[test]
1059    #[should_panic(expected = "shifted offsets will become negative which is not allowed")]
1060    fn should_panic_for_subtract_by_value_that_will_cause_offsets_to_be_less_than_zero() {
1061        // self[0] = 0, rhs = 1 -> 0 >= 1 is false -> assert fires
1062        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 6]));
1063        offsets.subtract(1);
1064    }
1065
1066    #[test]
1067    fn subtract_by_value_that_will_cause_offsets_to_be_less_than_zero_for_outside_the_slice() {
1068        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 1, 4, 7]));
1069        let sliced = offsets.slice(1, 2); // [1, 4, 7]
1070        drop(offsets);
1071        assert_eq!(sliced.as_ref(), &[1, 4, 7]);
1072
1073        let result = sliced.subtract(1);
1074        assert_eq!(result.as_ref(), &[0, 3, 6]);
1075        assert_eq!(result.len(), 3);
1076    }
1077
1078    #[test]
1079    #[should_panic(expected = "must not overflow")]
1080    fn should_panic_subtract_by_value_that_will_cause_offsets_to_overflow() {
1081        // rhs = -1 (negative). self[0] = 0 >= -1 passes.
1082        // last offset i32::MAX - (-1) = i32::MAX + 1 -> checked_sub returns None -> expect fires
1083        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 5, i32::MAX]));
1084        offsets.subtract(-1);
1085    }
1086
1087    #[test]
1088    fn subtract_by_value_that_will_cause_offsets_to_overflow_outside_the_slice() {
1089        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 6, i32::MAX]));
1090        let sliced = offsets.slice(0, 2); // [0, 3, 6]
1091        assert_eq!(sliced.as_ref(), &[0, 3, 6]);
1092
1093        let result = sliced.subtract(-1);
1094        assert_eq!(result.as_ref(), &[1, 4, 7]);
1095        assert_eq!(result.len(), 3);
1096    }
1097
1098    #[test]
1099    fn when_shift_is_0_subtract_should_reuse_the_buffer_even_when_it_is_shared() {
1100        // subtract(0) hits the early `return self` before any into_mutable,
1101        // so the returned buffer is the exact same allocation even while shared.
1102        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 6]));
1103        let shared = offsets.clone(); // refcount now 2 -> shared
1104        let result = offsets.subtract(0);
1105        assert!(
1106            result.ptr_eq(&shared),
1107            "subtract(0) must return the same underlying buffer, even when shared"
1108        );
1109    }
1110
1111    #[test]
1112    fn should_reuse_the_underline_data_when_the_buffer_is_not_shared() {
1113        // Unique ownership, offset 0 -> into_mutable succeeds -> mutate in place,
1114        // and MutableBuffer -> Buffer keeps the same allocation.
1115        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![2, 5, 8]));
1116        let ptr_before = offsets.as_ptr();
1117        let result = offsets.subtract(2);
1118        assert_eq!(
1119            ptr_before,
1120            result.as_ptr(),
1121            "a non-shared buffer should be mutated in place, reusing the allocation"
1122        );
1123        assert_eq!(result.as_ref(), &[0, 3, 6]);
1124    }
1125
1126    #[test]
1127    fn should_create_a_new_buffer_when_the_buffer_is_shared() {
1128        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![2, 5, 8]));
1129        let shared = offsets.clone();
1130        let ptr_before = offsets.as_ptr();
1131        let result = offsets.subtract(2);
1132        assert_ne!(
1133            ptr_before,
1134            result.as_ptr(),
1135            "a shared buffer must not be mutated in place; a new allocation is created"
1136        );
1137        assert_eq!(result.as_ref(), &[0, 3, 6]);
1138        // The shared view is untouched.
1139        assert_eq!(shared.as_ref(), &[2, 5, 8]);
1140    }
1141
1142    #[test]
1143    fn when_shift_is_negative_it_should_shift_offsets_in_the_right_direction() {
1144        // rhs = -2 -> offset - (-2) = offset + 2, so all offsets move up.
1145        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 6]));
1146        let result = offsets.subtract(-2);
1147        assert_eq!(result.as_ref(), &[2, 5, 8]);
1148    }
1149
1150    // Replace this test with test that assert a reuse after PR #10118 is merged
1151    #[test]
1152    fn for_sliced_unshared_buffer_shift_should_not_reuse_buffer() {
1153        // Underlying [0, 3, 6, 9, 12]; slice -> view [3, 6, 9].
1154        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![1, 3, 6, 9, 12]));
1155        let sliced = offsets.slice(1, 2); // [3, 6, 9]
1156        drop(offsets); // uniquely owned
1157        assert_eq!(sliced.as_ref(), &[3, 6, 9]);
1158
1159        let ptr_before = sliced.as_ptr();
1160        let result = sliced.subtract(1);
1161
1162        assert_ne!(
1163            ptr_before,
1164            result.as_ptr(),
1165            "should not be reused until #10118 is merged"
1166        );
1167
1168        assert_eq!(result.as_ref(), &[2, 5, 8]);
1169    }
1170
1171    #[test]
1172    fn for_sliced_but_start_at_0_unshared_buffer_shift_should_reuse_buffer() {
1173        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![1, 3, 6, 9, 12]));
1174        let sliced = offsets.slice(0, 2);
1175        drop(offsets); // uniquely owned
1176        assert_eq!(sliced.as_ref(), &[1, 3, 6]);
1177
1178        let ptr_before = sliced.as_ptr();
1179        let result = sliced.subtract(1);
1180
1181        assert_eq!(ptr_before, result.as_ptr(), "should be reused");
1182
1183        assert_eq!(result.as_ref(), &[0, 2, 5]);
1184    }
1185
1186    #[test]
1187    fn for_sliced_shared_buffer_shifted_buffer_should_only_include_the_sliced_data() {
1188        // Underlying: [0, 3, 6, 9, 12]; slice(1, 2) -> view [3, 6, 9].
1189        // `offsets` stays alive, so the sliced buffer is shared -> Err branch.
1190        // The Err branch copies `len` (= 3) elements from the *sliced* typed_data,
1191        // so the result contains only the sliced data, shifted.
1192        let offsets = OffsetBuffer::new(ScalarBuffer::<i32>::from(vec![0, 3, 6, 9, 12]));
1193        let sliced = offsets.slice(1, 2);
1194        assert_eq!(sliced.as_ref(), &[3, 6, 9]);
1195
1196        let result = sliced.subtract(3);
1197
1198        assert_eq!(
1199            result.as_ref(),
1200            &[0, 3, 6],
1201            "shifted result should contain only the sliced data"
1202        );
1203        assert_eq!(result.len(), 3);
1204
1205        // Assert that the underlying buffer of the result is not sliced to make sure it does not include the data outside the slice range from the original buffer
1206        let underlying_buffer = result.inner().inner();
1207        assert_eq!(underlying_buffer.ptr_offset(), 0);
1208        assert_eq!(underlying_buffer.len(), 3 * std::mem::size_of::<i32>());
1209    }
1210}