arrow_array/array/
byte_view_array.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::array::print_long_array;
19use crate::builder::{ArrayBuilder, GenericByteViewBuilder};
20use crate::iterator::ArrayIter;
21use crate::types::bytes::ByteArrayNativeType;
22use crate::types::{BinaryViewType, ByteViewType, StringViewType};
23use crate::{Array, ArrayAccessor, ArrayRef, GenericByteArray, OffsetSizeTrait, Scalar};
24use arrow_buffer::{ArrowNativeType, Buffer, NullBuffer, ScalarBuffer};
25use arrow_data::{ArrayData, ArrayDataBuilder, ByteView, MAX_INLINE_VIEW_LEN};
26use arrow_schema::{ArrowError, DataType};
27use core::str;
28use num::ToPrimitive;
29use std::any::Any;
30use std::cmp::Ordering;
31use std::fmt::Debug;
32use std::marker::PhantomData;
33use std::sync::Arc;
34
35use super::ByteArrayType;
36
37/// [Variable-size Binary View Layout]: An array of variable length bytes views.
38///
39/// This array type is used to store variable length byte data (e.g. Strings, Binary)
40/// and has efficient operations such as `take`, `filter`, and comparison.
41///
42/// [Variable-size Binary View Layout]: https://arrow.apache.org/docs/format/Columnar.html#variable-size-binary-view-layout
43///
44/// This is different from [`GenericByteArray`], which also stores variable
45/// length byte data, as it represents strings with an offset and length. `take`
46/// and `filter` like operations are implemented by manipulating the "views"
47/// (`u128`) without modifying the bytes. Each view also stores an inlined
48/// prefix which speed up comparisons.
49///
50/// # See Also
51///
52/// * [`StringViewArray`] for storing utf8 encoded string data
53/// * [`BinaryViewArray`] for storing bytes
54/// * [`ByteView`] to interpret `u128`s layout of the views.
55///
56/// [`ByteView`]: arrow_data::ByteView
57///
58/// # Layout: "views" and buffers
59///
60/// A `GenericByteViewArray` stores variable length byte strings. An array of
61/// `N` elements is stored as `N` fixed length "views" and a variable number
62/// of variable length "buffers".
63///
64/// Each view is a `u128` value whose layout is different depending on the
65/// length of the string stored at that location:
66///
67/// ```text
68///                         ┌──────┬────────────────────────┐
69///                         │length│      string value      │
70///    Strings (len <= 12)  │      │    (padded with 0)     │
71///                         └──────┴────────────────────────┘
72///                          0    31                      127
73///
74///                         ┌───────┬───────┬───────┬───────┐
75///                         │length │prefix │  buf  │offset │
76///    Strings (len > 12)   │       │       │ index │       │
77///                         └───────┴───────┴───────┴───────┘
78///                          0    31       63      95    127
79/// ```
80///
81/// * Strings with length <= 12 ([`MAX_INLINE_VIEW_LEN`]) are stored directly in
82///   the view. See [`Self::inline_value`] to access the inlined prefix from a
83///   short view.
84///
85/// * Strings with length > 12: The first four bytes are stored inline in the
86///   view and the entire string is stored in one of the buffers. See [`ByteView`]
87///   to access the fields of the these views.
88///
89/// As with other arrays, the optimized kernels in [`arrow_compute`] are likely
90/// the easiest and fastest way to work with this data. However, it is possible
91/// to access the views and buffers directly for more control.
92///
93/// For example
94///
95/// ```rust
96/// # use arrow_array::StringViewArray;
97/// # use arrow_array::Array;
98/// use arrow_data::ByteView;
99/// let array = StringViewArray::from(vec![
100///   "hello",
101///   "this string is longer than 12 bytes",
102///   "this string is also longer than 12 bytes"
103/// ]);
104///
105/// // ** Examine the first view (short string) **
106/// assert!(array.is_valid(0)); // Check for nulls
107/// let short_view: u128 = array.views()[0]; // "hello"
108/// // get length of the string
109/// let len = short_view as u32;
110/// assert_eq!(len, 5); // strings less than 12 bytes are stored in the view
111/// // SAFETY: `view` is a valid view
112/// let value = unsafe {
113///   StringViewArray::inline_value(&short_view, len as usize)
114/// };
115/// assert_eq!(value, b"hello");
116///
117/// // ** Examine the third view (long string) **
118/// assert!(array.is_valid(12)); // Check for nulls
119/// let long_view: u128 = array.views()[2]; // "this string is also longer than 12 bytes"
120/// let len = long_view as u32;
121/// assert_eq!(len, 40); // strings longer than 12 bytes are stored in the buffer
122/// let view = ByteView::from(long_view); // use ByteView to access the fields
123/// assert_eq!(view.length, 40);
124/// assert_eq!(view.buffer_index, 0);
125/// assert_eq!(view.offset, 35); // data starts after the first long string
126/// // Views for long strings store a 4 byte prefix
127/// let prefix = view.prefix.to_le_bytes();
128/// assert_eq!(&prefix, b"this");
129/// let value = array.value(2); // get the string value (see `value` implementation for how to access the bytes directly)
130/// assert_eq!(value, "this string is also longer than 12 bytes");
131/// ```
132///
133/// [`MAX_INLINE_VIEW_LEN`]: arrow_data::MAX_INLINE_VIEW_LEN
134/// [`arrow_compute`]: https://docs.rs/arrow/latest/arrow/compute/index.html
135///
136/// Unlike [`GenericByteArray`], there are no constraints on the offsets other
137/// than they must point into a valid buffer. However, they can be out of order,
138/// non continuous and overlapping.
139///
140/// For example, in the following diagram, the strings "FishWasInTownToday" and
141/// "CrumpleFacedFish" are both longer than 12 bytes and thus are stored in a
142/// separate buffer while the string "LavaMonster" is stored inlined in the
143/// view. In this case, the same bytes for "Fish" are used to store both strings.
144///
145/// [`ByteView`]: arrow_data::ByteView
146///
147/// ```text
148///                                                                            ┌───┐
149///                         ┌──────┬──────┬──────┬──────┐               offset │...│
150/// "FishWasInTownTodayYay" │  21  │ Fish │  0   │ 115  │─ ─              103  │Mr.│
151///                         └──────┴──────┴──────┴──────┘   │      ┌ ─ ─ ─ ─ ▶ │Cru│
152///                         ┌──────┬──────┬──────┬──────┐                      │mpl│
153/// "CrumpleFacedFish"      │  16  │ Crum │  0   │ 103  │─ ─│─ ─ ─ ┘           │eFa│
154///                         └──────┴──────┴──────┴──────┘                      │ced│
155///                         ┌──────┬────────────────────┐   └ ─ ─ ─ ─ ─ ─ ─ ─ ▶│Fis│
156/// "LavaMonster"           │  11  │   LavaMonster      │                      │hWa│
157///                         └──────┴────────────────────┘               offset │sIn│
158///                                                                       115  │Tow│
159///                                                                            │nTo│
160///                                                                            │day│
161///                                  u128 "views"                              │Yay│
162///                                                                   buffer 0 │...│
163///                                                                            └───┘
164/// ```
165pub struct GenericByteViewArray<T: ByteViewType + ?Sized> {
166    data_type: DataType,
167    views: ScalarBuffer<u128>,
168    buffers: Vec<Buffer>,
169    phantom: PhantomData<T>,
170    nulls: Option<NullBuffer>,
171}
172
173impl<T: ByteViewType + ?Sized> Clone for GenericByteViewArray<T> {
174    fn clone(&self) -> Self {
175        Self {
176            data_type: T::DATA_TYPE,
177            views: self.views.clone(),
178            buffers: self.buffers.clone(),
179            nulls: self.nulls.clone(),
180            phantom: Default::default(),
181        }
182    }
183}
184
185impl<T: ByteViewType + ?Sized> GenericByteViewArray<T> {
186    /// Create a new [`GenericByteViewArray`] from the provided parts, panicking on failure
187    ///
188    /// # Panics
189    ///
190    /// Panics if [`GenericByteViewArray::try_new`] returns an error
191    pub fn new(views: ScalarBuffer<u128>, buffers: Vec<Buffer>, nulls: Option<NullBuffer>) -> Self {
192        Self::try_new(views, buffers, nulls).unwrap()
193    }
194
195    /// Create a new [`GenericByteViewArray`] from the provided parts, returning an error on failure
196    ///
197    /// # Errors
198    ///
199    /// * `views.len() != nulls.len()`
200    /// * [ByteViewType::validate] fails
201    pub fn try_new(
202        views: ScalarBuffer<u128>,
203        buffers: Vec<Buffer>,
204        nulls: Option<NullBuffer>,
205    ) -> Result<Self, ArrowError> {
206        T::validate(&views, &buffers)?;
207
208        if let Some(n) = nulls.as_ref() {
209            if n.len() != views.len() {
210                return Err(ArrowError::InvalidArgumentError(format!(
211                    "Incorrect length of null buffer for {}ViewArray, expected {} got {}",
212                    T::PREFIX,
213                    views.len(),
214                    n.len(),
215                )));
216            }
217        }
218
219        Ok(Self {
220            data_type: T::DATA_TYPE,
221            views,
222            buffers,
223            nulls,
224            phantom: Default::default(),
225        })
226    }
227
228    /// Create a new [`GenericByteViewArray`] from the provided parts, without validation
229    ///
230    /// # Safety
231    ///
232    /// Safe if [`Self::try_new`] would not error
233    pub unsafe fn new_unchecked(
234        views: ScalarBuffer<u128>,
235        buffers: Vec<Buffer>,
236        nulls: Option<NullBuffer>,
237    ) -> Self {
238        if cfg!(feature = "force_validate") {
239            return Self::new(views, buffers, nulls);
240        }
241
242        Self {
243            data_type: T::DATA_TYPE,
244            phantom: Default::default(),
245            views,
246            buffers,
247            nulls,
248        }
249    }
250
251    /// Create a new [`GenericByteViewArray`] of length `len` where all values are null
252    pub fn new_null(len: usize) -> Self {
253        Self {
254            data_type: T::DATA_TYPE,
255            views: vec![0; len].into(),
256            buffers: vec![],
257            nulls: Some(NullBuffer::new_null(len)),
258            phantom: Default::default(),
259        }
260    }
261
262    /// Create a new [`Scalar`] from `value`
263    pub fn new_scalar(value: impl AsRef<T::Native>) -> Scalar<Self> {
264        Scalar::new(Self::from_iter_values(std::iter::once(value)))
265    }
266
267    /// Creates a [`GenericByteViewArray`] based on an iterator of values without nulls
268    pub fn from_iter_values<Ptr, I>(iter: I) -> Self
269    where
270        Ptr: AsRef<T::Native>,
271        I: IntoIterator<Item = Ptr>,
272    {
273        let iter = iter.into_iter();
274        let mut builder = GenericByteViewBuilder::<T>::with_capacity(iter.size_hint().0);
275        for v in iter {
276            builder.append_value(v);
277        }
278        builder.finish()
279    }
280
281    /// Deconstruct this array into its constituent parts
282    pub fn into_parts(self) -> (ScalarBuffer<u128>, Vec<Buffer>, Option<NullBuffer>) {
283        (self.views, self.buffers, self.nulls)
284    }
285
286    /// Returns the views buffer
287    #[inline]
288    pub fn views(&self) -> &ScalarBuffer<u128> {
289        &self.views
290    }
291
292    /// Returns the buffers storing string data
293    #[inline]
294    pub fn data_buffers(&self) -> &[Buffer] {
295        &self.buffers
296    }
297
298    /// Returns the element at index `i`
299    /// # Panics
300    /// Panics if index `i` is out of bounds.
301    pub fn value(&self, i: usize) -> &T::Native {
302        assert!(
303            i < self.len(),
304            "Trying to access an element at index {} from a {}ViewArray of length {}",
305            i,
306            T::PREFIX,
307            self.len()
308        );
309
310        unsafe { self.value_unchecked(i) }
311    }
312
313    /// Returns the element at index `i` without bounds checking
314    ///
315    /// # Safety
316    ///
317    /// Caller is responsible for ensuring that the index is within the bounds
318    /// of the array
319    pub unsafe fn value_unchecked(&self, idx: usize) -> &T::Native {
320        let v = self.views.get_unchecked(idx);
321        let len = *v as u32;
322        let b = if len <= MAX_INLINE_VIEW_LEN {
323            Self::inline_value(v, len as usize)
324        } else {
325            let view = ByteView::from(*v);
326            let data = self.buffers.get_unchecked(view.buffer_index as usize);
327            let offset = view.offset as usize;
328            data.get_unchecked(offset..offset + len as usize)
329        };
330        T::Native::from_bytes_unchecked(b)
331    }
332
333    /// Returns the first `len` bytes the inline value of the view.
334    ///
335    /// # Safety
336    /// - The `view` must be a valid element from `Self::views()` that adheres to the view layout.
337    /// - The `len` must be the length of the inlined value. It should never be larger than [`MAX_INLINE_VIEW_LEN`].
338    #[inline(always)]
339    pub unsafe fn inline_value(view: &u128, len: usize) -> &[u8] {
340        debug_assert!(len <= MAX_INLINE_VIEW_LEN as usize);
341        std::slice::from_raw_parts((view as *const u128 as *const u8).wrapping_add(4), len)
342    }
343
344    /// Constructs a new iterator for iterating over the values of this array
345    pub fn iter(&self) -> ArrayIter<&Self> {
346        ArrayIter::new(self)
347    }
348
349    /// Returns an iterator over the bytes of this array, including null values
350    pub fn bytes_iter(&self) -> impl Iterator<Item = &[u8]> {
351        self.views.iter().map(move |v| {
352            let len = *v as u32;
353            if len <= MAX_INLINE_VIEW_LEN {
354                unsafe { Self::inline_value(v, len as usize) }
355            } else {
356                let view = ByteView::from(*v);
357                let data = &self.buffers[view.buffer_index as usize];
358                let offset = view.offset as usize;
359                unsafe { data.get_unchecked(offset..offset + len as usize) }
360            }
361        })
362    }
363
364    /// Returns an iterator over the first `prefix_len` bytes of each array
365    /// element, including null values.
366    ///
367    /// If `prefix_len` is larger than the element's length, the iterator will
368    /// return an empty slice (`&[]`).
369    pub fn prefix_bytes_iter(&self, prefix_len: usize) -> impl Iterator<Item = &[u8]> {
370        self.views().into_iter().map(move |v| {
371            let len = (*v as u32) as usize;
372
373            if len < prefix_len {
374                return &[] as &[u8];
375            }
376
377            if prefix_len <= 4 || len as u32 <= MAX_INLINE_VIEW_LEN {
378                unsafe { StringViewArray::inline_value(v, prefix_len) }
379            } else {
380                let view = ByteView::from(*v);
381                let data = unsafe {
382                    self.data_buffers()
383                        .get_unchecked(view.buffer_index as usize)
384                };
385                let offset = view.offset as usize;
386                unsafe { data.get_unchecked(offset..offset + prefix_len) }
387            }
388        })
389    }
390
391    /// Returns an iterator over the last `suffix_len` bytes of each array
392    /// element, including null values.
393    ///
394    /// Note that for [`StringViewArray`] the last bytes may start in the middle
395    /// of a UTF-8 codepoint, and thus may not be a valid `&str`.
396    ///
397    /// If `suffix_len` is larger than the element's length, the iterator will
398    /// return an empty slice (`&[]`).
399    pub fn suffix_bytes_iter(&self, suffix_len: usize) -> impl Iterator<Item = &[u8]> {
400        self.views().into_iter().map(move |v| {
401            let len = (*v as u32) as usize;
402
403            if len < suffix_len {
404                return &[] as &[u8];
405            }
406
407            if len as u32 <= MAX_INLINE_VIEW_LEN {
408                unsafe { &StringViewArray::inline_value(v, len)[len - suffix_len..] }
409            } else {
410                let view = ByteView::from(*v);
411                let data = unsafe {
412                    self.data_buffers()
413                        .get_unchecked(view.buffer_index as usize)
414                };
415                let offset = view.offset as usize;
416                unsafe { data.get_unchecked(offset + len - suffix_len..offset + len) }
417            }
418        })
419    }
420
421    /// Returns a zero-copy slice of this array with the indicated offset and length.
422    pub fn slice(&self, offset: usize, length: usize) -> Self {
423        Self {
424            data_type: T::DATA_TYPE,
425            views: self.views.slice(offset, length),
426            buffers: self.buffers.clone(),
427            nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
428            phantom: Default::default(),
429        }
430    }
431
432    /// Returns a "compacted" version of this array
433    ///
434    /// The original array will *not* be modified
435    ///
436    /// # Garbage Collection
437    ///
438    /// Before GC:
439    /// ```text
440    ///                                        ┌──────┐
441    ///                                        │......│
442    ///                                        │......│
443    /// ┌────────────────────┐       ┌ ─ ─ ─ ▶ │Data1 │   Large buffer
444    /// │       View 1       │─ ─ ─ ─          │......│  with data that
445    /// ├────────────────────┤                 │......│ is not referred
446    /// │       View 2       │─ ─ ─ ─ ─ ─ ─ ─▶ │Data2 │ to by View 1 or
447    /// └────────────────────┘                 │......│      View 2
448    ///                                        │......│
449    ///    2 views, refer to                   │......│
450    ///   small portions of a                  └──────┘
451    ///      large buffer
452    /// ```
453    ///
454    /// After GC:
455    ///
456    /// ```text
457    /// ┌────────────────────┐                 ┌─────┐    After gc, only
458    /// │       View 1       │─ ─ ─ ─ ─ ─ ─ ─▶ │Data1│     data that is
459    /// ├────────────────────┤       ┌ ─ ─ ─ ▶ │Data2│    pointed to by
460    /// │       View 2       │─ ─ ─ ─          └─────┘     the views is
461    /// └────────────────────┘                                 left
462    ///
463    ///
464    ///         2 views
465    /// ```
466    /// This method will compact the data buffers by recreating the view array and only include the data
467    /// that is pointed to by the views.
468    ///
469    /// Note that it will copy the array regardless of whether the original array is compact.
470    /// Use with caution as this can be an expensive operation, only use it when you are sure that the view
471    /// array is significantly smaller than when it is originally created, e.g., after filtering or slicing.
472    ///
473    /// Note: this function does not attempt to canonicalize / deduplicate values. For this
474    /// feature see  [`GenericByteViewBuilder::with_deduplicate_strings`].
475    pub fn gc(&self) -> Self {
476        // 1) Read basic properties once
477        let len = self.len(); // number of elements
478        let nulls = self.nulls().cloned(); // reuse & clone existing null bitmap
479
480        // 1.5) Fast path: if there are no buffers, just reuse original views and no data blocks
481        if self.data_buffers().is_empty() {
482            return unsafe {
483                GenericByteViewArray::new_unchecked(
484                    self.views().clone(),
485                    vec![], // empty data blocks
486                    nulls,
487                )
488            };
489        }
490
491        // 2) Calculate total size of all non-inline data and detect if any exists
492        let total_large = self.total_buffer_bytes_used();
493
494        // 2.5) Fast path: if there is no non-inline data, avoid buffer allocation & processing
495        if total_large == 0 {
496            // Views are inline-only or all null; just reuse original views and no data blocks
497            return unsafe {
498                GenericByteViewArray::new_unchecked(
499                    self.views().clone(),
500                    vec![], // empty data blocks
501                    nulls,
502                )
503            };
504        }
505
506        // 3) Allocate exactly capacity for all non-inline data
507        let mut data_buf = Vec::with_capacity(total_large);
508
509        // 4) Iterate over views and process each inline/non-inline view
510        let views_buf: Vec<u128> = (0..len)
511            .map(|i| unsafe { self.copy_view_to_buffer(i, &mut data_buf) })
512            .collect();
513
514        // 5) Wrap up buffers
515        let data_block = Buffer::from_vec(data_buf);
516        let views_scalar = ScalarBuffer::from(views_buf);
517        let data_blocks = vec![data_block];
518
519        // SAFETY: views_scalar, data_blocks, and nulls are correctly aligned and sized
520        unsafe { GenericByteViewArray::new_unchecked(views_scalar, data_blocks, nulls) }
521    }
522
523    /// Copy the i‑th view into `data_buf` if it refers to an out‑of‑line buffer.
524    ///
525    /// # Safety
526    ///
527    /// - `i < self.len()`.
528    /// - Every element in `self.views()` must currently refer to a valid slice
529    ///   inside one of `self.buffers`.
530    /// - `data_buf` must be ready to have additional bytes appended.
531    /// - After this call, the returned view will have its
532    ///   `buffer_index` reset to `0` and its `offset` updated so that it points
533    ///   into the bytes just appended at the end of `data_buf`.
534    #[inline(always)]
535    unsafe fn copy_view_to_buffer(&self, i: usize, data_buf: &mut Vec<u8>) -> u128 {
536        // SAFETY: `i < self.len()` ensures this is in‑bounds.
537        let raw_view = *self.views().get_unchecked(i);
538        let mut bv = ByteView::from(raw_view);
539
540        // Inline‑small views stay as‑is.
541        if bv.length <= MAX_INLINE_VIEW_LEN {
542            raw_view
543        } else {
544            // SAFETY: `bv.buffer_index` and `bv.offset..bv.offset+bv.length`
545            // must both lie within valid ranges for `self.buffers`.
546            let buffer = self.buffers.get_unchecked(bv.buffer_index as usize);
547            let start = bv.offset as usize;
548            let end = start + bv.length as usize;
549            let slice = buffer.get_unchecked(start..end);
550
551            // Copy out‑of‑line data into our single “0” buffer.
552            let new_offset = data_buf.len() as u32;
553            data_buf.extend_from_slice(slice);
554
555            bv.buffer_index = 0;
556            bv.offset = new_offset;
557            bv.into()
558        }
559    }
560
561    /// Returns the total number of bytes used by all non inlined views in all
562    /// buffers.
563    ///
564    /// Note this does not account for views that point at the same underlying
565    /// data in buffers
566    ///
567    /// For example, if the array has three strings views:
568    /// * View with length = 9 (inlined)
569    /// * View with length = 32 (non inlined)
570    /// * View with length = 16 (non inlined)
571    ///
572    /// Then this method would report 48
573    pub fn total_buffer_bytes_used(&self) -> usize {
574        self.views()
575            .iter()
576            .map(|v| {
577                let len = *v as u32;
578                if len > MAX_INLINE_VIEW_LEN {
579                    len as usize
580                } else {
581                    0
582                }
583            })
584            .sum()
585    }
586
587    /// Compare two [`GenericByteViewArray`] at index `left_idx` and `right_idx`
588    ///
589    /// Comparing two ByteView types are non-trivial.
590    /// It takes a bit of patience to understand why we don't just compare two &[u8] directly.
591    ///
592    /// ByteView types give us the following two advantages, and we need to be careful not to lose them:
593    /// (1) For string/byte smaller than [`MAX_INLINE_VIEW_LEN`] bytes, the entire data is inlined in the view.
594    ///     Meaning that reading one array element requires only one memory access
595    ///     (two memory access required for StringArray, one for offset buffer, the other for value buffer).
596    ///
597    /// (2) For string/byte larger than [`MAX_INLINE_VIEW_LEN`] bytes, we can still be faster than (for certain operations) StringArray/ByteArray,
598    ///     thanks to the inlined 4 bytes.
599    ///     Consider equality check:
600    ///     If the first four bytes of the two strings are different, we can return false immediately (with just one memory access).
601    ///
602    /// If we directly compare two &[u8], we materialize the entire string (i.e., make multiple memory accesses), which might be unnecessary.
603    /// - Most of the time (eq, ord), we only need to look at the first 4 bytes to know the answer,
604    ///   e.g., if the inlined 4 bytes are different, we can directly return unequal without looking at the full string.
605    ///
606    /// # Order check flow
607    /// (1) if both string are smaller than [`MAX_INLINE_VIEW_LEN`] bytes, we can directly compare the data inlined to the view.
608    /// (2) if any of the string is larger than [`MAX_INLINE_VIEW_LEN`] bytes, we need to compare the full string.
609    ///     (2.1) if the inlined 4 bytes are different, we can return the result immediately.
610    ///     (2.2) o.w., we need to compare the full string.
611    ///
612    /// # Safety
613    /// The left/right_idx must within range of each array
614    pub unsafe fn compare_unchecked(
615        left: &GenericByteViewArray<T>,
616        left_idx: usize,
617        right: &GenericByteViewArray<T>,
618        right_idx: usize,
619    ) -> Ordering {
620        let l_view = left.views().get_unchecked(left_idx);
621        let l_byte_view = ByteView::from(*l_view);
622
623        let r_view = right.views().get_unchecked(right_idx);
624        let r_byte_view = ByteView::from(*r_view);
625
626        let l_len = l_byte_view.length;
627        let r_len = r_byte_view.length;
628
629        if l_len <= 12 && r_len <= 12 {
630            return Self::inline_key_fast(*l_view).cmp(&Self::inline_key_fast(*r_view));
631        }
632
633        // one of the string is larger than 12 bytes,
634        // we then try to compare the inlined data first
635
636        // Note: In theory, ByteView is only used for string which is larger than 12 bytes,
637        // but we can still use it to get the inlined prefix for shorter strings.
638        // The prefix is always the first 4 bytes of the view, for both short and long strings.
639        let l_inlined_be = l_byte_view.prefix.swap_bytes();
640        let r_inlined_be = r_byte_view.prefix.swap_bytes();
641        if l_inlined_be != r_inlined_be {
642            return l_inlined_be.cmp(&r_inlined_be);
643        }
644
645        // unfortunately, we need to compare the full data
646        let l_full_data: &[u8] = unsafe { left.value_unchecked(left_idx).as_ref() };
647        let r_full_data: &[u8] = unsafe { right.value_unchecked(right_idx).as_ref() };
648
649        l_full_data.cmp(r_full_data)
650    }
651
652    /// Builds a 128-bit composite key for an inline value:
653    ///
654    /// - High 96 bits: the inline data in big-endian byte order (for correct lexicographical sorting).
655    /// - Low  32 bits: the length in big-endian byte order, acting as a tiebreaker so shorter strings
656    ///   (or those with fewer meaningful bytes) always numerically sort before longer ones.
657    ///
658    /// This function extracts the length and the 12-byte inline string data from the raw
659    /// little-endian `u128` representation, converts them to big-endian ordering, and packs them
660    /// into a single `u128` value suitable for fast, branchless comparisons.
661    ///
662    /// # Why include length?
663    ///
664    /// A pure 96-bit content comparison can’t distinguish between two values whose inline bytes
665    /// compare equal—either because one is a true prefix of the other or because zero-padding
666    /// hides extra bytes. By tucking the 32-bit length into the lower bits, a single `u128` compare
667    /// handles both content and length in one go.
668    ///
669    /// Example: comparing "bar" (3 bytes) vs "bar\0" (4 bytes)
670    ///
671    /// | String     | Bytes 0–4 (length LE) | Bytes 4–16 (data + padding)    |
672    /// |------------|-----------------------|---------------------------------|
673    /// | `"bar"`   | `03 00 00 00`         | `62 61 72` + 9 × `00`           |
674    /// | `"bar\0"`| `04 00 00 00`         | `62 61 72 00` + 8 × `00`        |
675    ///
676    /// Both inline parts become `62 61 72 00…00`, so they tie on content. The length field
677    /// then differentiates:
678    ///
679    /// ```text
680    /// key("bar")   = 0x0000000000000000000062617200000003
681    /// key("bar\0") = 0x0000000000000000000062617200000004
682    /// ⇒ key("bar") < key("bar\0")
683    /// ```
684    /// # Inlining and Endianness
685    ///
686    /// - We start by calling `.to_le_bytes()` on the `raw` `u128`, because Rust’s native in‑memory
687    ///   representation is little‑endian on x86/ARM.
688    /// - We extract the low 32 bits numerically (`raw as u32`)—this step is endianness‑free.
689    /// - We copy the 12 bytes of inline data (original order) into `buf[0..12]`.
690    /// - We serialize `length` as big‑endian into `buf[12..16]`.
691    /// - Finally, `u128::from_be_bytes(buf)` treats `buf[0]` as the most significant byte
692    ///   and `buf[15]` as the least significant, producing a `u128` whose integer value
693    ///   directly encodes “inline data then length” in big‑endian form.
694    ///
695    /// This ensures that a simple `u128` comparison is equivalent to the desired
696    /// lexicographical comparison of the inline bytes followed by length.
697    #[inline(always)]
698    pub fn inline_key_fast(raw: u128) -> u128 {
699        // 1. Decompose `raw` into little‑endian bytes:
700        //    - raw_bytes[0..4]  = length in LE
701        //    - raw_bytes[4..16] = inline string data
702        let raw_bytes = raw.to_le_bytes();
703
704        // 2. Numerically truncate to get the low 32‑bit length (endianness‑free).
705        let length = raw as u32;
706
707        // 3. Build a 16‑byte buffer in big‑endian order:
708        //    - buf[0..12]  = inline string bytes (in original order)
709        //    - buf[12..16] = length.to_be_bytes() (BE)
710        let mut buf = [0u8; 16];
711        buf[0..12].copy_from_slice(&raw_bytes[4..16]); // inline data
712
713        // Why convert length to big-endian for comparison?
714        //
715        // Rust (on most platforms) stores integers in little-endian format,
716        // meaning the least significant byte is at the lowest memory address.
717        // For example, an u32 value like 0x22345677 is stored in memory as:
718        //
719        //   [0x77, 0x56, 0x34, 0x22]  // little-endian layout
720        //    ^     ^     ^     ^
721        //  LSB   ↑↑↑           MSB
722        //
723        // This layout is efficient for arithmetic but *not* suitable for
724        // lexicographic (dictionary-style) comparison of byte arrays.
725        //
726        // To compare values by byte order—e.g., for sorted keys or binary trees—
727        // we must convert them to **big-endian**, where:
728        //
729        //   - The most significant byte (MSB) comes first (index 0)
730        //   - The least significant byte (LSB) comes last (index N-1)
731        //
732        // In big-endian, the same u32 = 0x22345677 would be represented as:
733        //
734        //   [0x22, 0x34, 0x56, 0x77]
735        //
736        // This ordering aligns with natural string/byte sorting, so calling
737        // `.to_be_bytes()` allows us to construct
738        // keys where standard numeric comparison (e.g., `<`, `>`) behaves
739        // like lexicographic byte comparison.
740        buf[12..16].copy_from_slice(&length.to_be_bytes()); // length in BE
741
742        // 4. Deserialize the buffer as a big‑endian u128:
743        //    buf[0] is MSB, buf[15] is LSB.
744        // Details:
745        // Note on endianness and layout:
746        //
747        // Although `buf[0]` is stored at the lowest memory address,
748        // calling `u128::from_be_bytes(buf)` interprets it as the **most significant byte (MSB)**,
749        // and `buf[15]` as the **least significant byte (LSB)**.
750        //
751        // This is the core principle of **big-endian decoding**:
752        //   - Byte at index 0 maps to bits 127..120 (highest)
753        //   - Byte at index 1 maps to bits 119..112
754        //   - ...
755        //   - Byte at index 15 maps to bits 7..0 (lowest)
756        //
757        // So even though memory layout goes from low to high (left to right),
758        // big-endian treats the **first byte** as highest in value.
759        //
760        // This guarantees that comparing two `u128` keys is equivalent to lexicographically
761        // comparing the original inline bytes, followed by length.
762        u128::from_be_bytes(buf)
763    }
764}
765
766impl<T: ByteViewType + ?Sized> Debug for GenericByteViewArray<T> {
767    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
768        write!(f, "{}ViewArray\n[\n", T::PREFIX)?;
769        print_long_array(self, f, |array, index, f| {
770            std::fmt::Debug::fmt(&array.value(index), f)
771        })?;
772        write!(f, "]")
773    }
774}
775
776impl<T: ByteViewType + ?Sized> Array for GenericByteViewArray<T> {
777    fn as_any(&self) -> &dyn Any {
778        self
779    }
780
781    fn to_data(&self) -> ArrayData {
782        self.clone().into()
783    }
784
785    fn into_data(self) -> ArrayData {
786        self.into()
787    }
788
789    fn data_type(&self) -> &DataType {
790        &self.data_type
791    }
792
793    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
794        Arc::new(self.slice(offset, length))
795    }
796
797    fn len(&self) -> usize {
798        self.views.len()
799    }
800
801    fn is_empty(&self) -> bool {
802        self.views.is_empty()
803    }
804
805    fn shrink_to_fit(&mut self) {
806        self.views.shrink_to_fit();
807        self.buffers.iter_mut().for_each(|b| b.shrink_to_fit());
808        self.buffers.shrink_to_fit();
809        if let Some(nulls) = &mut self.nulls {
810            nulls.shrink_to_fit();
811        }
812    }
813
814    fn offset(&self) -> usize {
815        0
816    }
817
818    fn nulls(&self) -> Option<&NullBuffer> {
819        self.nulls.as_ref()
820    }
821
822    fn logical_null_count(&self) -> usize {
823        // More efficient that the default implementation
824        self.null_count()
825    }
826
827    fn get_buffer_memory_size(&self) -> usize {
828        let mut sum = self.buffers.iter().map(|b| b.capacity()).sum::<usize>();
829        sum += self.views.inner().capacity();
830        if let Some(x) = &self.nulls {
831            sum += x.buffer().capacity()
832        }
833        sum
834    }
835
836    fn get_array_memory_size(&self) -> usize {
837        std::mem::size_of::<Self>() + self.get_buffer_memory_size()
838    }
839}
840
841impl<'a, T: ByteViewType + ?Sized> ArrayAccessor for &'a GenericByteViewArray<T> {
842    type Item = &'a T::Native;
843
844    fn value(&self, index: usize) -> Self::Item {
845        GenericByteViewArray::value(self, index)
846    }
847
848    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
849        GenericByteViewArray::value_unchecked(self, index)
850    }
851}
852
853impl<'a, T: ByteViewType + ?Sized> IntoIterator for &'a GenericByteViewArray<T> {
854    type Item = Option<&'a T::Native>;
855    type IntoIter = ArrayIter<Self>;
856
857    fn into_iter(self) -> Self::IntoIter {
858        ArrayIter::new(self)
859    }
860}
861
862impl<T: ByteViewType + ?Sized> From<ArrayData> for GenericByteViewArray<T> {
863    fn from(value: ArrayData) -> Self {
864        let views = value.buffers()[0].clone();
865        let views = ScalarBuffer::new(views, value.offset(), value.len());
866        let buffers = value.buffers()[1..].to_vec();
867        Self {
868            data_type: T::DATA_TYPE,
869            views,
870            buffers,
871            nulls: value.nulls().cloned(),
872            phantom: Default::default(),
873        }
874    }
875}
876
877/// Efficiently convert a [`GenericByteArray`] to a [`GenericByteViewArray`]
878///
879/// For example this method can convert a [`StringArray`] to a
880/// [`StringViewArray`].
881///
882/// If the offsets are all less than u32::MAX, the new [`GenericByteViewArray`]
883/// is built without copying the underlying string data (views are created
884/// directly into the existing buffer)
885///
886/// [`StringArray`]: crate::StringArray
887impl<FROM, V> From<&GenericByteArray<FROM>> for GenericByteViewArray<V>
888where
889    FROM: ByteArrayType,
890    FROM::Offset: OffsetSizeTrait + ToPrimitive,
891    V: ByteViewType<Native = FROM::Native>,
892{
893    fn from(byte_array: &GenericByteArray<FROM>) -> Self {
894        let offsets = byte_array.offsets();
895
896        let can_reuse_buffer = match offsets.last() {
897            Some(offset) => offset.as_usize() < u32::MAX as usize,
898            None => true,
899        };
900
901        if can_reuse_buffer {
902            // build views directly pointing to the existing buffer
903            let len = byte_array.len();
904            let mut views_builder = GenericByteViewBuilder::<V>::with_capacity(len);
905            let str_values_buf = byte_array.values().clone();
906            let block = views_builder.append_block(str_values_buf);
907            for (i, w) in offsets.windows(2).enumerate() {
908                let offset = w[0].as_usize();
909                let end = w[1].as_usize();
910                let length = end - offset;
911
912                if byte_array.is_null(i) {
913                    views_builder.append_null();
914                } else {
915                    // Safety: the input was a valid array so it valid UTF8 (if string). And
916                    // all offsets were valid
917                    unsafe {
918                        views_builder.append_view_unchecked(block, offset as u32, length as u32)
919                    }
920                }
921            }
922            assert_eq!(views_builder.len(), len);
923            views_builder.finish()
924        } else {
925            // Otherwise, create a new buffer for large strings
926            // TODO: the original buffer could still be used
927            // by making multiple slices of u32::MAX length
928            GenericByteViewArray::<V>::from_iter(byte_array.iter())
929        }
930    }
931}
932
933impl<T: ByteViewType + ?Sized> From<GenericByteViewArray<T>> for ArrayData {
934    fn from(mut array: GenericByteViewArray<T>) -> Self {
935        let len = array.len();
936        array.buffers.insert(0, array.views.into_inner());
937        let builder = ArrayDataBuilder::new(T::DATA_TYPE)
938            .len(len)
939            .buffers(array.buffers)
940            .nulls(array.nulls);
941
942        unsafe { builder.build_unchecked() }
943    }
944}
945
946impl<'a, Ptr, T> FromIterator<&'a Option<Ptr>> for GenericByteViewArray<T>
947where
948    Ptr: AsRef<T::Native> + 'a,
949    T: ByteViewType + ?Sized,
950{
951    fn from_iter<I: IntoIterator<Item = &'a Option<Ptr>>>(iter: I) -> Self {
952        iter.into_iter()
953            .map(|o| o.as_ref().map(|p| p.as_ref()))
954            .collect()
955    }
956}
957
958impl<Ptr, T: ByteViewType + ?Sized> FromIterator<Option<Ptr>> for GenericByteViewArray<T>
959where
960    Ptr: AsRef<T::Native>,
961{
962    fn from_iter<I: IntoIterator<Item = Option<Ptr>>>(iter: I) -> Self {
963        let iter = iter.into_iter();
964        let mut builder = GenericByteViewBuilder::<T>::with_capacity(iter.size_hint().0);
965        builder.extend(iter);
966        builder.finish()
967    }
968}
969
970/// A [`GenericByteViewArray`] of `[u8]`
971///
972/// See [`GenericByteViewArray`] for format and layout details.
973///
974/// # Example
975/// ```
976/// use arrow_array::BinaryViewArray;
977/// let array = BinaryViewArray::from_iter_values(vec![b"hello" as &[u8], b"world", b"lulu", b"large payload over 12 bytes"]);
978/// assert_eq!(array.value(0), b"hello");
979/// assert_eq!(array.value(3), b"large payload over 12 bytes");
980/// ```
981pub type BinaryViewArray = GenericByteViewArray<BinaryViewType>;
982
983impl BinaryViewArray {
984    /// Convert the [`BinaryViewArray`] to [`StringViewArray`]
985    /// If items not utf8 data, validate will fail and error returned.
986    pub fn to_string_view(self) -> Result<StringViewArray, ArrowError> {
987        StringViewType::validate(self.views(), self.data_buffers())?;
988        unsafe { Ok(self.to_string_view_unchecked()) }
989    }
990
991    /// Convert the [`BinaryViewArray`] to [`StringViewArray`]
992    /// # Safety
993    /// Caller is responsible for ensuring that items in array are utf8 data.
994    pub unsafe fn to_string_view_unchecked(self) -> StringViewArray {
995        StringViewArray::new_unchecked(self.views, self.buffers, self.nulls)
996    }
997}
998
999impl From<Vec<&[u8]>> for BinaryViewArray {
1000    fn from(v: Vec<&[u8]>) -> Self {
1001        Self::from_iter_values(v)
1002    }
1003}
1004
1005impl From<Vec<Option<&[u8]>>> for BinaryViewArray {
1006    fn from(v: Vec<Option<&[u8]>>) -> Self {
1007        v.into_iter().collect()
1008    }
1009}
1010
1011/// A [`GenericByteViewArray`] that stores utf8 data
1012///
1013/// See [`GenericByteViewArray`] for format and layout details.
1014///
1015/// # Example
1016/// ```
1017/// use arrow_array::StringViewArray;
1018/// let array = StringViewArray::from_iter_values(vec!["hello", "world", "lulu", "large payload over 12 bytes"]);
1019/// assert_eq!(array.value(0), "hello");
1020/// assert_eq!(array.value(3), "large payload over 12 bytes");
1021/// ```
1022pub type StringViewArray = GenericByteViewArray<StringViewType>;
1023
1024impl StringViewArray {
1025    /// Convert the [`StringViewArray`] to [`BinaryViewArray`]
1026    pub fn to_binary_view(self) -> BinaryViewArray {
1027        unsafe { BinaryViewArray::new_unchecked(self.views, self.buffers, self.nulls) }
1028    }
1029
1030    /// Returns true if all data within this array is ASCII
1031    pub fn is_ascii(&self) -> bool {
1032        // Alternative (but incorrect): directly check the underlying buffers
1033        // (1) Our string view might be sparse, i.e., a subset of the buffers,
1034        //      so even if the buffer is not ascii, we can still be ascii.
1035        // (2) It is quite difficult to know the range of each buffer (unlike StringArray)
1036        // This means that this operation is quite expensive, shall we cache the result?
1037        //  i.e. track `is_ascii` in the builder.
1038        self.iter().all(|v| match v {
1039            Some(v) => v.is_ascii(),
1040            None => true,
1041        })
1042    }
1043}
1044
1045impl From<Vec<&str>> for StringViewArray {
1046    fn from(v: Vec<&str>) -> Self {
1047        Self::from_iter_values(v)
1048    }
1049}
1050
1051impl From<Vec<Option<&str>>> for StringViewArray {
1052    fn from(v: Vec<Option<&str>>) -> Self {
1053        v.into_iter().collect()
1054    }
1055}
1056
1057impl From<Vec<String>> for StringViewArray {
1058    fn from(v: Vec<String>) -> Self {
1059        Self::from_iter_values(v)
1060    }
1061}
1062
1063impl From<Vec<Option<String>>> for StringViewArray {
1064    fn from(v: Vec<Option<String>>) -> Self {
1065        v.into_iter().collect()
1066    }
1067}
1068
1069#[cfg(test)]
1070mod tests {
1071    use crate::builder::{BinaryViewBuilder, StringViewBuilder};
1072    use crate::types::BinaryViewType;
1073    use crate::{
1074        Array, BinaryViewArray, GenericBinaryArray, GenericByteViewArray, StringViewArray,
1075    };
1076    use arrow_buffer::{Buffer, ScalarBuffer};
1077    use arrow_data::{ByteView, MAX_INLINE_VIEW_LEN};
1078    use rand::prelude::StdRng;
1079    use rand::{Rng, SeedableRng};
1080
1081    const BLOCK_SIZE: u32 = 8;
1082
1083    #[test]
1084    fn try_new_string() {
1085        let array = StringViewArray::from_iter_values(vec![
1086            "hello",
1087            "world",
1088            "lulu",
1089            "large payload over 12 bytes",
1090        ]);
1091        assert_eq!(array.value(0), "hello");
1092        assert_eq!(array.value(3), "large payload over 12 bytes");
1093    }
1094
1095    #[test]
1096    fn try_new_binary() {
1097        let array = BinaryViewArray::from_iter_values(vec![
1098            b"hello".as_slice(),
1099            b"world".as_slice(),
1100            b"lulu".as_slice(),
1101            b"large payload over 12 bytes".as_slice(),
1102        ]);
1103        assert_eq!(array.value(0), b"hello");
1104        assert_eq!(array.value(3), b"large payload over 12 bytes");
1105    }
1106
1107    #[test]
1108    fn try_new_empty_string() {
1109        // test empty array
1110        let array = {
1111            let mut builder = StringViewBuilder::new();
1112            builder.finish()
1113        };
1114        assert!(array.is_empty());
1115    }
1116
1117    #[test]
1118    fn try_new_empty_binary() {
1119        // test empty array
1120        let array = {
1121            let mut builder = BinaryViewBuilder::new();
1122            builder.finish()
1123        };
1124        assert!(array.is_empty());
1125    }
1126
1127    #[test]
1128    fn test_append_string() {
1129        // test builder append
1130        let array = {
1131            let mut builder = StringViewBuilder::new();
1132            builder.append_value("hello");
1133            builder.append_null();
1134            builder.append_option(Some("large payload over 12 bytes"));
1135            builder.finish()
1136        };
1137        assert_eq!(array.value(0), "hello");
1138        assert!(array.is_null(1));
1139        assert_eq!(array.value(2), "large payload over 12 bytes");
1140    }
1141
1142    #[test]
1143    fn test_append_binary() {
1144        // test builder append
1145        let array = {
1146            let mut builder = BinaryViewBuilder::new();
1147            builder.append_value(b"hello");
1148            builder.append_null();
1149            builder.append_option(Some(b"large payload over 12 bytes"));
1150            builder.finish()
1151        };
1152        assert_eq!(array.value(0), b"hello");
1153        assert!(array.is_null(1));
1154        assert_eq!(array.value(2), b"large payload over 12 bytes");
1155    }
1156
1157    #[test]
1158    fn test_in_progress_recreation() {
1159        let array = {
1160            // make a builder with small block size.
1161            let mut builder = StringViewBuilder::new().with_fixed_block_size(14);
1162            builder.append_value("large payload over 12 bytes");
1163            builder.append_option(Some("another large payload over 12 bytes that double than the first one, so that we can trigger the in_progress in builder re-created"));
1164            builder.finish()
1165        };
1166        assert_eq!(array.value(0), "large payload over 12 bytes");
1167        assert_eq!(array.value(1), "another large payload over 12 bytes that double than the first one, so that we can trigger the in_progress in builder re-created");
1168        assert_eq!(2, array.buffers.len());
1169    }
1170
1171    #[test]
1172    #[should_panic(expected = "Invalid buffer index at 0: got index 3 but only has 1 buffers")]
1173    fn new_with_invalid_view_data() {
1174        let v = "large payload over 12 bytes";
1175        let view = ByteView::new(13, &v.as_bytes()[0..4])
1176            .with_buffer_index(3)
1177            .with_offset(1);
1178        let views = ScalarBuffer::from(vec![view.into()]);
1179        let buffers = vec![Buffer::from_slice_ref(v)];
1180        StringViewArray::new(views, buffers, None);
1181    }
1182
1183    #[test]
1184    #[should_panic(
1185        expected = "Encountered non-UTF-8 data at index 0: invalid utf-8 sequence of 1 bytes from index 0"
1186    )]
1187    fn new_with_invalid_utf8_data() {
1188        let v: Vec<u8> = vec![
1189            // invalid UTF8
1190            0xf0, 0x80, 0x80, 0x80, // more bytes to make it larger than 12
1191            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1192        ];
1193        let view = ByteView::new(v.len() as u32, &v[0..4]);
1194        let views = ScalarBuffer::from(vec![view.into()]);
1195        let buffers = vec![Buffer::from_slice_ref(v)];
1196        StringViewArray::new(views, buffers, None);
1197    }
1198
1199    #[test]
1200    #[should_panic(expected = "View at index 0 contained non-zero padding for string of length 1")]
1201    fn new_with_invalid_zero_padding() {
1202        let mut data = [0; 12];
1203        data[0] = b'H';
1204        data[11] = 1; // no zero padding
1205
1206        let mut view_buffer = [0; 16];
1207        view_buffer[0..4].copy_from_slice(&1u32.to_le_bytes());
1208        view_buffer[4..].copy_from_slice(&data);
1209
1210        let view = ByteView::from(u128::from_le_bytes(view_buffer));
1211        let views = ScalarBuffer::from(vec![view.into()]);
1212        let buffers = vec![];
1213        StringViewArray::new(views, buffers, None);
1214    }
1215
1216    #[test]
1217    #[should_panic(expected = "Mismatch between embedded prefix and data")]
1218    fn test_mismatch_between_embedded_prefix_and_data() {
1219        let input_str_1 = "Hello, Rustaceans!";
1220        let input_str_2 = "Hallo, Rustaceans!";
1221        let length = input_str_1.len() as u32;
1222        assert!(input_str_1.len() > 12);
1223
1224        let mut view_buffer = [0; 16];
1225        view_buffer[0..4].copy_from_slice(&length.to_le_bytes());
1226        view_buffer[4..8].copy_from_slice(&input_str_1.as_bytes()[0..4]);
1227        view_buffer[8..12].copy_from_slice(&0u32.to_le_bytes());
1228        view_buffer[12..].copy_from_slice(&0u32.to_le_bytes());
1229        let view = ByteView::from(u128::from_le_bytes(view_buffer));
1230        let views = ScalarBuffer::from(vec![view.into()]);
1231        let buffers = vec![Buffer::from_slice_ref(input_str_2.as_bytes())];
1232
1233        StringViewArray::new(views, buffers, None);
1234    }
1235
1236    #[test]
1237    fn test_gc() {
1238        let test_data = [
1239            Some("longer than 12 bytes"),
1240            Some("short"),
1241            Some("t"),
1242            Some("longer than 12 bytes"),
1243            None,
1244            Some("short"),
1245        ];
1246
1247        let array = {
1248            let mut builder = StringViewBuilder::new().with_fixed_block_size(8); // create multiple buffers
1249            test_data.into_iter().for_each(|v| builder.append_option(v));
1250            builder.finish()
1251        };
1252        assert!(array.buffers.len() > 1);
1253
1254        fn check_gc(to_test: &StringViewArray) {
1255            let gc = to_test.gc();
1256            assert_ne!(to_test.data_buffers().len(), gc.data_buffers().len());
1257
1258            to_test.iter().zip(gc.iter()).for_each(|(a, b)| {
1259                assert_eq!(a, b);
1260            });
1261            assert_eq!(to_test.len(), gc.len());
1262        }
1263
1264        check_gc(&array);
1265        check_gc(&array.slice(1, 3));
1266        check_gc(&array.slice(2, 1));
1267        check_gc(&array.slice(2, 2));
1268        check_gc(&array.slice(3, 1));
1269    }
1270
1271    /// 1) Empty array: no elements, expect gc to return empty with no data buffers
1272    #[test]
1273    fn test_gc_empty_array() {
1274        let array = StringViewBuilder::new()
1275            .with_fixed_block_size(BLOCK_SIZE)
1276            .finish();
1277        let gced = array.gc();
1278        // length and null count remain zero
1279        assert_eq!(gced.len(), 0);
1280        assert_eq!(gced.null_count(), 0);
1281        // no underlying data buffers should be allocated
1282        assert!(
1283            gced.data_buffers().is_empty(),
1284            "Expected no data buffers for empty array"
1285        );
1286    }
1287
1288    /// 2) All inline values (<= INLINE_LEN): capacity-only data buffer, same values
1289    #[test]
1290    fn test_gc_all_inline() {
1291        let mut builder = StringViewBuilder::new().with_fixed_block_size(BLOCK_SIZE);
1292        // append many short strings, each exactly INLINE_LEN long
1293        for _ in 0..100 {
1294            let s = "A".repeat(MAX_INLINE_VIEW_LEN as usize);
1295            builder.append_option(Some(&s));
1296        }
1297        let array = builder.finish();
1298        let gced = array.gc();
1299        // Since all views fit inline, data buffer is empty
1300        assert_eq!(
1301            gced.data_buffers().len(),
1302            0,
1303            "Should have no data buffers for inline values"
1304        );
1305        assert_eq!(gced.len(), 100);
1306        // verify element-wise equality
1307        array.iter().zip(gced.iter()).for_each(|(orig, got)| {
1308            assert_eq!(orig, got, "Inline value mismatch after gc");
1309        });
1310    }
1311
1312    /// 3) All large values (> INLINE_LEN): each must be copied into the new data buffer
1313    #[test]
1314    fn test_gc_all_large() {
1315        let mut builder = StringViewBuilder::new().with_fixed_block_size(BLOCK_SIZE);
1316        let large_str = "X".repeat(MAX_INLINE_VIEW_LEN as usize + 5);
1317        // append multiple large strings
1318        for _ in 0..50 {
1319            builder.append_option(Some(&large_str));
1320        }
1321        let array = builder.finish();
1322        let gced = array.gc();
1323        // New data buffers should be populated (one or more blocks)
1324        assert!(
1325            !gced.data_buffers().is_empty(),
1326            "Expected data buffers for large values"
1327        );
1328        assert_eq!(gced.len(), 50);
1329        // verify that every large string emerges unchanged
1330        array.iter().zip(gced.iter()).for_each(|(orig, got)| {
1331            assert_eq!(orig, got, "Large view mismatch after gc");
1332        });
1333    }
1334
1335    /// 4) All null elements: ensure null bitmap handling path is correct
1336    #[test]
1337    fn test_gc_all_nulls() {
1338        let mut builder = StringViewBuilder::new().with_fixed_block_size(BLOCK_SIZE);
1339        for _ in 0..20 {
1340            builder.append_null();
1341        }
1342        let array = builder.finish();
1343        let gced = array.gc();
1344        // length and null count match
1345        assert_eq!(gced.len(), 20);
1346        assert_eq!(gced.null_count(), 20);
1347        // data buffers remain empty for null-only array
1348        assert!(
1349            gced.data_buffers().is_empty(),
1350            "No data should be stored for nulls"
1351        );
1352    }
1353
1354    /// 5) Random mix of inline, large, and null values with slicing tests
1355    #[test]
1356    fn test_gc_random_mixed_and_slices() {
1357        let mut rng = StdRng::seed_from_u64(42);
1358        let mut builder = StringViewBuilder::new().with_fixed_block_size(BLOCK_SIZE);
1359        // Keep a Vec of original Option<String> for later comparison
1360        let mut original: Vec<Option<String>> = Vec::new();
1361
1362        for _ in 0..200 {
1363            if rng.random_bool(0.1) {
1364                // 10% nulls
1365                builder.append_null();
1366                original.push(None);
1367            } else {
1368                // random length between 0 and twice the inline limit
1369                let len = rng.random_range(0..(MAX_INLINE_VIEW_LEN * 2));
1370                let s: String = "A".repeat(len as usize);
1371                builder.append_option(Some(&s));
1372                original.push(Some(s));
1373            }
1374        }
1375
1376        let array = builder.finish();
1377        // Test multiple slice ranges to ensure offset logic is correct
1378        for (offset, slice_len) in &[(0, 50), (10, 100), (150, 30)] {
1379            let sliced = array.slice(*offset, *slice_len);
1380            let gced = sliced.gc();
1381            // Build expected slice of Option<&str>
1382            let expected: Vec<Option<&str>> = original[*offset..(*offset + *slice_len)]
1383                .iter()
1384                .map(|opt| opt.as_deref())
1385                .collect();
1386
1387            assert_eq!(gced.len(), *slice_len, "Slice length mismatch");
1388            // Compare element-wise
1389            gced.iter().zip(expected.iter()).for_each(|(got, expect)| {
1390                assert_eq!(got, *expect, "Value mismatch in mixed slice after gc");
1391            });
1392        }
1393    }
1394
1395    #[test]
1396    fn test_eq() {
1397        let test_data = [
1398            Some("longer than 12 bytes"),
1399            None,
1400            Some("short"),
1401            Some("again, this is longer than 12 bytes"),
1402        ];
1403
1404        let array1 = {
1405            let mut builder = StringViewBuilder::new().with_fixed_block_size(8);
1406            test_data.into_iter().for_each(|v| builder.append_option(v));
1407            builder.finish()
1408        };
1409        let array2 = {
1410            // create a new array with the same data but different layout
1411            let mut builder = StringViewBuilder::new().with_fixed_block_size(100);
1412            test_data.into_iter().for_each(|v| builder.append_option(v));
1413            builder.finish()
1414        };
1415        assert_eq!(array1, array1.clone());
1416        assert_eq!(array2, array2.clone());
1417        assert_eq!(array1, array2);
1418    }
1419
1420    /// Integration tests for `inline_key_fast` covering:
1421    ///
1422    /// 1. Monotonic ordering across increasing lengths and lexical variations.
1423    /// 2. Cross-check against `GenericBinaryArray` comparison to ensure semantic equivalence.
1424    ///
1425    /// This also includes a specific test for the “bar” vs. “bar\0” case, demonstrating why
1426    /// the length field is required even when all inline bytes fit in 12 bytes.
1427    ///
1428    /// The test includes strings that verify correct byte order (prevent reversal bugs),
1429    /// and length-based tie-breaking in the composite key.
1430    ///
1431    /// The test confirms that `inline_key_fast` produces keys which sort consistently
1432    /// with the expected lexicographical order of the raw byte arrays.
1433    #[test]
1434    fn test_inline_key_fast_various_lengths_and_lexical() {
1435        /// Helper to create a raw u128 value representing an inline ByteView:
1436        /// - `length`: number of meaningful bytes (must be ≤ 12)
1437        /// - `data`: the actual inline data bytes
1438        ///
1439        /// The first 4 bytes encode length in little-endian,
1440        /// the following 12 bytes contain the inline string data (unpadded).
1441        fn make_raw_inline(length: u32, data: &[u8]) -> u128 {
1442            assert!(length as usize <= 12, "Inline length must be ≤ 12");
1443            assert!(
1444                data.len() == length as usize,
1445                "Data length must match `length`"
1446            );
1447
1448            let mut raw_bytes = [0u8; 16];
1449            raw_bytes[0..4].copy_from_slice(&length.to_le_bytes()); // length stored little-endian
1450            raw_bytes[4..(4 + data.len())].copy_from_slice(data); // inline data
1451            u128::from_le_bytes(raw_bytes)
1452        }
1453
1454        // Test inputs: various lengths and lexical orders,
1455        // plus special cases for byte order and length tie-breaking
1456        let test_inputs: Vec<&[u8]> = vec![
1457            b"a",
1458            b"aa",
1459            b"aaa",
1460            b"aab",
1461            b"abcd",
1462            b"abcde",
1463            b"abcdef",
1464            b"abcdefg",
1465            b"abcdefgh",
1466            b"abcdefghi",
1467            b"abcdefghij",
1468            b"abcdefghijk",
1469            b"abcdefghijkl",
1470            // Tests for byte-order reversal bug:
1471            // Without the fix, "backend one" would compare as "eno dnekcab",
1472            // causing incorrect sort order relative to "backend two".
1473            b"backend one",
1474            b"backend two",
1475            // Tests length-tiebreaker logic:
1476            // "bar" (3 bytes) and "bar\0" (4 bytes) have identical inline data,
1477            // so only the length differentiates their ordering.
1478            b"bar",
1479            b"bar\0",
1480            // Additional lexical and length tie-breaking cases with same prefix, in correct lex order:
1481            b"than12Byt",
1482            b"than12Bytes",
1483            b"than12Bytes\0",
1484            b"than12Bytesx",
1485            b"than12Bytex",
1486            b"than12Bytez",
1487            // Additional lexical tests
1488            b"xyy",
1489            b"xyz",
1490            b"xza",
1491        ];
1492
1493        // Create a GenericBinaryArray for cross-comparison of lex order
1494        let array: GenericBinaryArray<i32> =
1495            GenericBinaryArray::from(test_inputs.iter().map(|s| Some(*s)).collect::<Vec<_>>());
1496
1497        for i in 0..array.len() - 1 {
1498            let v1 = array.value(i);
1499            let v2 = array.value(i + 1);
1500
1501            // Assert the array's natural lexical ordering is correct
1502            assert!(v1 < v2, "Array compare failed: {v1:?} !< {v2:?}");
1503
1504            // Assert the keys produced by inline_key_fast reflect the same ordering
1505            let key1 = GenericByteViewArray::<BinaryViewType>::inline_key_fast(make_raw_inline(
1506                v1.len() as u32,
1507                v1,
1508            ));
1509            let key2 = GenericByteViewArray::<BinaryViewType>::inline_key_fast(make_raw_inline(
1510                v2.len() as u32,
1511                v2,
1512            ));
1513
1514            assert!(
1515                key1 < key2,
1516                "Key compare failed: key({v1:?})=0x{key1:032x} !< key({v2:?})=0x{key2:032x}",
1517            );
1518        }
1519    }
1520}