serde_arrow 0.15.0-rc.1

Convert sequences of Rust objects to Arrow arrays and back again
Documentation
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
413
414
415
416
417
418
419
420
421
use std::{
    backtrace::{Backtrace, BacktraceStatus},
    collections::BTreeMap,
    convert::Infallible,
};

pub fn set_default(
    annotations: &mut BTreeMap<String, String>,
    key: &str,
    value: impl std::fmt::Display,
) {
    if !annotations.contains_key(key) {
        annotations.insert(String::from(key), value.to_string());
    }
}

pub fn prepend(
    annotations: &mut BTreeMap<String, String>,
    key: &str,
    value: impl std::fmt::Display,
) {
    if let Some(prev) = annotations.get_mut(key) {
        *prev = format!("{}.{}", value, prev);
    } else {
        annotations.insert(String::from(key), value.to_string());
    }
}

pub struct FieldName<'a>(pub &'a str);

impl std::fmt::Display for FieldName<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if !self.0.is_empty() {
            std::fmt::Display::fmt(self.0, f)
        } else {
            write!(f, "<empty>")
        }
    }
}

/// Execute a faillible function and return the result
///
/// This function is mostly useful to add annotations to a complex block of operations
pub fn try_<T>(func: impl FnOnce() -> Result<T>) -> Result<T> {
    func()
}

/// An object that offers additional context to an error
pub trait Context {
    fn annotate(&self, annotations: &mut BTreeMap<String, String>);
}

impl Context for BTreeMap<String, String> {
    fn annotate(&self, annotations: &mut BTreeMap<String, String>) {
        for (k, v) in self {
            if !annotations.contains_key(k) {
                annotations.insert(k.to_owned(), v.to_owned());
            }
        }
    }
}

/// Helpers to attach the metadata associated with a context to an error
pub trait ContextSupport {
    type Output;

    fn ctx<C: Context>(self, context: &C) -> Self::Output;
}

impl<T, E: Into<Error>> ContextSupport for Result<T, E> {
    type Output = Result<T, Error>;

    fn ctx<C: Context>(self, context: &C) -> Self::Output {
        match self {
            Ok(value) => Ok(value),
            Err(err) => Err(err.ctx(context)),
        }
    }
}

impl<E: Into<Error>> ContextSupport for E {
    type Output = Error;

    fn ctx<C: Context>(self, context: &C) -> Self::Output {
        let mut err = self.into();
        context.annotate(&mut err.inner.annotations);
        err
    }
}

/// A Result type that defaults to `serde_arrow`'s [Error] type
///
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Common errors during `serde_arrow`'s usage
///
/// The error carries a backtrace if `RUST_BACKTRACE=1`, see [`std::backtrace`] for details. This
/// backtrace is included when printing the error. If the error is caused by another error, that
/// error can be retrieved with [`source()`][std::error::Error::source].
///
/// # Display representation
///
/// This error type follows anyhow's display representation: when printed with display format (`{}`)
/// (or converted to string) the error does not include a backtrace. Use the debug format (`{:?}`)
/// to include the backtrace information.
///
pub struct Error {
    pub(crate) inner: Box<ErrorInner>,
}

pub(crate) struct ErrorInner {
    kind: ErrorKind,
    message: String,
    backtrace: Box<Backtrace>,
    cause: Option<Box<dyn std::error::Error + Send + Sync>>,
    pub(crate) annotations: BTreeMap<String, String>,
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        self.inner.kind == other.inner.kind
            && self.inner.message == other.inner.message
            && self.inner.annotations == other.inner.annotations
    }
}

/// Classifies an error for pattern matching
///
/// Use [`Error::kind()`] to get the kind of an error for matching.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// A generic error with a custom message
    Custom,
    /// Attempted to write null to a non-nullable field
    NullabilityViolation {
        /// The field name, if known
        field: Option<String>,
    },
    /// Missing required field in struct
    MissingField {
        /// The name of the missing field
        field: String,
    },
}

/// Error creation
impl Error {
    pub fn new(kind: ErrorKind, message: String) -> Self {
        Self {
            inner: Box::new(ErrorInner {
                kind,
                message,
                backtrace: Box::new(Backtrace::capture()),
                cause: None,
                annotations: BTreeMap::new(),
            }),
        }
    }

    pub fn new_from<E: std::error::Error + Send + Sync + 'static>(
        kind: ErrorKind,
        message: String,
        cause: E,
    ) -> Self {
        let mut err = Self::new(kind, message);
        err.inner.cause = Some(Box::new(cause));
        err
    }
}

/// Access information about the error
impl Error {
    /// Get the error message
    pub fn message(&self) -> &str {
        &self.inner.message
    }

    pub fn backtrace(&self) -> &Backtrace {
        &self.inner.backtrace
    }

    /// Get a reference to the annotations of this error
    pub(crate) fn annotations(&self) -> Option<&BTreeMap<String, String>> {
        Some(&self.inner.annotations)
    }

    pub(crate) fn modify_message<F: FnOnce(&mut String)>(&mut self, func: F) {
        func(&mut self.inner.message);
    }

    /// Get the kind of this error for pattern matching
    pub fn kind(&self) -> &ErrorKind {
        &self.inner.kind
    }
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Error: {msg}{annotations}\n{bt}",
            msg = self.message(),
            annotations = AnnotationsDisplay(self.annotations()),
            bt = BacktraceDisplay(self.backtrace()),
        )
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Error: {msg}{annotations}",
            msg = self.message(),
            annotations = AnnotationsDisplay(self.annotations()),
        )
    }
}

