Skip to main content

arrow_array/
trusted_len.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow_buffer::{ArrowNativeType, Buffer, MutableBuffer, bit_util};
6
7/// Creates two [`Buffer`]s from an iterator of `Option`.
8/// The first buffer corresponds to a bitmap buffer, the second one
9/// corresponds to a values buffer.
10/// # Safety
11/// The caller must ensure that `iterator` is `TrustedLen`.
12#[inline]
13pub(crate) unsafe fn trusted_len_unzip<I, P, T>(iterator: I) -> (Buffer, Buffer)
14where
15    T: ArrowNativeType,
16    P: std::borrow::Borrow<Option<T>>,
17    I: Iterator<Item = P>,
18{
19    let (_, upper) = iterator.size_hint();
20    let upper = upper.expect("trusted_len_unzip requires an upper limit");
21    let len = upper * std::mem::size_of::<T>();
22
23    let mut null = MutableBuffer::from_len_zeroed(upper.saturating_add(7) / 8);
24    let mut buffer = MutableBuffer::new(len);
25
26    let dst_null = null.as_mut_ptr();
27    let mut dst = buffer.as_mut_ptr().cast::<T>();
28    for (i, item) in iterator.enumerate() {
29        let item = item.borrow();
30        if let Some(item) = item {
31            unsafe { std::ptr::write(dst, *item) };
32            unsafe { bit_util::set_bit_raw(dst_null, i) };
33        } else {
34            unsafe { std::ptr::write(dst, T::default()) };
35        }
36        dst = unsafe { dst.add(1) };
37    }
38    assert_eq!(
39        unsafe { dst.offset_from(buffer.as_ptr().cast::<T>()) as usize },
40        upper,
41        "Trusted iterator length was not accurately reported"
42    );
43    unsafe { buffer.set_len(len) };
44    (null.into(), buffer.into())
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn trusted_len_unzip_good() {
53        let vec = [Some(1u32), None];
54        let (null, buffer) = unsafe { trusted_len_unzip(vec.iter()) };
55        assert_eq!(null.as_slice(), &[0b00000001]);
56        assert_eq!(buffer.as_slice(), &[1u8, 0, 0, 0, 0, 0, 0, 0]);
57    }
58
59    #[test]
60    #[should_panic(expected = "trusted_len_unzip requires an upper limit")]
61    fn trusted_len_unzip_panic() {
62        let iter = std::iter::repeat(Some(4i32));
63        unsafe { trusted_len_unzip(iter) };
64    }
65}