Skip to main content

quack_rs/arrow/
array.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! `ArrowArray` — an owned Arrow C Data Interface array.
7
8use std::mem::ManuallyDrop;
9use std::ptr;
10
11use super::{ArrowArray, RawArrowArray};
12
13impl ArrowArray {
14    /// An unfilled record, ready for a producer to write into.
15    #[inline]
16    #[must_use]
17    pub const fn empty() -> Self {
18        Self(RawArrowArray::empty())
19    }
20
21    /// Takes ownership of a filled ABI record.
22    ///
23    /// # Safety
24    ///
25    /// - `raw` must be a record whose `release` callback this value may call
26    ///   exactly once, and no other wrapper may hold the same record.
27    /// - It must be a valid Arrow C Data Interface array: `length`, `offset`
28    ///   and `null_count` true, and every buffer, child and dictionary pointer
29    ///   valid for the lengths and offsets the record and its descendants
30    ///   declare. The safe accessors here and [`data_chunk_from_arrow`][super::data_chunk_from_arrow] read
31    ///   through those pointers; the Arrow C Data Interface carries no sizes
32    ///   that could be checked instead.
33    #[inline]
34    #[must_use]
35    pub const unsafe fn from_raw(raw: RawArrowArray) -> Self {
36        Self(raw)
37    }
38
39    /// Moves the record out of `ptr`, leaving a released placeholder behind.
40    ///
41    /// See [`ArrowSchema::take_from`][super::ArrowSchema::take_from].
42    ///
43    /// # Safety
44    ///
45    /// - `ptr` must be valid for reads and writes and properly aligned for
46    ///   [`RawArrowArray`].
47    /// - The caller must not use the record behind `ptr` afterwards.
48    /// - The record behind `ptr` must meet [`from_raw`][Self::from_raw]'s
49    ///   contract: this value calls its `release` callback, and the safe
50    ///   accessors and `data_chunk_from_arrow` read through its pointers.
51    #[must_use]
52    pub const unsafe fn take_from(ptr: *mut RawArrowArray) -> Self {
53        // SAFETY: `ptr` is valid for reads and writes per this function's contract.
54        let raw = unsafe { ptr::read(ptr) };
55        // SAFETY: as above; the placeholder has `release == NULL`.
56        unsafe { ptr::write(ptr, RawArrowArray::empty()) };
57        Self(raw)
58    }
59
60    /// Relinquishes ownership, returning the ABI record.
61    ///
62    /// The caller becomes responsible for calling `release` on it.
63    #[must_use]
64    pub fn into_raw(self) -> RawArrowArray {
65        let this = ManuallyDrop::new(self);
66        // SAFETY: `this` is never dropped, so the record is moved out exactly once.
67        unsafe { ptr::read(&raw const this.0) }
68    }
69
70    /// A pointer to the ABI record, for C APIs that read it.
71    #[inline]
72    #[must_use]
73    pub const fn as_ptr(&self) -> *const RawArrowArray {
74        &raw const self.0
75    }
76
77    /// A mutable pointer to the ABI record, for C APIs that fill it.
78    #[inline]
79    #[must_use]
80    pub const fn as_mut_ptr(&mut self) -> *mut RawArrowArray {
81        &raw mut self.0
82    }
83
84    /// Whether `release` is null — either never filled, or already released.
85    #[inline]
86    #[must_use]
87    pub const fn is_released(&self) -> bool {
88        self.0.release.is_none()
89    }
90
91    /// Releases the array now instead of at drop. Idempotent.
92    pub fn release(&mut self) {
93        if let Some(release) = self.0.release {
94            // SAFETY: `release` came from the producer that filled this record.
95            // It runs at most once: the specification has it null itself, and
96            // the line after it nulls it for a producer that does not.
97            unsafe { release(&raw mut self.0) };
98            self.0.release = None;
99        }
100    }
101
102    /// Number of rows. `0` once released.
103    #[must_use]
104    pub fn len(&self) -> usize {
105        if self.is_released() {
106            return 0;
107        }
108        usize::try_from(self.0.length).unwrap_or(0)
109    }
110
111    /// Whether the array carries no rows.
112    #[must_use]
113    pub fn is_empty(&self) -> bool {
114        self.len() == 0
115    }
116
117    /// Number of null entries, or `-1` when the producer did not compute it.
118    #[inline]
119    #[must_use]
120    pub const fn null_count(&self) -> i64 {
121        self.0.null_count
122    }
123
124    /// Logical offset into the buffers.
125    #[inline]
126    #[must_use]
127    pub const fn offset(&self) -> i64 {
128        self.0.offset
129    }
130
131    /// Number of child arrays — the column count, for the struct array a
132    /// converted `DuckDB` chunk produces. `0` once released.
133    #[must_use]
134    pub fn child_count(&self) -> usize {
135        if self.is_released() {
136            return 0;
137        }
138        usize::try_from(self.0.n_children).unwrap_or(0)
139    }
140
141    /// Borrows child array `index`.
142    ///
143    /// Children are owned by this array's producer and released with it.
144    #[must_use]
145    pub fn child(&self, index: usize) -> Option<&Self> {
146        if index >= self.child_count() || self.0.children.is_null() {
147            return None;
148        }
149        // SAFETY: `children` points to at least `n_children` pointers, and
150        // `index` is in range.
151        let child = unsafe { *self.0.children.add(index) };
152        if child.is_null() {
153            return None;
154        }
155        // SAFETY: `Self` is `#[repr(transparent)]` over `RawArrowArray`, and the
156        // child lives as long as this array does.
157        Some(unsafe { &*child.cast::<Self>() })
158    }
159}
160
161impl Drop for ArrowArray {
162    fn drop(&mut self) {
163        self.release();
164    }
165}
166
167impl core::fmt::Debug for ArrowArray {
168    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
169        if self.is_released() {
170            return f
171                .debug_struct("ArrowArray")
172                .field("released", &true)
173                .finish();
174        }
175        f.debug_struct("ArrowArray")
176            .field("length", &self.0.length)
177            .field("null_count", &self.0.null_count)
178            .field("offset", &self.0.offset)
179            .field("n_buffers", &self.0.n_buffers)
180            .field("n_children", &self.0.n_children)
181            .finish_non_exhaustive()
182    }
183}