struct AnnotationsDisplay<'a>(Option<&'a BTreeMap<String, String>>);

impl std::fmt::Display for AnnotationsDisplay<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Some(annotations) = self.0 else {
            return Ok(());
        };
        if annotations.is_empty() {
            return Ok(());
        }

        write!(f, " (")?;
        for (idx, (key, value)) in annotations.iter().enumerate() {
            if idx != 0 {
                write!(f, ", ")?;
            }
            write!(f, "{key}: {value:?}")?;
        }
        write!(f, ")")
    }
}

struct BacktraceDisplay<'a>(&'a Backtrace);

impl std::fmt::Display for BacktraceDisplay<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0.status() {
            BacktraceStatus::Captured => write!(f, "Backtrace:\n{bt}", bt=self.0),
            BacktraceStatus::Disabled => write!(f, "Backtrace not captured; set the `RUST_BACKTRACE=1` env variable to enable"),
            _ => write!(f, "Backtrace not captured: most likely backtraces are not supported on the current platform"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.inner.cause.as_ref()?.as_ref())
    }
}

impl serde::ser::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: std::fmt::Display,
    {
        Self::new(ErrorKind::Custom, format!("serialization failed: {msg}"))
    }
}

impl serde::de::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: std::fmt::Display,
    {
        Self::new(ErrorKind::Custom, format!("deserialization failed: {msg}"))
    }
}

macro_rules! fail {
    // TODO: Remove context support. Context should only be added add specified recursion points in
    // serializers or deserializers making this macro form obsolete
    (in $context:expr, $($tt:tt)*) => {
        {
            #[allow(unused, reason = "simplify macro")]
            use $crate::internal::error::Context;
            let mut err = $crate::internal::error::Error::new($crate::internal::error::ErrorKind::Custom, format!($($tt)*));
            $context.annotate(&mut err.inner.annotations);
            return Err(err);
        }
    };
    ($($tt:tt)*) => {
        return Err($crate::internal::error::Error::new($crate::internal::error::ErrorKind::Custom, format!($($tt)*)))
    };
}

pub(crate) use fail;

impl From<marrow::error::MarrowError> for Error {
    fn from(err: marrow::error::MarrowError) -> Self {
        Self::new_from(
            ErrorKind::Custom,
            format!("failed to convert Arrow data: {err}"),
            err,
        )
    }
}

impl From<chrono::format::ParseError> for Error {
    fn from(err: chrono::format::ParseError) -> Self {
        Self::new_from(
            ErrorKind::Custom,
            format!("failed to parse date or time: {err}"),
            err,
        )
    }
}

impl From<std::char::CharTryFromError> for Error {
    fn from(err: std::char::CharTryFromError) -> Error {
        Self::new_from(
            ErrorKind::Custom,
            format!("failed to convert integer to character: {err}"),
            err,
        )
    }
}

impl From<std::char::TryFromCharError> for Error {
    fn from(err: std::char::TryFromCharError) -> Error {
        Self::new_from(
            ErrorKind::Custom,
            format!("failed to convert character to integer: {err}"),
            err,
        )
    }
}

impl From<std::num::TryFromIntError> for Error {
    fn from(err: std::num::TryFromIntError) -> Error {
        Self::new_from(
            ErrorKind::Custom,
            format!("integer conversion failed: {err}"),
            err,
        )
    }
}

impl From<std::num::ParseIntError> for Error {
    fn from(err: std::num::ParseIntError) -> Self {
        Self::new_from(
            ErrorKind::Custom,
            format!("failed to parse integer: {err}"),
            err,
        )
    }
}

impl From<std::num::ParseFloatError> for Error {
    fn from(err: std::num::ParseFloatError) -> Self {
        Self::new_from(
            ErrorKind::Custom,
            format!("failed to parse floating-point value: {err}"),
            err,
        )
    }
}

impl From<std::fmt::Error> for Error {
    fn from(err: std::fmt::Error) -> Self {
        Self::new_from(ErrorKind::Custom, format!("formatting failed: {err}"), err)
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(err: std::str::Utf8Error) -> Self {
        Self::new_from(ErrorKind::Custom, format!("invalid UTF-8 data: {err}"), err)
    }
}

impl From<Infallible> for Error {
    fn from(_: Infallible) -> Self {
        unreachable!()
    }
}

impl From<bytemuck::PodCastError> for Error {
    fn from(err: bytemuck::PodCastError) -> Self {
        // Note: bytemuck::PodCastError does not implement std::error::Error
        Self::new(ErrorKind::Custom, format!("byte cast failed: {err}"))
    }
}

pub type PanicOnError<T> = std::result::Result<T, PanicOnErrorError>;

/// An error type for testing, that panics once an error is converted
#[derive(Debug)]
pub struct PanicOnErrorError;

// use Display to not match PanicOnErrorError itself, use Debug for printing to include stacktrace
impl<E: std::fmt::Display + std::fmt::Debug> From<E> for PanicOnErrorError {
    #[allow(clippy::panic, reason = "PanicOnErrorError is only used in tests")]
    fn from(value: E) -> Self {
        panic!("{value:?}");
    }
}

#[test]
fn error_can_be_converted_to_anyhow() {
    fn func() -> anyhow::Result<()> {
        Err(Error::new(ErrorKind::Custom, "dummy".to_string()))?;
        Ok(())
    }
    assert!(func().is_err());
}

#[allow(unused, reason = "trait assertions")]
const _: () = {
    trait AssertSendSync: Send + Sync {}
    impl AssertSendSync for Error {}
    impl<T: Send + Sync> AssertSendSync for Result<T> {}
};