use crate::builder::ArrayBuilder;
use crate::{ArrayRef, NullArray};
use arrow_data::ArrayData;
use arrow_schema::DataType;
use std::any::Any;
use std::sync::Arc;
#[derive(Debug)]
pub struct NullBuilder {
len: usize,
}
impl Default for NullBuilder {
fn default() -> Self {
Self::new()
}
}
impl NullBuilder {
pub fn new() -> Self {
Self { len: 0 }
}
#[deprecated = "there is no actual notion of capacity in the NullBuilder, so emulating it makes little sense"]
pub fn with_capacity(_capacity: usize) -> Self {
Self::new()
}
#[deprecated = "there is no actual notion of capacity in the NullBuilder, so emulating it makes little sense"]
pub fn capacity(&self) -> usize {
self.len
}
#[inline]
pub fn append_null(&mut self) {
self.len += 1;
}
#[inline]
pub fn append_nulls(&mut self, n: usize) {
self.len += n;
}
#[inline]
pub fn append_empty_value(&mut self) {
self.append_null();
}
#[inline]
pub fn append_empty_values(&mut self, n: usize) {
self.append_nulls(n);
}
pub fn finish(&mut self) -> NullArray {
let len = self.len();
let builder = ArrayData::new_null(&DataType::Null, len).into_builder();
let array_data = unsafe { builder.build_unchecked() };
NullArray::from(array_data)
}
pub fn finish_cloned(&self) -> NullArray {
let len = self.len();
let builder = ArrayData::new_null(&DataType::Null, len).into_builder();
let array_data = unsafe { builder.build_unchecked() };
NullArray::from(array_data)
}
}
impl ArrayBuilder for NullBuilder {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_box_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn len(&self) -> usize {
self.len
}
fn finish(&mut self) -> ArrayRef {
Arc::new(self.finish())
}
fn finish_cloned(&self) -> ArrayRef {
Arc::new(self.finish_cloned())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Array;
#[test]
fn test_null_array_builder() {
let mut builder = NullArray::builder(10);
builder.append_null();
builder.append_nulls(4);
builder.append_empty_value();
builder.append_empty_values(4);
let arr = builder.finish();
assert_eq!(10, arr.len());
assert_eq!(0, arr.offset());
assert_eq!(0, arr.null_count());
assert!(arr.is_nullable());
}
#[test]
fn test_null_array_builder_finish_cloned() {
let mut builder = NullArray::builder(16);
builder.append_null();
builder.append_empty_value();
builder.append_empty_values(3);
let mut array = builder.finish_cloned();
assert_eq!(5, array.len());
builder.append_empty_values(5);
array = builder.finish();
assert_eq!(10, array.len());
}
}