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::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
17use qubit_value::{Value, ValueResult};
18use url::Url;
19
20/// Converts metadata backing [`Value`] instances into supported Rust types.
21///
22/// This trait is implemented for the same concrete output types accepted by
23/// [`Value::to`]. It keeps metadata accessors generic without depending on
24/// `qubit-value` internal conversion traits.
25pub trait FromMetadataValue: Sized {
26 /// Converts `value` into `Self`.
27 ///
28 /// # Errors
29 ///
30 /// Returns a [`qubit_value::ValueError`] when the stored value is absent,
31 /// unsupported, or cannot be converted to `Self`.
32 fn from_metadata_value(value: &Value) -> ValueResult<Self>;
33}
34
35macro_rules! impl_from_metadata_value {
36 ($($type:ty),+ $(,)?) => {
37 $(
38 impl FromMetadataValue for $type {
39 #[inline]
40 fn from_metadata_value(value: &Value) -> ValueResult<Self> {
41 value.to::<$type>()
42 }
43 }
44 )+
45 };
46}
47
48impl_from_metadata_value!(
49 bool,
50 char,
51 i8,
52 i16,
53 i32,
54 i64,
55 i128,
56 u8,
57 u16,
58 u32,
59 u64,
60 u128,
61 f32,
62 f64,
63 String,
64 NaiveDate,
65 NaiveTime,
66 NaiveDateTime,
67 DateTime<Utc>,
68 num_bigint::BigInt,
69 BigDecimal,
70 isize,
71 usize,
72 Duration,
73 Url,
74 HashMap<String, String>,
75 serde_json::Value,
76);