Skip to main content

qubit_value/value/
value_getter.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! `TryFrom<&Value>` implementations for strict typed reads.
10
11use super::value::{
12    Value,
13    ValueRepr,
14};
15use crate::ValueMissing;
16use crate::value_error::{
17    ValueError,
18    ValueResult,
19};
20
21macro_rules! impl_value_try_from_table {
22    (
23        ;
24        $(
25            (
26                [$($cfg:meta),*],
27                $variant:ident,
28                $type:ty,
29                $data_type:expr,
30                $materialization:ident,
31                $json_class:ident,
32                $number_projection:ident,
33                $value_doc:literal,
34                $multi_doc:literal
35            )
36        ),+ $(,)?
37    ) => {
38        $(
39            $(#[$cfg])*
40            impl TryFrom<&Value> for $type {
41                type Error = ValueError;
42
43                #[inline(always)]
44                fn try_from(value: &Value) -> ValueResult<$type> {
45                    match &value.repr {
46                        ValueRepr::$variant(value) => {
47                            Ok(materialize_value_storage!($variant, $materialization, value))
48                        }
49                        ValueRepr::Unset(actual) if *actual == $data_type => {
50                            Err(ValueError::Missing(ValueMissing::UnsetScalar {
51                                data_type: *actual,
52                            }))
53                        }
54                        _ => Err(ValueError::TypeMismatch {
55                            expected: $data_type,
56                            actual: value.data_type(),
57                        }),
58                    }
59                }
60            }
61        )+
62    };
63}
64
65for_each_value_type!(impl_value_try_from_table);