1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
use arrow::{
array::{
Array, ArrayRef, ArrowPrimitiveType, BooleanArray, FixedSizeListArray, ListArray,
PrimitiveArray, UInt32Array,
},
buffer::{NullBuffer, OffsetBuffer},
datatypes::{DataType, Field},
error::ArrowError,
};
use itertools::Itertools as _;
// ---------------------------------------------------------------------------------
/// Downcast an arrow array to another array, without having to go via `Any`.
pub trait ArrowArrayDowncastRef<'a>: 'a {
/// Downcast an arrow array to another array, without having to go via `Any`.
fn downcast_array_ref<T: Array + 'static>(self) -> Option<&'a T>;
}
impl<'a> ArrowArrayDowncastRef<'a> for &'a dyn Array {
fn downcast_array_ref<T: Array + 'static>(self) -> Option<&'a T> {
self.as_any().downcast_ref()
}
}
impl<'a> ArrowArrayDowncastRef<'a> for &'a ArrayRef {
fn downcast_array_ref<T: Array + 'static>(self) -> Option<&'a T> {
self.as_any().downcast_ref()
}
}
// ---------------------------------------------------------------------------------
#[inline]
pub fn into_arrow_ref(array: impl Array + 'static) -> ArrayRef {
std::sync::Arc::new(array)
}
/// Returns an iterator with the lengths of the offsets.
pub fn offsets_lengths(
offsets: &arrow::buffer::OffsetBuffer<i32>,
) -> impl Iterator<Item = usize> + '_ {
// TODO(emilk): remove when we update to Arrow 54 (which has an API for this)
offsets.windows(2).map(|w| {
let start = w[0];
let end = w[1];
debug_assert!(
start <= end && 0 <= start,
"Bad arrow offset buffer: {start}, {end}"
);
end.saturating_sub(start).max(0) as usize
})
}
/// Repartitions a [`ListArray`] according to the specified `lengths`, ignoring previous partitioning.
///
/// The specified `lengths` must sum to the total length underlying values (i.e. the child array).
///
/// The validity of the values is ignored.
#[inline]
pub fn repartition_list_array(
list_array: ListArray,
lengths: impl IntoIterator<Item = usize>,
) -> arrow::error::Result<ListArray> {
let (field, _offsets, values, _nulls) = list_array.into_parts();
let offsets = OffsetBuffer::from_lengths(lengths);
let nulls = None;
ListArray::try_new(field, offsets, values, nulls)
}
/// Returns true if the given `list_array` is semantically empty.
///
/// Semantic emptiness is defined as either one of these:
/// * The list is physically empty (literally no data).
/// * The list only contains null entries, or empty arrays, or a mix of both.
#[inline]
pub fn is_list_array_semantically_empty(list_array: &ListArray) -> bool {
list_array.values().is_empty()
}
/// Create a sparse list-array out of an array of arrays.
///
/// All arrays must have the same datatype.
///
/// Returns `None` if `arrays` is empty.
#[inline]
pub fn arrays_to_list_array_opt(arrays: &[Option<&dyn Array>]) -> Option<ListArray> {
let datatype = arrays
.iter()
.flatten()
.map(|array| array.data_type().clone())
.next()?;
arrays_to_list_array(datatype, arrays)
}
/// An empty array of the given datatype.
// TODO(#3741): replace with `arrow::array::new_empty_array`
pub fn new_empty_array(datatype: &DataType) -> ArrayRef {
let capacity = 0;
arrow::array::make_builder(datatype, capacity).finish()
}
/// Create a sparse list-array out of an array of arrays.
///
/// Returns `None` if any of the specified `arrays` doesn't match the given `array_datatype`.
///
/// Returns an empty list if `arrays` is empty.
pub fn arrays_to_list_array(
array_datatype: DataType,
arrays: &[Option<&dyn Array>],
) -> Option<ListArray> {
let arrays_dense = arrays.iter().flatten().copied().collect_vec();
let data = if arrays_dense.is_empty() {
new_empty_array(&array_datatype)
} else {
re_tracing::profile_scope!("concatenate", arrays_dense.len().to_string());
concat_arrays(&arrays_dense)
.map_err(|err| {
re_log::warn_once!("failed to concatenate arrays: {err}");
err
})
.ok()?
};
let nullable = true;
let field = Field::new_list_field(array_datatype, nullable);
let offsets = OffsetBuffer::from_lengths(
arrays
.iter()
.map(|array| array.map_or(0, |array| array.len())),
);
#[allow(clippy::from_iter_instead_of_collect)]
let nulls = NullBuffer::from_iter(arrays.iter().map(Option::is_some));
Some(ListArray::new(field.into(), offsets, data, nulls.into()))
}
/// Given a sparse [`ListArray`] (i.e. an array with a nulls bitmap that contains at least
/// one falsy value), returns a dense [`ListArray`] that only contains the non-null values from
/// the original list.
///
/// This is a no-op if the original array is already dense.
pub fn sparse_list_array_to_dense_list_array(list_array: &ListArray) -> ListArray {
if list_array.is_empty() {
return list_array.clone();
}
let is_empty = list_array.nulls().is_some_and(|nulls| nulls.is_empty());
if is_empty {
return list_array.clone();
}
let offsets = OffsetBuffer::from_lengths(list_array.iter().flatten().map(|array| array.len()));
let fields = list_array_fields(list_array);
ListArray::new(fields, offsets, list_array.values().clone(), None)
}
fn list_array_fields(list_array: &arrow::array::GenericListArray<i32>) -> std::sync::Arc<Field> {
match list_array.data_type() {
DataType::List(fields) | DataType::LargeList(fields) => fields,
_ => unreachable!("The GenericListArray constructor guaranteed we can't get here"),
}
.clone()
}
/// Create a new [`ListArray`] of target length by appending null values to its back.
///
/// This will share the same child data array buffer, but will create new offset and nulls buffers.
pub fn pad_list_array_back(list_array: &ListArray, target_len: usize) -> ListArray {
let missing_len = target_len.saturating_sub(list_array.len());
if missing_len == 0 {
return list_array.clone();
}
let fields = list_array_fields(list_array);
let offsets = {
OffsetBuffer::from_lengths(
list_array
.iter()
.map(|array| array.map_or(0, |array| array.len()))
.chain(std::iter::repeat(0).take(missing_len)),
)
};
let values = list_array.values().clone();
let nulls = {
if let Some(nulls) = list_array.nulls() {
#[allow(clippy::from_iter_instead_of_collect)]
NullBuffer::from_iter(
nulls
.iter()
.chain(std::iter::repeat(false).take(missing_len)),
)
} else {
#[allow(clippy::from_iter_instead_of_collect)]
NullBuffer::from_iter(
std::iter::repeat(true)
.take(list_array.len())
.chain(std::iter::repeat(false).take(missing_len)),
)
}
};
ListArray::new(fields, offsets, values, Some(nulls))
}
/// Create a new [`ListArray`] of target length by appending null values to its front.
///
/// This will share the same child data array buffer, but will create new offset and nulls buffers.
pub fn pad_list_array_front(list_array: &ListArray, target_len: usize) -> ListArray {
let missing_len = target_len.saturating_sub(list_array.len());
if missing_len == 0 {
return list_array.clone();
}
let fields = list_array_fields(list_array);
let offsets = {
OffsetBuffer::from_lengths(
std::iter::repeat(0).take(missing_len).chain(
list_array
.iter()
.map(|array| array.map_or(0, |array| array.len())),
),
)
};
let values = list_array.values().clone();
let nulls = {
if let Some(nulls) = list_array.nulls() {
#[allow(clippy::from_iter_instead_of_collect)]
NullBuffer::from_iter(
std::iter::repeat(false)
.take(missing_len)
.chain(nulls.iter()),
)
} else {
#[allow(clippy::from_iter_instead_of_collect)]
NullBuffer::from_iter(
std::iter::repeat(false)
.take(missing_len)
.chain(std::iter::repeat(true).take(list_array.len())),
)
}
};
ListArray::new(fields, offsets, values, Some(nulls))
}
/// Returns a new [[`ListArray`]] with len `entries`.
///
/// Each entry will be an empty array of the given `child_datatype`.
pub fn new_list_array_of_empties(child_datatype: &DataType, len: usize) -> ListArray {
let empty_array = new_empty_array(child_datatype);
let offsets = OffsetBuffer::from_lengths(std::iter::repeat(0).take(len));
let nullable = true;
ListArray::new(
Field::new_list_field(empty_array.data_type().clone(), nullable).into(),
offsets,
empty_array,
None,
)
}
/// Applies a [`arrow::compute::concat`] kernel to the given `arrays`.
///
/// Early outs where it makes sense (e.g. `arrays.len() == 1`).
///
/// Returns an error if the arrays don't share the exact same datatype.
pub fn concat_arrays(arrays: &[&dyn Array]) -> arrow::error::Result<ArrayRef> {
#[allow(clippy::disallowed_methods)] // that's the whole point
let mut array = arrow::compute::concat(arrays)?;
array.shrink_to_fit(); // VERY IMPORTANT! https://github.com/rerun-io/rerun/issues/7222
Ok(array)
}
/// Applies a [filter] kernel to the given `array`.
///
/// Panics iff the length of the filter doesn't match the length of the array.
///
/// In release builds, filters are allowed to have null entries (they will be interpreted as `false`).
/// In debug builds, null entries will panic.
///
/// Note: a `filter` kernel _copies_ the data in order to make the resulting arrays contiguous in memory.
///
/// Takes care of up- and down-casting the data back and forth on behalf of the caller.
///
/// [filter]: arrow::compute::filter
pub fn filter_array<A: Array + Clone + 'static>(array: &A, filter: &BooleanArray) -> A {
assert_eq!(
array.len(), filter.len(),
"the length of the filter must match the length of the array (the underlying kernel will panic otherwise)",
);
debug_assert!(
filter.nulls().is_none(),
"filter masks with nulls bits are technically valid, but generally a sign that something went wrong",
);
#[allow(clippy::disallowed_methods)] // that's the whole point
#[allow(clippy::unwrap_used)]
let mut array = arrow::compute::filter(array, filter)
// Unwrap: this literally cannot fail.
.unwrap()
.as_any()
.downcast_ref::<A>()
// Unwrap: that's initial type that we got.
.unwrap()
.clone();
array.shrink_to_fit(); // VERY IMPORTANT! https://github.com/rerun-io/rerun/issues/7222
array
}
/// Applies a [take] kernel to the given `array`.
///
/// In release builds, indices are allowed to have null entries (they will be taken as `null`s).
/// In debug builds, null entries will panic.
///
/// Note: a `take` kernel _copies_ the data in order to make the resulting arrays contiguous in memory.
///
/// Takes care of up- and down-casting the data back and forth on behalf of the caller.
///
/// [take]: arrow::compute::take
//
// TODO(cmc): in an ideal world, a `take` kernel should merely _slice_ the data and avoid any allocations/copies
// where possible (e.g. list-arrays).
// That is not possible with vanilla [`ListArray`]s since they don't expose any way to encode optional lengths,
// in addition to offsets.
// For internal stuff, we could perhaps provide a custom implementation that returns a `DictionaryArray` instead?
pub fn take_array<A, O>(array: &A, indices: &PrimitiveArray<O>) -> A
where
A: Array + Clone + 'static,
O: ArrowPrimitiveType,
O::Native: std::ops::Add<Output = O::Native>,
{
use arrow::datatypes::ArrowNativeTypeOp as _;
debug_assert!(
indices.nulls().is_none(),
"index arrays with nulls bits are technically valid, but generally a sign that something went wrong",
);
if indices.len() == array.len() {
let indices = indices.values();
let starts_at_zero = || indices[0] == O::Native::ZERO;
let is_consecutive = || {
indices
.windows(2)
.all(|values| values[1] == values[0] + O::Native::ONE)
};
if starts_at_zero() && is_consecutive() {
#[allow(clippy::unwrap_used)]
return array
.clone()
.as_any()
.downcast_ref::<A>()
// Unwrap: that's initial type that we got.
.unwrap()
.clone();
}
}
#[allow(clippy::disallowed_methods)] // that's the whole point
#[allow(clippy::unwrap_used)]
let mut array = arrow::compute::take(array, indices, Default::default())
// Unwrap: this literally cannot fail.
.unwrap()
.as_any()
.downcast_ref::<A>()
// Unwrap: that's initial type that we got.
.unwrap()
.clone();
array.shrink_to_fit(); // VERY IMPORTANT! https://github.com/rerun-io/rerun/issues/7222
array
}
/// Extract the element at `idx` from a `FixedSizeListArray`.
///
/// For example:
/// `[[1, 2], [3, 4], [5, 6]] -> [1, 3, 5]`
pub fn extract_fixed_size_array_element(
data: &FixedSizeListArray,
idx: u32,
) -> Result<ArrayRef, ArrowError> {
let num_elements = data.value_length() as u32;
let num_values = data.len() as u32;
let indices = UInt32Array::from(
(0..num_values)
.map(|i| i * num_elements + idx)
.collect::<Vec<_>>(),
);
// We have forbidden using arrow::take, but it really is what we want here
// `take_array` results in an unwrap so it appears not to be the right choice.
// TODO(jleibs): Follow up with cmc on if there's a different way to do this.
#[allow(clippy::disallowed_methods)]
arrow::compute::kernels::take::take(data.values(), &indices, None)
}