Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions arrow-json/src/reader/string_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use arrow_array::{Array, GenericStringArray, OffsetSizeTrait};
use arrow_data::ArrayData;
use arrow_schema::ArrowError;
use std::marker::PhantomData;
use std::io::Write;

use crate::reader::tape::{Tape, TapeElement};
use crate::reader::ArrayDecoder;
Expand All @@ -30,15 +31,25 @@ const FALSE: &str = "false";
pub struct StringArrayDecoder<O: OffsetSizeTrait> {
coerce_primitive: bool,
phantom: PhantomData<O>,
number_buffer: Vec<u8>,
}

impl<O: OffsetSizeTrait> StringArrayDecoder<O> {
pub fn new(coerce_primitive: bool) -> Self {
Self {
coerce_primitive,
phantom: Default::default(),
number_buffer: Vec::with_capacity(32),
}
}

fn write_number<T: std::fmt::Display>(&mut self, n: T) -> &str {
self.number_buffer.clear();
write!(&mut self.number_buffer, "{}", n).unwrap();
// SAFETY: We only write ASCII characters (digits, signs, decimal points,
// exponent symbols) into `number_buffer`, which are guaranteed valid UTF-8.
unsafe { std::str::from_utf8_unchecked(&self.number_buffer) }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can avoid unsafe here by using

    number_buffer: String,

This is similar to how @zhuqi-lucas did it here:

        // Temporary buffer to avoid per-iteration allocation for numeric types
        let mut tmp_buf = String::new();
...

}
}

impl<O: OffsetSizeTrait> ArrayDecoder for StringArrayDecoder<O> {
Expand Down Expand Up @@ -103,20 +114,24 @@ impl<O: OffsetSizeTrait> ArrayDecoder for StringArrayDecoder<O> {
TapeElement::I64(high) if coerce_primitive => match tape.get(p + 1) {
TapeElement::I32(low) => {
let val = ((high as i64) << 32) | (low as u32) as i64;
builder.append_value(val.to_string());
let s = self.write_number(val);
builder.append_value(s);
}
_ => unreachable!(),
},
TapeElement::I32(n) if coerce_primitive => {
builder.append_value(n.to_string());
let s = self.write_number(n);
builder.append_value(s);
}
TapeElement::F32(n) if coerce_primitive => {
builder.append_value(n.to_string());
let s = self.write_number(n);
builder.append_value(s);
}
TapeElement::F64(high) if coerce_primitive => match tape.get(p + 1) {
TapeElement::F32(low) => {
let val = f64::from_bits(((high as u64) << 32) | low as u64);
builder.append_value(val.to_string());
let s = self.write_number(val);
builder.append_value(s);
}
_ => unreachable!(),
},
Expand Down