Skip to main content

quack_rs/vector/
complex.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//! Complex type vector operations: STRUCT fields, LIST elements, MAP entries.
7//!
8//! `DuckDB` stores complex types as nested vectors:
9//!
10//! - **STRUCT**: a parent vector with N child vectors, one per field.
11//! - **LIST**: a parent vector holding `duckdb_list_entry { offset, length }` per row,
12//!   plus a single flat child vector containing all elements end-to-end.
13//! - **MAP**: stored as `LIST<STRUCT{key, value}>` — the list's child vector is a
14//!   STRUCT with two children: `key` (index 0) and `value` (index 1).
15//!
16//! # Reading vs writing
17//!
18//! - Use [`StructVector`] / [`ListVector`] / [`MapVector`] to access child vectors
19//!   from input or output vectors.
20//! - Child vectors are themselves `duckdb_vector` handles — pass them to
21//!   [`VectorReader`] or
22//!   [`VectorWriter`] to read/write the actual values.
23//!
24//! # Example: Reading a STRUCT column
25//!
26//! ```rust,no_run
27//! use quack_rs::vector::{VectorReader, complex::StructVector};
28//! use libduckdb_sys::{duckdb_data_chunk, duckdb_data_chunk_get_vector};
29//!
30//! // Inside a table function scan callback:
31//! // let parent_vec = unsafe { duckdb_data_chunk_get_vector(chunk, 0) };
32//! // let x_vec = StructVector::get_child(parent_vec, 0); // field index 0
33//! // let x_reader = unsafe { VectorReader::from_vector(x_vec, row_count) };
34//! // let x: f64 = unsafe { x_reader.read_f64(row_idx) };
35//! ```
36//!
37//! # Example: Writing a LIST column
38//!
39//! ```rust,no_run
40//! use quack_rs::vector::{VectorWriter, complex::ListVector};
41//! use libduckdb_sys::{duckdb_data_chunk_get_vector, duckdb_data_chunk};
42//!
43//! // Inside a scan callback:
44//! // let list_vec = unsafe { duckdb_data_chunk_get_vector(output, 0) };
45//! // // Write 3 elements for row 0: [10, 20, 30]
46//! // ListVector::reserve(list_vec, 3);
47//! // ListVector::set_size(list_vec, 3);
48//! // // Write the list offset/length entry for row 0.
49//! // ListVector::set_entry(list_vec, 0, 0, 3); // row=0, offset=0, length=3
50//! // // Write values into the child vector.
51//! // let child = ListVector::get_child(list_vec);
52//! // let mut writer = unsafe { VectorWriter::from_vector(child) };
53//! // unsafe { writer.write_i64(0, 10); writer.write_i64(1, 20); writer.write_i64(2, 30); }
54//! ```
55
56use libduckdb_sys::{
57    duckdb_array_vector_get_child, duckdb_list_entry, duckdb_list_vector_get_child,
58    duckdb_list_vector_get_size, duckdb_list_vector_reserve, duckdb_list_vector_set_size,
59    duckdb_struct_vector_get_child, duckdb_validity_row_is_valid, duckdb_vector,
60    duckdb_vector_get_data, duckdb_vector_get_validity, idx_t,
61};
62
63use crate::vector::{VectorReader, VectorWriter};
64
65// ─── STRUCT ──────────────────────────────────────────────────────────────────
66
67/// Operations on STRUCT vectors (accessing child field vectors).
68#[derive(Debug)]
69pub struct StructVector;
70
71impl StructVector {
72    /// Returns the child vector for the given field index of a STRUCT vector.
73    ///
74    /// Field indices correspond to the order of fields in the STRUCT type definition.
75    ///
76    /// # Safety
77    ///
78    /// - `vector` must be a valid `DuckDB` STRUCT vector.
79    /// - `field_idx` must be a valid field index (0 ≤ `field_idx` < number of struct fields).
80    /// - The returned vector is borrowed from `vector` and must not outlive it.
81    #[inline]
82    #[must_use]
83    pub unsafe fn get_child(vector: duckdb_vector, field_idx: usize) -> duckdb_vector {
84        // SAFETY: caller guarantees vector is a valid STRUCT vector and field_idx is valid.
85        unsafe { duckdb_struct_vector_get_child(vector, field_idx as idx_t) }
86    }
87
88    /// Creates a [`VectorReader`] for the given field of a STRUCT vector.
89    ///
90    /// # Safety
91    ///
92    /// - `vector` must be a valid `DuckDB` STRUCT vector.
93    /// - `field_idx` must be a valid field index.
94    /// - `row_count` must match the number of rows in the parent chunk.
95    pub unsafe fn field_reader(
96        vector: duckdb_vector,
97        field_idx: usize,
98        row_count: usize,
99    ) -> VectorReader {
100        // SAFETY: `StructVector::get_child` needs a live STRUCT vector and
101        // `field_idx` < its field count; those are this function's first two
102        // `# Safety` clauses, forwarded unchanged.
103        let child = unsafe { Self::get_child(vector, field_idx) };
104        // SAFETY: child is a valid vector with row_count rows.
105        unsafe { VectorReader::from_vector(child, row_count) }
106    }
107
108    /// Creates a [`VectorWriter`] for the given field of a STRUCT vector.
109    ///
110    /// # Safety
111    ///
112    /// - `vector` must be a valid `DuckDB` STRUCT vector.
113    /// - `field_idx` must be a valid field index.
114    /// - If `vector` lies inside the child of a `LIST` or `MAP` vector — is
115    ///   that child, or a STRUCT field or ARRAY element vector below it with no
116    ///   other `LIST` or `MAP` in between — the writer must not be used after
117    ///   that `LIST` or `MAP` is grown with a `reserve`, as for
118    ///   [`VectorWriter::from_vector`].
119    pub unsafe fn field_writer(vector: duckdb_vector, field_idx: usize) -> VectorWriter {
120        // SAFETY: `StructVector::get_child` needs a live STRUCT vector and
121        // `field_idx` < its field count; those are this function's first two
122        // `# Safety` clauses, forwarded unchanged.
123        let child = unsafe { Self::get_child(vector, field_idx) };
124        // SAFETY: child is a valid writable vector.
125        unsafe { VectorWriter::from_vector(child) }
126    }
127}
128
129// ─── LIST ────────────────────────────────────────────────────────────────────
130
131/// Operations on LIST vectors.
132///
133/// A LIST vector stores a `duckdb_list_entry { offset: u64, length: u64 }` per row
134/// in the parent vector, and all element values in a flat child vector.
135///
136/// # Write workflow
137///
138/// 1. [`reserve`][ListVector::reserve] — ensure child vector has capacity.
139/// 2. Write element values into the child via [`get_child`][ListVector::get_child] + [`VectorWriter`].
140/// 3. [`set_size`][ListVector::set_size] — tell `DuckDB` how many elements were written.
141/// 4. [`set_entry`][ListVector::set_entry] — write the offset/length for each parent row.
142#[derive(Debug)]
143pub struct ListVector;
144
145impl ListVector {
146    /// Returns the child vector containing all list elements (flat, across all rows).
147    ///
148    /// # Safety
149    ///
150    /// - `vector` must be a valid `DuckDB` LIST vector.
151    /// - The returned handle is borrowed from `vector`.
152    #[inline]
153    #[must_use]
154    pub unsafe fn get_child(vector: duckdb_vector) -> duckdb_vector {
155        // SAFETY: caller guarantees vector is a valid LIST vector.
156        unsafe { duckdb_list_vector_get_child(vector) }
157    }
158
159    /// Returns the total number of elements currently in the child vector.
160    ///
161    /// # Safety
162    ///
163    /// `vector` must be a valid `DuckDB` LIST vector.
164    #[inline]
165    #[must_use]
166    pub unsafe fn get_size(vector: duckdb_vector) -> usize {
167        // SAFETY: `duckdb_list_vector_get_size` returns 0 for a null handle and
168        // otherwise calls `ListVector::GetListSize` (data_chunk-c.cpp), which casts
169        // the vector's `auxiliary` buffer to `VectorListBuffer` (vector.cpp), so it
170        // needs a LIST (or MAP) vector; the `# Safety` contract makes `vector` a
171        // valid LIST vector.
172        usize::try_from(unsafe { duckdb_list_vector_get_size(vector) }).unwrap_or(0)
173    }
174
175    /// Sets the number of elements in the child vector.
176    ///
177    /// Call after writing all element values. `DuckDB` uses this to know how many
178    /// child elements are valid.
179    ///
180    /// # Safety
181    ///
182    /// - `vector` must be a valid `DuckDB` LIST vector.
183    /// - `size` must equal the number of elements written into the child vector.
184    #[inline]
185    pub unsafe fn set_size(vector: duckdb_vector, size: usize) {
186        // SAFETY: caller guarantees vector is valid.
187        unsafe { duckdb_list_vector_set_size(vector, size as idx_t) };
188    }
189
190    /// Reserves capacity in the child vector for at least `capacity` elements.
191    ///
192    /// Call before writing elements to ensure the child vector has enough space.
193    ///
194    /// [`ListBuilder`][crate::vector::ListBuilder] checks the capacity limit
195    /// for you; prefer it when element counts come from input data.
196    ///
197    /// # Safety
198    ///
199    /// - `vector` must be a valid `DuckDB` LIST vector.
200    /// - `capacity` must not exceed
201    ///   [`max_child_capacity(vector)`][crate::vector::max_child_capacity]:
202    ///   2^37 bytes in the widest buffer the child's type grows, as a
203    ///   power-of-two element count. Above it `DuckDB` throws an
204    ///   `OutOfRangeException` (`VectorListBuffer::Reserve`, `Vector::Resize`),
205    ///   which the C API does not catch, so the process aborts. Below it, a
206    ///   reservation the allocator cannot satisfy aborts the same way, so a
207    ///   capacity derived from input data should be bounded to what fits in
208    ///   memory.
209    #[inline]
210    pub unsafe fn reserve(vector: duckdb_vector, capacity: usize) {
211        // SAFETY: the caller guarantees a valid LIST vector (clause 1) and a
212        // capacity at or below `max_child_capacity` (clause 2), under which
213        // `ListVector::Reserve` does not throw for size.
214        unsafe { duckdb_list_vector_reserve(vector, capacity as idx_t) };
215    }
216
217    /// Writes the offset/length metadata entry for a parent row.
218    ///
219    /// This tells `DuckDB` where in the flat child vector this row's elements start
220    /// and how many elements it has.
221    ///
222    /// # Safety
223    ///
224    /// - `vector` must be a valid `DuckDB` LIST vector.
225    /// - `row_idx` must be a valid row index in the parent vector.
226    /// - `offset + length` must not exceed the size of the child vector.
227    pub unsafe fn set_entry(vector: duckdb_vector, row_idx: usize, offset: u64, length: u64) {
228        // SAFETY: vector is valid; we write to the parent vector's data at row_idx.
229        let data = unsafe { duckdb_vector_get_data(vector) };
230        // The parent stores duckdb_list_entry per row. Each entry is { offset: u64, length: u64 }.
231        // SAFETY: `data` is the flat `list_entry_t` array of this LIST vector
232        // (`duckdb_vector_get_data` returns `FlatVector::GetData`, data_chunk-c.cpp),
233        // one 16-byte `{offset: u64, length: u64}` entry per row of capacity, which
234        // `duckdb_list_entry` mirrors (see `list_entry_layout` below). The
235        // `# Safety` contract requires `row_idx` to be a valid row of `vector`, so
236        // `add(row_idx)` stays inside that allocation.
237        let entry_ptr = unsafe { data.cast::<duckdb_list_entry>().add(row_idx) };
238        // SAFETY: entry_ptr is in bounds for the allocated vector.
239        unsafe {
240            (*entry_ptr).offset = offset;
241            (*entry_ptr).length = length;
242        }
243    }
244
245    /// Returns the `duckdb_list_entry` for a given row (for reading).
246    ///
247    /// # NULL rows
248    ///
249    /// `DuckDB` writes no entry for a NULL row. The slot holds stale or
250    /// never-written bytes, so for a NULL row `offset` and `length` are
251    /// arbitrary: on `DuckDB` 2.0.0 a `nullif(l, [])` column gave NULL rows with
252    /// lengths around 7·10¹³, and a loop over such an entry reads far outside
253    /// the child vector (a segmentation fault in a minority of runs). **Check
254    /// the row's validity before using the entry**, or call
255    /// [`get_entry_checked`][Self::get_entry_checked], which does that and also
256    /// refuses an entry that does not lie inside the child.
257    ///
258    /// # Safety
259    ///
260    /// - `vector` must be a valid `DuckDB` LIST vector.
261    /// - `row_idx` must be a valid row index.
262    /// - For a NULL row the returned entry is meaningless and must not be used
263    ///   to index the child.
264    #[must_use]
265    pub unsafe fn get_entry(vector: duckdb_vector, row_idx: usize) -> duckdb_list_entry {
266        // SAFETY: `duckdb_vector_get_data` only dereferences the handle, returning
267        // null for a null one (data_chunk-c.cpp); the `# Safety` contract makes
268        // `vector` a valid LIST vector, whose data buffer is its `list_entry_t`
269        // array.
270        let data = unsafe { duckdb_vector_get_data(vector) };
271        // SAFETY: the buffer holds one 16-byte `list_entry_t` per row, which
272        // `duckdb_list_entry` mirrors, and the `# Safety` contract requires
273        // `row_idx` to be a valid row index, so `add(row_idx)` stays in bounds.
274        let entry_ptr = unsafe { data.cast::<duckdb_list_entry>().add(row_idx) };
275        // SAFETY: `entry_ptr` points into the entry array, so reading the bytes is
276        // defined (`duckdb_list_entry` is two `u64`s, valid for any bit pattern).
277        // Only a row that is not NULL holds an entry DuckDB or `set_entry` wrote;
278        // a NULL row's bytes are arbitrary, which `# NULL rows` above tells the
279        // caller not to trust.
280        unsafe { core::ptr::read_unaligned(entry_ptr) }
281    }
282
283    /// Returns the entry for a row that is not NULL, or `None` for a NULL row
284    /// or an entry that does not lie inside the child vector.
285    ///
286    /// This is the read-side companion of [`get_entry`][Self::get_entry]: it
287    /// checks the row's validity first (a vector with no validity mask has no
288    /// NULL rows), then that `offset + length` does not exceed
289    /// [`get_size`][Self::get_size]. The elements of a returned entry can be
290    /// indexed in a child reader created with `get_size` elements.
291    ///
292    /// # Safety
293    ///
294    /// - `vector` must be a valid `DuckDB` LIST vector.
295    /// - `row_idx` must be a valid row index.
296    #[must_use]
297    pub unsafe fn get_entry_checked(
298        vector: duckdb_vector,
299        row_idx: usize,
300    ) -> Option<duckdb_list_entry> {
301        // SAFETY: `duckdb_vector_get_validity` returns the vector's mask, or null
302        // when it has none (every row valid) or for a null handle; the `# Safety`
303        // contract makes `vector` a valid vector.
304        let validity = unsafe { duckdb_vector_get_validity(vector) };
305        // SAFETY: a non-null mask covers every row of the vector, and `row_idx`
306        // is a valid row index per the contract; a null mask is never read.
307        let is_valid = validity.is_null()
308            || unsafe { duckdb_validity_row_is_valid(validity, row_idx as idx_t) };
309        if !is_valid {
310            return None;
311        }
312        // SAFETY: forwarded from this function's contract; the row is not NULL,
313        // so its entry was written.
314        let entry = unsafe { Self::get_entry(vector, row_idx) };
315        // SAFETY: `vector` is a valid LIST vector per the contract.
316        let child_len = u64::try_from(unsafe { Self::get_size(vector) }).unwrap_or(u64::MAX);
317        entry_in_bounds(entry.offset, entry.length, child_len).then_some(entry)
318    }
319
320    /// Creates a [`VectorWriter`] for the child vector (elements).
321    ///
322    /// # Safety
323    ///
324    /// - `vector` must be a valid `DuckDB` LIST vector.
325    /// - Every index written must be below the capacity most recently reserved
326    ///   with [`ListVector::reserve`].
327    /// - The writer must not be used after the child is grown again
328    ///   ([`ListVector::reserve`] with a larger capacity, or a
329    ///   [`ListBuilder`](crate::vector::ListBuilder) row that grows it): growing
330    ///   reallocates the child's data and validity buffers, and the writer
331    ///   caches pointers to both. Fetch a new writer after every reserve.
332    pub unsafe fn child_writer(vector: duckdb_vector) -> VectorWriter {
333        // SAFETY: `ListVector::get_child` only needs a valid LIST vector, which is
334        // this function's first `# Safety` clause.
335        let child = unsafe { Self::get_child(vector) };
336        // SAFETY: `VectorWriter::from_vector` needs a valid, writable vector that
337        // outlives the writer. `child` is `&ListVector::GetEntry(*v)`
338        // (data_chunk-c.cpp), which duckdb.h documents as valid as long as the
339        // parent is, and the parent is the caller's valid LIST vector; the returned
340        // writer has no lifetime, so keeping `vector` alive while it is used is left
341        // to the caller, as with every raw-handle constructor here.
342        unsafe { VectorWriter::from_vector(child) }
343    }
344
345    /// Creates a [`VectorReader`] for the child vector (reading list elements).
346    ///
347    /// # Safety
348    ///
349    /// - `vector` must be a valid `DuckDB` LIST vector.
350    /// - `element_count` must equal the total number of elements in the child.
351    pub unsafe fn child_reader(vector: duckdb_vector, element_count: usize) -> VectorReader {
352        // SAFETY: `ListVector::get_child` only needs a valid LIST vector, which is
353        // this function's first `# Safety` clause.
354        let child = unsafe { Self::get_child(vector) };
355        // SAFETY: `VectorReader::from_vector` needs a valid vector and its row count.
356        // `child` is `&ListVector::GetEntry(*v)` (data_chunk-c.cpp), valid as long as
357        // the caller's LIST vector is (duckdb.h), and `# Safety` clause 2 makes
358        // `element_count` the number of elements in that child.
359        unsafe { VectorReader::from_vector(child, element_count) }
360    }
361}
362
363// ─── MAP ─────────────────────────────────────────────────────────────────────
364
365/// Operations on MAP vectors.
366///
367/// `DuckDB` stores maps as `LIST<STRUCT{key: K, value: V}>`.
368/// The child of the list vector is a STRUCT vector with two fields:
369/// - field index 0: keys
370/// - field index 1: values
371///
372/// # Example
373///
374/// ```rust,no_run
375/// use quack_rs::vector::complex::MapVector;
376/// use libduckdb_sys::duckdb_vector;
377///
378/// // Reading MAP keys from a MAP vector:
379/// // let keys_vec = unsafe { MapVector::keys(map_vector) };
380/// // let vals_vec = unsafe { MapVector::values(map_vector) };
381/// ```
382#[derive(Debug)]
383pub struct MapVector;
384
385impl MapVector {
386    /// Returns the child STRUCT vector (contains both keys and values as fields).
387    ///
388    /// # Safety
389    ///
390    /// `vector` must be a valid `DuckDB` MAP vector.
391    #[inline]
392    #[must_use]
393    pub unsafe fn struct_child(vector: duckdb_vector) -> duckdb_vector {
394        // MAP is LIST<STRUCT{key,value}>, so the list child is a STRUCT vector.
395        // SAFETY: `duckdb_list_vector_get_child` calls `ListVector::GetEntry`
396        // (data_chunk-c.cpp), whose `GetEntryInternal` accepts `LogicalTypeId::MAP`
397        // as well as LIST (vector.cpp); the `# Safety` contract makes `vector` a
398        // valid MAP vector.
399        unsafe { duckdb_list_vector_get_child(vector) }
400    }
401
402    /// Returns the keys vector (STRUCT field 0 of the MAP's child).
403    ///
404    /// # Safety
405    ///
406    /// `vector` must be a valid `DuckDB` MAP vector.
407    #[inline]
408    #[must_use]
409    pub unsafe fn keys(vector: duckdb_vector) -> duckdb_vector {
410        // SAFETY: `struct_child` only needs a valid MAP vector, which is this
411        // function's `# Safety` contract.
412        let struct_vec = unsafe { Self::struct_child(vector) };
413        // SAFETY: MAP child STRUCT always has key at field 0, value at field 1.
414        unsafe { duckdb_struct_vector_get_child(struct_vec, 0) }
415    }
416
417    /// Returns the values vector (STRUCT field 1 of the MAP's child).
418    ///
419    /// # Safety
420    ///
421    /// `vector` must be a valid `DuckDB` MAP vector.
422    #[inline]
423    #[must_use]
424    pub unsafe fn values(vector: duckdb_vector) -> duckdb_vector {
425        // SAFETY: `struct_child` only needs a valid MAP vector, which is this
426        // function's `# Safety` contract.
427        let struct_vec = unsafe { Self::struct_child(vector) };
428        // SAFETY: MAP child STRUCT always has key at field 0, value at field 1.
429        unsafe { duckdb_struct_vector_get_child(struct_vec, 1) }
430    }
431
432    /// Returns the total number of key-value pairs across all rows.
433    ///
434    /// # Safety
435    ///
436    /// `vector` must be a valid `DuckDB` MAP vector.
437    #[inline]
438    #[must_use]
439    pub unsafe fn total_entry_count(vector: duckdb_vector) -> usize {
440        // SAFETY: `duckdb_list_vector_get_size` calls `ListVector::GetListSize`
441        // (data_chunk-c.cpp), which reads the `VectorListBuffer` that LIST and MAP
442        // vectors both carry (vector.cpp); the `# Safety` contract makes `vector` a
443        // valid MAP vector.
444        usize::try_from(unsafe { duckdb_list_vector_get_size(vector) }).unwrap_or(0)
445    }
446
447    /// Reserves capacity in the MAP's child vector for at least `capacity` entries.
448    ///
449    /// # Safety
450    ///
451    /// - `vector` must be a valid `DuckDB` MAP vector.
452    /// - `capacity` must not exceed
453    ///   [`max_child_capacity(vector)`][crate::vector::max_child_capacity];
454    ///   see [`ListVector::reserve`], which this shares with `DuckDB`.
455    #[inline]
456    pub unsafe fn reserve(vector: duckdb_vector, capacity: usize) {
457        // SAFETY: `duckdb_list_vector_reserve` calls `ListVector::Reserve`
458        // (data_chunk-c.cpp), which requires a LIST or MAP vector with a list buffer
459        // (vector.cpp) — `# Safety` clause 1 — and throws `OutOfRangeException`
460        // when the rounded-up capacity's bytes pass `MAX_VECTOR_SIZE` = 2^37
461        // (vector_buffer.cpp, vector.cpp), which would abort across the C API;
462        // clause 2 keeps `capacity` at or below `max_child_capacity`.
463        unsafe { duckdb_list_vector_reserve(vector, capacity as idx_t) };
464    }
465
466    /// Sets the total number of key-value entries written.
467    ///
468    /// # Safety
469    ///
470    /// - `vector` must be a valid `DuckDB` MAP vector.
471    /// - `size` must equal the number of key-value entries written into the key
472    ///   and value child vectors, so it is at most the capacity reserved with
473    ///   [`reserve`][Self::reserve]. `DuckDB` stores `size` unchecked and later
474    ///   reads that many child entries.
475    #[inline]
476    pub unsafe fn set_size(vector: duckdb_vector, size: usize) {
477        // SAFETY: `duckdb_list_vector_set_size` calls `ListVector::SetListSize`
478        // (data_chunk-c.cpp), which casts the vector's `auxiliary` to
479        // `VectorListBuffer` and stores `size` unchecked (vector.cpp,
480        // vector_buffer.cpp). `# Safety` clause 1 makes `vector` a valid MAP
481        // vector; clause 2 keeps `size` within the entries actually written,
482        // so DuckDB's later reads of `size` child entries stay in bounds.
483        unsafe { duckdb_list_vector_set_size(vector, size as idx_t) };
484    }
485
486    /// Writes the offset/length metadata for a parent MAP row.
487    ///
488    /// This has the same semantics as [`ListVector::set_entry`], since MAP is a LIST.
489    ///
490    /// # Safety
491    ///
492    /// Same as [`ListVector::set_entry`].
493    #[inline]
494    pub unsafe fn set_entry(vector: duckdb_vector, row_idx: usize, offset: u64, length: u64) {
495        // SAFETY: same layout as ListVector.
496        unsafe { ListVector::set_entry(vector, row_idx, offset, length) };
497    }
498
499    /// Returns the `duckdb_list_entry` for a given MAP row (for reading).
500    ///
501    /// Like [`ListVector::get_entry`], the entry of a NULL row is arbitrary:
502    /// check the row's validity first, or use
503    /// [`get_entry_checked`][Self::get_entry_checked].
504    ///
505    /// # Safety
506    ///
507    /// Same as [`ListVector::get_entry`].
508    #[must_use]
509    pub unsafe fn get_entry(vector: duckdb_vector, row_idx: usize) -> duckdb_list_entry {
510        // SAFETY: this function's contract is `ListVector::get_entry`'s (a valid
511        // vector whose data is a `list_entry_t` array, and a valid `row_idx`); a
512        // MAP vector is physically `LIST<STRUCT{key, value}>`, so its data buffer
513        // has that same layout.
514        unsafe { ListVector::get_entry(vector, row_idx) }
515    }
516
517    /// Returns the entry for a MAP row that is not NULL, or `None` for a NULL
518    /// row or an entry outside the entry list. See
519    /// [`ListVector::get_entry_checked`].
520    ///
521    /// # Safety
522    ///
523    /// Same as [`ListVector::get_entry`].
524    #[must_use]
525    pub unsafe fn get_entry_checked(
526        vector: duckdb_vector,
527        row_idx: usize,
528    ) -> Option<duckdb_list_entry> {
529        // SAFETY: this function's contract is `ListVector::get_entry_checked`'s; a
530        // MAP vector is physically a LIST vector (see `get_entry`), and its list
531        // size is the entry count.
532        unsafe { ListVector::get_entry_checked(vector, row_idx) }
533    }
534
535    /// Creates a [`VectorWriter`] for the keys vector (STRUCT field 0).
536    ///
537    /// # Safety
538    ///
539    /// - `vector` must be a valid `DuckDB` MAP vector.
540    /// - Every index written must be below the capacity most recently reserved
541    ///   with [`MapVector::reserve`].
542    /// - The writer must not be used after the map is grown again
543    ///   ([`MapVector::reserve`] with a larger capacity, or a
544    ///   [`ListBuilder`](crate::vector::ListBuilder) row that grows it): growing
545    ///   reallocates the child's data and validity buffers, and the writer
546    ///   caches pointers to both. Fetch a new writer after every reserve.
547    pub unsafe fn key_writer(vector: duckdb_vector) -> VectorWriter {
548        // SAFETY: `keys` only needs a valid MAP vector, which is this function's
549        // `# Safety` contract.
550        let keys = unsafe { Self::keys(vector) };
551        // SAFETY: keys is a valid writable child vector.
552        unsafe { VectorWriter::from_vector(keys) }
553    }
554
555    /// Creates a [`VectorWriter`] for the values vector (STRUCT field 1).
556    ///
557    /// # Safety
558    ///
559    /// - `vector` must be a valid `DuckDB` MAP vector.
560    /// - Every index written must be below the capacity most recently reserved
561    ///   with [`MapVector::reserve`].
562    /// - The writer must not be used after the map is grown again
563    ///   ([`MapVector::reserve`] with a larger capacity, or a
564    ///   [`ListBuilder`](crate::vector::ListBuilder) row that grows it): growing
565    ///   reallocates the child's data and validity buffers, and the writer
566    ///   caches pointers to both. Fetch a new writer after every reserve.
567    pub unsafe fn value_writer(vector: duckdb_vector) -> VectorWriter {
568        // SAFETY: `values` only needs a valid MAP vector, which is this function's
569        // `# Safety` contract.
570        let vals = unsafe { Self::values(vector) };
571        // SAFETY: vals is a valid writable child vector.
572        unsafe { VectorWriter::from_vector(vals) }
573    }
574
575    /// Creates a [`VectorReader`] for the keys vector.
576    ///
577    /// # Safety
578    ///
579    /// - `vector` must be a valid `DuckDB` MAP vector.
580    /// - `element_count` must equal the total number of key-value entries.
581    pub unsafe fn key_reader(vector: duckdb_vector, element_count: usize) -> VectorReader {
582        // SAFETY: `keys` only needs a valid MAP vector, which is this function's
583        // first `# Safety` clause.
584        let keys = unsafe { Self::keys(vector) };
585        // SAFETY: keys is a valid vector with element_count elements.
586        unsafe { VectorReader::from_vector(keys, element_count) }
587    }
588
589    /// Creates a [`VectorReader`] for the values vector.
590    ///
591    /// # Safety
592    ///
593    /// - `vector` must be a valid `DuckDB` MAP vector.
594    /// - `element_count` must equal the total number of key-value entries.
595    pub unsafe fn value_reader(vector: duckdb_vector, element_count: usize) -> VectorReader {
596        // SAFETY: `values` only needs a valid MAP vector, which is this function's
597        // first `# Safety` clause.
598        let vals = unsafe { Self::values(vector) };
599        // SAFETY: vals is a valid vector with element_count elements.
600        unsafe { VectorReader::from_vector(vals, element_count) }
601    }
602}
603
604// ─── ARRAY ──────────────────────────────────────────────────────────────────
605
606/// Helpers for working with `ARRAY` vectors (fixed-size arrays).
607#[derive(Debug)]
608pub struct ArrayVector;
609
610impl ArrayVector {
611    /// Returns the child vector of an array vector.
612    ///
613    /// # Safety
614    ///
615    /// - `vector` must be a valid `DuckDB` ARRAY vector.
616    /// - The returned handle is borrowed from `vector` and must not outlive it.
617    #[inline]
618    #[must_use]
619    pub unsafe fn get_child(vector: duckdb_vector) -> duckdb_vector {
620        // SAFETY: `duckdb_array_vector_get_child` calls `ArrayVector::GetEntry`
621        // (data_chunk-c.cpp), which requires an ARRAY vector; the `# Safety`
622        // contract makes `vector` a valid ARRAY vector.
623        unsafe { duckdb_array_vector_get_child(vector) }
624    }
625}
626
627/// Whether the span `[offset, offset + length)` lies inside a child vector of
628/// `child_len` elements. An overflowing span does not.
629const fn entry_in_bounds(offset: u64, length: u64, child_len: u64) -> bool {
630    match offset.checked_add(length) {
631        Some(end) => end <= child_len,
632        None => false,
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    use super::entry_in_bounds;
639    use libduckdb_sys::duckdb_list_entry;
640
641    /// The span check `get_entry_checked` makes on a row that is not NULL.
642    #[test]
643    fn entry_in_bounds_accepts_exactly_the_spans_inside_the_child() {
644        assert!(entry_in_bounds(0, 0, 0), "an empty list in an empty child");
645        assert!(entry_in_bounds(0, 5, 5), "the whole child");
646        assert!(entry_in_bounds(3, 2, 5), "the last elements");
647        assert!(entry_in_bounds(5, 0, 5), "an empty list at the end");
648        assert!(!entry_in_bounds(0, 6, 5), "one past the end");
649        assert!(!entry_in_bounds(4, 2, 5), "straddling the end");
650        assert!(!entry_in_bounds(6, 0, 5), "an offset past the end");
651        // The shapes of a NULL row's stale entry seen on DuckDB 2.0.0: a huge
652        // length, and a sum that wraps.
653        assert!(!entry_in_bounds(0, 68_951_404_952_617, 33_407));
654        assert!(!entry_in_bounds(u64::MAX, 1, u64::MAX));
655        assert!(!entry_in_bounds(1, u64::MAX, u64::MAX));
656    }
657
658    #[test]
659    fn list_entry_layout() {
660        // Verify duckdb_list_entry has the expected size (2 × u64 = 16 bytes).
661        assert_eq!(
662            core::mem::size_of::<duckdb_list_entry>(),
663            16,
664            "duckdb_list_entry should be {{ offset: u64, length: u64 }}"
665        );
666    }
667}