Skip to main content

quack_rs/arrow/
schema.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//! `ArrowSchema` — an owned Arrow C Data Interface schema.
7
8use std::ffi::CStr;
9use std::mem::ManuallyDrop;
10use std::ptr;
11
12use super::{ArrowSchema, RawArrowSchema};
13
14impl ArrowSchema {
15    /// An unfilled record, ready for a producer to write into.
16    ///
17    /// `release` is null, so dropping one frees nothing.
18    #[inline]
19    #[must_use]
20    pub const fn empty() -> Self {
21        Self(RawArrowSchema::empty())
22    }
23
24    /// Takes ownership of a filled ABI record.
25    ///
26    /// # Safety
27    ///
28    /// - `raw` must be a record whose `release` callback this value may call
29    ///   exactly once, and no other wrapper may hold the same record.
30    /// - It must be a valid Arrow C Data Interface schema: `format` and
31    ///   `name` null or NUL-terminated, `children` null or pointing at
32    ///   `n_children` valid child schemas, recursively. The safe accessors
33    ///   ([`format`][Self::format], [`name`][Self::name],
34    ///   [`child`][Self::child]) and `schema_from_arrow` read through those
35    ///   pointers.
36    #[inline]
37    #[must_use]
38    pub const unsafe fn from_raw(raw: RawArrowSchema) -> Self {
39        Self(raw)
40    }
41
42    /// Moves the record out of `ptr`, leaving a released placeholder behind.
43    ///
44    /// This is how to import from another Arrow binding — arrow-rs's
45    /// `FFI_ArrowSchema`, say — without a double free: the source is overwritten
46    /// with [`RawArrowSchema::empty`], so its own destructor sees `release ==
47    /// NULL` and does nothing.
48    ///
49    /// # Safety
50    ///
51    /// - `ptr` must be valid for reads and writes and properly aligned for
52    ///   [`RawArrowSchema`], which every Arrow C Data Interface `ArrowSchema` is.
53    /// - The caller must not use the record behind `ptr` afterwards, other than
54    ///   to drop the (now released) wrapper holding it.
55    /// - The record behind `ptr` must meet [`from_raw`][Self::from_raw]'s
56    ///   contract: this value calls its `release` callback, and the safe
57    ///   accessors read through its pointers.
58    #[must_use]
59    pub const unsafe fn take_from(ptr: *mut RawArrowSchema) -> Self {
60        // SAFETY: `ptr` is valid for reads and writes per this function's contract.
61        let raw = unsafe { ptr::read(ptr) };
62        // SAFETY: as above; the placeholder has `release == NULL`.
63        unsafe { ptr::write(ptr, RawArrowSchema::empty()) };
64        Self(raw)
65    }
66
67    /// Relinquishes ownership, returning the ABI record.
68    ///
69    /// The caller becomes responsible for calling `release` on it.
70    #[must_use]
71    pub fn into_raw(self) -> RawArrowSchema {
72        let this = ManuallyDrop::new(self);
73        // SAFETY: `this` is never dropped, so the record is moved out exactly once.
74        unsafe { ptr::read(&raw const this.0) }
75    }
76
77    /// A pointer to the ABI record, for C APIs that read it.
78    #[inline]
79    #[must_use]
80    pub const fn as_ptr(&self) -> *const RawArrowSchema {
81        &raw const self.0
82    }
83
84    /// A mutable pointer to the ABI record, for C APIs that fill it.
85    #[inline]
86    #[must_use]
87    pub const fn as_mut_ptr(&mut self) -> *mut RawArrowSchema {
88        &raw mut self.0
89    }
90
91    /// Whether `release` is null — either never filled, or already released.
92    #[inline]
93    #[must_use]
94    pub const fn is_released(&self) -> bool {
95        self.0.release.is_none()
96    }
97
98    /// Releases the schema now instead of at drop. Idempotent.
99    pub fn release(&mut self) {
100        if let Some(release) = self.0.release {
101            // SAFETY: `release` came from the producer that filled this record.
102            // It runs at most once: the specification has it null itself, and
103            // the line after it nulls it for a producer that does not.
104            unsafe { release(&raw mut self.0) };
105            self.0.release = None;
106        }
107    }
108
109    /// The Arrow format string, e.g. `"+s"` for the struct at the root of a
110    /// converted `DuckDB` schema.
111    ///
112    /// `None` if the schema is released, the pointer is null, or the string is
113    /// not valid UTF-8.
114    #[must_use]
115    pub fn format(&self) -> Option<&str> {
116        if self.is_released() || self.0.format.is_null() {
117            return None;
118        }
119        // SAFETY: a live record's `format` is a null-terminated string owned by
120        // the producer and valid for as long as the record is.
121        unsafe { CStr::from_ptr(self.0.format) }.to_str().ok()
122    }
123
124    /// The raw `metadata` pointer: null when released or when there is none.
125    pub(super) const fn metadata_ptr(&self) -> *const core::ffi::c_char {
126        if self.is_released() {
127            core::ptr::null()
128        } else {
129            self.0.metadata
130        }
131    }
132
133    /// The column name, or `None` when released, null, or not UTF-8.
134    #[must_use]
135    pub fn name(&self) -> Option<&str> {
136        if self.is_released() || self.0.name.is_null() {
137            return None;
138        }
139        // SAFETY: as in `format`.
140        unsafe { CStr::from_ptr(self.0.name) }.to_str().ok()
141    }
142
143    /// The Arrow flag bits (`ARROW_FLAG_NULLABLE` and friends).
144    #[inline]
145    #[must_use]
146    pub const fn flags(&self) -> i64 {
147        self.0.flags
148    }
149
150    /// Number of child schemas — the column count, at the root of a converted
151    /// `DuckDB` schema. `0` once released.
152    #[must_use]
153    pub fn child_count(&self) -> usize {
154        if self.is_released() {
155            return 0;
156        }
157        usize::try_from(self.0.n_children).unwrap_or(0)
158    }
159
160    /// Borrows child schema `index`.
161    ///
162    /// Children are owned by this schema's producer and released with it, which
163    /// is why this borrows rather than handing out an [`ArrowSchema`] that would
164    /// try to release them again.
165    #[must_use]
166    pub fn child(&self, index: usize) -> Option<&Self> {
167        if index >= self.child_count() || self.0.children.is_null() {
168            return None;
169        }
170        // SAFETY: `children` points to at least `n_children` pointers, and
171        // `index` is in range.
172        let child = unsafe { *self.0.children.add(index) };
173        if child.is_null() {
174            return None;
175        }
176        // SAFETY: `Self` is `#[repr(transparent)]` over `RawArrowSchema`, and the
177        // child lives as long as this schema does.
178        Some(unsafe { &*child.cast::<Self>() })
179    }
180
181    /// Borrows the dictionary (value) schema of a dictionary-encoded type, or
182    /// `None` for any other type or once released.
183    #[must_use]
184    pub(super) fn dictionary(&self) -> Option<&Self> {
185        if self.is_released() || self.0.dictionary.is_null() {
186            return None;
187        }
188        // SAFETY: as for `child`: `repr(transparent)`, and the dictionary lives
189        // as long as this schema does.
190        Some(unsafe { &*self.0.dictionary.cast::<Self>() })
191    }
192}
193
194impl Drop for ArrowSchema {
195    fn drop(&mut self) {
196        self.release();
197    }
198}
199
200impl core::fmt::Debug for ArrowSchema {
201    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
202        if self.is_released() {
203            return f
204                .debug_struct("ArrowSchema")
205                .field("released", &true)
206                .finish();
207        }
208        f.debug_struct("ArrowSchema")
209            .field("format", &self.format())
210            .field("name", &self.name())
211            .field("flags", &self.0.flags)
212            .field("n_children", &self.0.n_children)
213            .finish_non_exhaustive()
214    }
215}