polars_arrow/array/utf8/
mutable_values.rs

1use std::sync::Arc;
2
3use polars_error::{polars_bail, PolarsResult};
4
5use super::{MutableUtf8Array, StrAsBytes, Utf8Array};
6use crate::array::physical_binary::*;
7use crate::array::specification::{try_check_offsets_bounds, try_check_utf8};
8use crate::array::{Array, ArrayValuesIter, MutableArray, TryExtend, TryExtendFromSelf, TryPush};
9use crate::bitmap::MutableBitmap;
10use crate::datatypes::ArrowDataType;
11use crate::offset::{Offset, Offsets};
12use crate::trusted_len::TrustedLen;
13
14/// A [`MutableArray`] that builds a [`Utf8Array`]. It differs
15/// from [`MutableUtf8Array`] in that it builds non-null [`Utf8Array`].
16#[derive(Debug, Clone)]
17pub struct MutableUtf8ValuesArray<O: Offset> {
18    dtype: ArrowDataType,
19    offsets: Offsets<O>,
20    values: Vec<u8>,
21}
22
23impl<O: Offset> From<MutableUtf8ValuesArray<O>> for Utf8Array<O> {
24    fn from(other: MutableUtf8ValuesArray<O>) -> Self {
25        // SAFETY:
26        // `MutableUtf8ValuesArray` has the same invariants as `Utf8Array` and thus
27        // `Utf8Array` can be safely created from `MutableUtf8ValuesArray` without checks.
28        unsafe {
29            Utf8Array::<O>::new_unchecked(
30                other.dtype,
31                other.offsets.into(),
32                other.values.into(),
33                None,
34            )
35        }
36    }
37}
38
39impl<O: Offset> From<MutableUtf8ValuesArray<O>> for MutableUtf8Array<O> {
40    fn from(other: MutableUtf8ValuesArray<O>) -> Self {
41        // SAFETY:
42        // `MutableUtf8ValuesArray` has the same invariants as `MutableUtf8Array`
43        unsafe {
44            MutableUtf8Array::<O>::new_unchecked(other.dtype, other.offsets, other.values, None)
45        }
46    }
47}
48
49impl<O: Offset> Default for MutableUtf8ValuesArray<O> {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55impl<O: Offset> MutableUtf8ValuesArray<O> {
56    /// Returns an empty [`MutableUtf8ValuesArray`].
57    pub fn new() -> Self {
58        Self {
59            dtype: Self::default_dtype(),
60            offsets: Offsets::new(),
61            values: Vec::<u8>::new(),
62        }
63    }
64
65    /// Returns a [`MutableUtf8ValuesArray`] created from its internal representation.
66    ///
67    /// # Errors
68    /// This function returns an error iff:
69    /// * The last offset is not equal to the values' length.
70    /// * The `dtype`'s [`crate::datatypes::PhysicalType`] is not equal to either `Utf8` or `LargeUtf8`.
71    /// * The `values` between two consecutive `offsets` are not valid utf8
72    /// # Implementation
73    /// This function is `O(N)` - checking utf8 is `O(N)`
74    pub fn try_new(
75        dtype: ArrowDataType,
76        offsets: Offsets<O>,
77        values: Vec<u8>,
78    ) -> PolarsResult<Self> {
79        try_check_utf8(&offsets, &values)?;
80        if dtype.to_physical_type() != Self::default_dtype().to_physical_type() {
81            polars_bail!(ComputeError: "MutableUtf8ValuesArray can only be initialized with DataType::Utf8 or DataType::LargeUtf8")
82        }
83
84        Ok(Self {
85            dtype,
86            offsets,
87            values,
88        })
89    }
90
91    /// Returns a [`MutableUtf8ValuesArray`] created from its internal representation.
92    ///
93    /// # Panic
94    /// This function does not panic iff:
95    /// * The last offset is equal to the values' length.
96    /// * The `dtype`'s [`crate::datatypes::PhysicalType`] is equal to either `Utf8` or `LargeUtf8`.
97    ///
98    /// # Safety
99    /// This function is safe iff:
100    /// * the offsets are monotonically increasing
101    /// * The `values` between two consecutive `offsets` are not valid utf8
102    /// # Implementation
103    /// This function is `O(1)`
104    pub unsafe fn new_unchecked(
105        dtype: ArrowDataType,
106        offsets: Offsets<O>,
107        values: Vec<u8>,
108    ) -> Self {
109        try_check_offsets_bounds(&offsets, values.len())
110            .expect("The length of the values must be equal to the last offset value");
111
112        if dtype.to_physical_type() != Self::default_dtype().to_physical_type() {
113            panic!("MutableUtf8ValuesArray can only be initialized with DataType::Utf8 or DataType::LargeUtf8")
114        }
115
116        Self {
117            dtype,
118            offsets,
119            values,
120        }
121    }
122
123    /// Returns the default [`ArrowDataType`] of this container: [`ArrowDataType::Utf8`] or [`ArrowDataType::LargeUtf8`]
124    /// depending on the generic [`Offset`].
125    pub fn default_dtype() -> ArrowDataType {
126        Utf8Array::<O>::default_dtype()
127    }
128
129    /// Initializes a new [`MutableUtf8ValuesArray`] with a pre-allocated capacity of items.
130    pub fn with_capacity(capacity: usize) -> Self {
131        Self::with_capacities(capacity, 0)
132    }
133
134    /// Initializes a new [`MutableUtf8ValuesArray`] with a pre-allocated capacity of items and values.
135    pub fn with_capacities(capacity: usize, values: usize) -> Self {
136        Self {
137            dtype: Self::default_dtype(),
138            offsets: Offsets::<O>::with_capacity(capacity),
139            values: Vec::<u8>::with_capacity(values),
140        }
141    }
142
143    /// returns its values.
144    #[inline]
145    pub fn values(&self) -> &Vec<u8> {
146        &self.values
147    }
148
149    /// returns its offsets.
150    #[inline]
151    pub fn offsets(&self) -> &Offsets<O> {
152        &self.offsets
153    }
154
155    /// Reserves `additional` elements and `additional_values` on the values.
156    #[inline]
157    pub fn reserve(&mut self, additional: usize, additional_values: usize) {
158        self.offsets.reserve(additional + 1);
159        self.values.reserve(additional_values);
160    }
161
162    /// Returns the capacity in number of items
163    pub fn capacity(&self) -> usize {
164        self.offsets.capacity()
165    }
166
167    /// Returns the length of this array
168    #[inline]
169    pub fn len(&self) -> usize {
170        self.offsets.len_proxy()
171    }
172
173    /// Pushes a new item to the array.
174    /// # Panic
175    /// This operation panics iff the length of all values (in bytes) exceeds `O` maximum value.
176    #[inline]
177    pub fn push<T: AsRef<str>>(&mut self, value: T) {
178        self.try_push(value).unwrap()
179    }
180
181    /// Pop the last entry from [`MutableUtf8ValuesArray`].
182    /// This function returns `None` iff this array is empty.
183    pub fn pop(&mut self) -> Option<String> {
184        if self.len() == 0 {
185            return None;
186        }
187        self.offsets.pop()?;
188        let start = self.offsets.last().to_usize();
189        let value = self.values.split_off(start);
190        // SAFETY: utf8 is validated on initialization
191        Some(unsafe { String::from_utf8_unchecked(value) })
192    }
193
194    /// Returns the value of the element at index `i`.
195    /// # Panic
196    /// This function panics iff `i >= self.len`.
197    #[inline]
198    pub fn value(&self, i: usize) -> &str {
199        assert!(i < self.len());
200        unsafe { self.value_unchecked(i) }
201    }
202
203    /// Returns the value of the element at index `i`.
204    ///
205    /// # Safety
206    /// This function is safe iff `i < self.len`.
207    #[inline]
208    pub unsafe fn value_unchecked(&self, i: usize) -> &str {
209        // soundness: the invariant of the function
210        let (start, end) = self.offsets.start_end(i);
211
212        // soundness: the invariant of the struct
213        let slice = self.values.get_unchecked(start..end);
214
215        // soundness: the invariant of the struct
216        std::str::from_utf8_unchecked(slice)
217    }
218
219    /// Returns an iterator of `&str`
220    pub fn iter(&self) -> ArrayValuesIter<Self> {
221        ArrayValuesIter::new(self)
222    }
223
224    /// Shrinks the capacity of the [`MutableUtf8ValuesArray`] to fit its current length.
225    pub fn shrink_to_fit(&mut self) {
226        self.values.shrink_to_fit();
227        self.offsets.shrink_to_fit();
228    }
229
230    /// Extract the low-end APIs from the [`MutableUtf8ValuesArray`].
231    pub fn into_inner(self) -> (ArrowDataType, Offsets<O>, Vec<u8>) {
232        (self.dtype, self.offsets, self.values)
233    }
234}
235
236impl<O: Offset> MutableArray for MutableUtf8ValuesArray<O> {
237    fn len(&self) -> usize {
238        self.len()
239    }
240
241    fn validity(&self) -> Option<&MutableBitmap> {
242        None
243    }
244
245    fn as_box(&mut self) -> Box<dyn Array> {
246        let array: Utf8Array<O> = std::mem::take(self).into();
247        array.boxed()
248    }
249
250    fn as_arc(&mut self) -> Arc<dyn Array> {
251        let array: Utf8Array<O> = std::mem::take(self).into();
252        array.arced()
253    }
254
255    fn dtype(&self) -> &ArrowDataType {
256        &self.dtype
257    }
258
259    fn as_any(&self) -> &dyn std::any::Any {
260        self
261    }
262
263    fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
264        self
265    }
266
267    #[inline]
268    fn push_null(&mut self) {
269        self.push::<&str>("")
270    }
271
272    fn reserve(&mut self, additional: usize) {
273        self.reserve(additional, 0)
274    }
275
276    fn shrink_to_fit(&mut self) {
277        self.shrink_to_fit()
278    }
279}
280
281impl<O: Offset, P: AsRef<str>> FromIterator<P> for MutableUtf8ValuesArray<O> {
282    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Self {
283        let (offsets, values) = values_iter(iter.into_iter().map(StrAsBytes));
284        // soundness: T: AsRef<str> and offsets are monotonically increasing
285        unsafe { Self::new_unchecked(Self::default_dtype(), offsets, values) }
286    }
287}
288
289impl<O: Offset> MutableUtf8ValuesArray<O> {
290    pub(crate) unsafe fn extend_from_trusted_len_iter<I, P>(
291        &mut self,
292        validity: &mut MutableBitmap,
293        iterator: I,
294    ) where
295        P: AsRef<str>,
296        I: Iterator<Item = Option<P>>,
297    {
298        let iterator = iterator.map(|x| x.map(StrAsBytes));
299        extend_from_trusted_len_iter(&mut self.offsets, &mut self.values, validity, iterator);
300    }
301
302    /// Extends the [`MutableUtf8ValuesArray`] from a [`TrustedLen`]
303    #[inline]
304    pub fn extend_trusted_len<I, P>(&mut self, iterator: I)
305    where
306        P: AsRef<str>,
307        I: TrustedLen<Item = P>,
308    {
309        unsafe { self.extend_trusted_len_unchecked(iterator) }
310    }
311
312    /// Extends [`MutableUtf8ValuesArray`] from an iterator of trusted len.
313    ///
314    /// # Safety
315    /// The iterator must be trusted len.
316    #[inline]
317    pub unsafe fn extend_trusted_len_unchecked<I, P>(&mut self, iterator: I)
318    where
319        P: AsRef<str>,
320        I: Iterator<Item = P>,
321    {
322        let iterator = iterator.map(StrAsBytes);
323        extend_from_trusted_len_values_iter(&mut self.offsets, &mut self.values, iterator);
324    }
325
326    /// Creates a [`MutableUtf8ValuesArray`] from a [`TrustedLen`]
327    #[inline]
328    pub fn from_trusted_len_iter<I, P>(iterator: I) -> Self
329    where
330        P: AsRef<str>,
331        I: TrustedLen<Item = P>,
332    {
333        // soundness: I is `TrustedLen`
334        unsafe { Self::from_trusted_len_iter_unchecked(iterator) }
335    }
336
337    /// Returns a new [`MutableUtf8ValuesArray`] from an iterator of trusted length.
338    ///
339    /// # Safety
340    /// The iterator must be [`TrustedLen`](https://doc.rust-lang.org/std/iter/trait.TrustedLen.html).
341    /// I.e. that `size_hint().1` correctly reports its length.
342    #[inline]
343    pub unsafe fn from_trusted_len_iter_unchecked<I, P>(iterator: I) -> Self
344    where
345        P: AsRef<str>,
346        I: Iterator<Item = P>,
347    {
348        let iterator = iterator.map(StrAsBytes);
349        let (offsets, values) = trusted_len_values_iter(iterator);
350
351        // soundness: P is `str` and offsets are monotonically increasing
352        Self::new_unchecked(Self::default_dtype(), offsets, values)
353    }
354
355    /// Returns a new [`MutableUtf8ValuesArray`] from an iterator.
356    /// # Error
357    /// This operation errors iff the total length in bytes on the iterator exceeds `O`'s maximum value.
358    /// (`i32::MAX` or `i64::MAX` respectively).
359    pub fn try_from_iter<P: AsRef<str>, I: IntoIterator<Item = P>>(iter: I) -> PolarsResult<Self> {
360        let iterator = iter.into_iter();
361        let (lower, _) = iterator.size_hint();
362        let mut array = Self::with_capacity(lower);
363        for item in iterator {
364            array.try_push(item)?;
365        }
366        Ok(array)
367    }
368
369    /// Extend with a fallible iterator
370    pub fn extend_fallible<T, I, E>(&mut self, iter: I) -> std::result::Result<(), E>
371    where
372        E: std::error::Error,
373        I: IntoIterator<Item = std::result::Result<T, E>>,
374        T: AsRef<str>,
375    {
376        let mut iter = iter.into_iter();
377        self.reserve(iter.size_hint().0, 0);
378        iter.try_for_each(|x| {
379            self.push(x?);
380            Ok(())
381        })
382    }
383}
384
385impl<O: Offset, T: AsRef<str>> Extend<T> for MutableUtf8ValuesArray<O> {
386    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
387        extend_from_values_iter(
388            &mut self.offsets,
389            &mut self.values,
390            iter.into_iter().map(StrAsBytes),
391        );
392    }
393}
394
395impl<O: Offset, T: AsRef<str>> TryExtend<T> for MutableUtf8ValuesArray<O> {
396    fn try_extend<I: IntoIterator<Item = T>>(&mut self, iter: I) -> PolarsResult<()> {
397        let mut iter = iter.into_iter();
398        self.reserve(iter.size_hint().0, 0);
399        iter.try_for_each(|x| self.try_push(x))
400    }
401}
402
403impl<O: Offset, T: AsRef<str>> TryPush<T> for MutableUtf8ValuesArray<O> {
404    #[inline]
405    fn try_push(&mut self, value: T) -> PolarsResult<()> {
406        let bytes = value.as_ref().as_bytes();
407        self.values.extend_from_slice(bytes);
408        self.offsets.try_push(bytes.len())
409    }
410}
411
412impl<O: Offset> TryExtendFromSelf for MutableUtf8ValuesArray<O> {
413    fn try_extend_from_self(&mut self, other: &Self) -> PolarsResult<()> {
414        self.values.extend_from_slice(&other.values);
415        self.offsets.try_extend_from_self(&other.offsets)
416    }
417}