arrow_json/reader/
primitive_array.rs

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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use num::NumCast;
use std::marker::PhantomData;

use arrow_array::builder::PrimitiveBuilder;
use arrow_array::{Array, ArrowPrimitiveType};
use arrow_cast::parse::Parser;
use arrow_data::ArrayData;
use arrow_schema::{ArrowError, DataType};
use half::f16;

use crate::reader::tape::{Tape, TapeElement};
use crate::reader::ArrayDecoder;

/// A trait for JSON-specific primitive parsing logic
///
/// According to the specification unquoted fields should be parsed as a double-precision
/// floating point numbers, including scientific representation such as `2e3`
///
/// In practice, it is common to serialize numbers outside the range of an `f64` and expect
/// them to round-trip correctly. As such when parsing integers we first parse as the integer
/// and fallback to parsing as a floating point if this fails
trait ParseJsonNumber: Sized {
    fn parse(s: &[u8]) -> Option<Self>;
}

macro_rules! primitive_parse {
    ($($t:ty),+) => {
        $(impl ParseJsonNumber for $t {
            fn parse(s: &[u8]) -> Option<Self> {
                match lexical_core::parse::<Self>(s) {
                    Ok(f) => Some(f),
                    Err(_) => lexical_core::parse::<f64>(s).ok().and_then(NumCast::from),
                }
            }
        })+
    };
}

primitive_parse!(i8, i16, i32, i64, u8, u16, u32, u64);

impl ParseJsonNumber for f16 {
    fn parse(s: &[u8]) -> Option<Self> {
        lexical_core::parse::<f32>(s).ok().map(f16::from_f32)
    }
}

impl ParseJsonNumber for f32 {
    fn parse(s: &[u8]) -> Option<Self> {
        lexical_core::parse::<Self>(s).ok()
    }
}

impl ParseJsonNumber for f64 {
    fn parse(s: &[u8]) -> Option<Self> {
        lexical_core::parse::<Self>(s).ok()
    }
}

pub struct PrimitiveArrayDecoder<P: ArrowPrimitiveType> {
    data_type: DataType,
    // Invariant and Send
    phantom: PhantomData<fn(P) -> P>,
}

impl<P: ArrowPrimitiveType> PrimitiveArrayDecoder<P> {
    pub fn new(data_type: DataType) -> Self {
        Self {
            data_type,
            phantom: Default::default(),
        }
    }
}

impl<P> ArrayDecoder for PrimitiveArrayDecoder<P>
where
    P: ArrowPrimitiveType + Parser,
    P::Native: ParseJsonNumber + NumCast,
{
    fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayData, ArrowError> {
        let mut builder =
            PrimitiveBuilder::<P>::with_capacity(pos.len()).with_data_type(self.data_type.clone());
        let d = &self.data_type;

        for p in pos {
            match tape.get(*p) {
                TapeElement::Null => builder.append_null(),
                TapeElement::String(idx) => {
                    let s = tape.get_string(idx);
                    let value = P::parse(s).ok_or_else(|| {
                        ArrowError::JsonError(format!("failed to parse \"{s}\" as {d}",))
                    })?;

                    builder.append_value(value)
                }
                TapeElement::Number(idx) => {
                    let s = tape.get_string(idx);
                    let value = ParseJsonNumber::parse(s.as_bytes()).ok_or_else(|| {
                        ArrowError::JsonError(format!("failed to parse {s} as {d}",))
                    })?;

                    builder.append_value(value)
                }
                TapeElement::F32(v) => {
                    let v = f32::from_bits(v);
                    let value = NumCast::from(v).ok_or_else(|| {
                        ArrowError::JsonError(format!("failed to parse {v} as {d}",))
                    })?;
                    builder.append_value(value)
                }
                TapeElement::I32(v) => {
                    let value = NumCast::from(v).ok_or_else(|| {
                        ArrowError::JsonError(format!("failed to parse {v} as {d}",))
                    })?;
                    builder.append_value(value)
                }
                TapeElement::F64(high) => match tape.get(p + 1) {
                    TapeElement::F32(low) => {
                        let v = f64::from_bits((high as u64) << 32 | low as u64);
                        let value = NumCast::from(v).ok_or_else(|| {
                            ArrowError::JsonError(format!("failed to parse {v} as {d}",))
                        })?;
                        builder.append_value(value)
                    }
                    _ => unreachable!(),
                },
                TapeElement::I64(high) => match tape.get(p + 1) {
                    TapeElement::I32(low) => {
                        let v = (high as i64) << 32 | (low as u32) as i64;
                        let value = NumCast::from(v).ok_or_else(|| {
                            ArrowError::JsonError(format!("failed to parse {v} as {d}",))
                        })?;
                        builder.append_value(value)
                    }
                    _ => unreachable!(),
                },
                _ => return Err(tape.error(*p, "primitive")),
            }
        }

        Ok(builder.finish().into_data())
    }
}