qubit_metadata/from_metadata_value.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Provides conversion from metadata values into supported Rust values.
11
12use std::collections::HashMap;
13use std::time::Duration;
14
15use bigdecimal::BigDecimal;
16use chrono::{
17 DateTime,
18 NaiveDate,
19 NaiveDateTime,
20 NaiveTime,
21 Utc,
22};
23use qubit_value::{
24 Value,
25 ValueResult,
26};
27use url::Url;
28
29/// Converts metadata backing [`Value`] instances into supported Rust types.
30///
31/// This trait is implemented for the same concrete output types accepted by
32/// [`Value::to`]. It keeps metadata accessors generic without depending on
33/// `qubit-value` internal conversion traits.
34pub trait FromMetadataValue: Sized {
35 /// Converts `value` into `Self`.
36 ///
37 /// # Errors
38 ///
39 /// Returns a [`qubit_value::ValueError`] when the stored value is absent,
40 /// unsupported, or cannot be converted to `Self`.
41 fn from_metadata_value(value: &Value) -> ValueResult<Self>;
42}
43
44macro_rules! impl_from_metadata_value {
45 ($($type:ty),+ $(,)?) => {
46 $(
47 impl FromMetadataValue for $type {
48 #[inline]
49 fn from_metadata_value(value: &Value) -> ValueResult<Self> {
50 value.to::<$type>()
51 }
52 }
53 )+
54 };
55}
56
57impl_from_metadata_value!(
58 bool,
59 char,
60 i8,
61 i16,
62 i32,
63 i64,
64 i128,
65 u8,
66 u16,
67 u32,
68 u64,
69 u128,
70 f32,
71 f64,
72 String,
73 NaiveDate,
74 NaiveTime,
75 NaiveDateTime,
76 DateTime<Utc>,
77 num_bigint::BigInt,
78 BigDecimal,
79 isize,
80 usize,
81 Duration,
82 Url,
83 HashMap<String, String>,
84 serde_json::Value,
85);