qubit-datatype 0.8.0

Runtime data type descriptors and conversion utilities for Rust
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! # Reusable Data Conversion
//!
//! Defines the public source wrapper and delegates target families to focused
//! conversion modules.

use std::borrow::Cow;
use std::collections::HashMap;
use std::time::Duration;

#[cfg(feature = "big-decimal")]
use bigdecimal::BigDecimal;
#[cfg(feature = "chrono")]
use chrono::{
    DateTime,
    NaiveDate,
    NaiveDateTime,
    NaiveTime,
    Utc,
};
#[cfg(feature = "big-integer")]
use num_bigint::BigInt;
#[cfg(feature = "url")]
use url::Url;

use super::data_conversion_target::DataConversionTarget;
use super::error::{
    DataConversionError,
    InvalidValueReason,
};
use super::options::DataConversionOptions;
use crate::datatype::{
    DataType,
    for_each_data_type_mapping,
};

mod boolean;
mod duration;
mod internal;
mod numeric;
mod source;
mod string_source;
mod structured;
mod text;

macro_rules! data_converter_data_type_match {
    ($value:expr; $( $(#[$meta:meta])* ($variant:ident, $source:ty, $strategy:ident) ),+ $(,)?) => {
        match $value {
            Self::Unset(data_type) => *data_type,
            $(
                $(#[$meta])*
                Self::$variant(_) => DataType::$variant,
            )+
        }
    };
}

/// A borrowed-or-owned runtime source value for policy-driven conversion.
///
/// `DataConverter` erases the concrete Rust source type while preserving its
/// [`DataType`]. Construct one with a standard [`From`] conversion, then call
/// [`Self::to`] for the default profile or [`Self::to_with`] for an explicit
/// [`DataConversionOptions`] profile. `Cow`-backed variants borrow large values
/// when possible, so wrapping a string, big number, URL, map, or JSON value
/// does not require cloning it.
///
/// When the wrapper does not need to be reused, [`Self::into_target`] and
/// [`Self::into_target_with`] can move an owned value into a matching target
/// instead of cloning its allocation.
///
/// Use this type when the source type is known at run time, such as values read
/// from configuration, command-line arguments, or heterogeneous metadata. For
/// homogeneous collections, [`super::DataConverters`] provides indexed batch
/// errors on top of the same conversion rules.
///
/// # Examples
///
/// ```
/// use qubit_datatype::{
///     DataConversionOptions,
///     DataConverter,
/// };
///
/// let source = DataConverter::from("42");
/// assert_eq!(source.to::<u16>(), Ok(42));
///
/// let lossy = DataConversionOptions::lossy();
/// let value: u16 = DataConverter::from("3.9").to_with(&lossy).unwrap();
/// assert_eq!(value, 3);
/// ```
///
/// Platform-sized integers are intentionally not conversion sources:
///
/// ```compile_fail
/// use qubit_datatype::DataConverter;
///
/// let _ = DataConverter::from(1_usize);
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DataConverter<'a> {
    /// Missing source whose declared type remains known.
    Unset(
        /// Declared type retained for the missing source.
        DataType,
    ),
    /// Boolean source value.
    Bool(
        /// Boolean source value.
        bool,
    ),
    /// Unicode scalar source value.
    Char(
        /// Unicode scalar source value.
        char,
    ),
    /// 8-bit signed integer source value.
    Int8(
        /// 8-bit signed integer source value.
        i8,
    ),
    /// 16-bit signed integer source value.
    Int16(
        /// 16-bit signed integer source value.
        i16,
    ),
    /// 32-bit signed integer source value.
    Int32(
        /// 32-bit signed integer source value.
        i32,
    ),
    /// 64-bit signed integer source value.
    Int64(
        /// 64-bit signed integer source value.
        i64,
    ),
    /// 128-bit signed integer source value.
    Int128(
        /// 128-bit signed integer source value.
        i128,
    ),
    /// 8-bit unsigned integer source value.
    UInt8(
        /// 8-bit unsigned integer source value.
        u8,
    ),
    /// 16-bit unsigned integer source value.
    UInt16(
        /// 16-bit unsigned integer source value.
        u16,
    ),
    /// 32-bit unsigned integer source value.
    UInt32(
        /// 32-bit unsigned integer source value.
        u32,
    ),
    /// 64-bit unsigned integer source value.
    UInt64(
        /// 64-bit unsigned integer source value.
        u64,
    ),
    /// 128-bit unsigned integer source value.
    UInt128(
        /// 128-bit unsigned integer source value.
        u128,
    ),
    /// 32-bit floating-point source value.
    Float32(
        /// 32-bit floating-point source value.
        f32,
    ),
    /// 64-bit floating-point source value.
    Float64(
        /// 64-bit floating-point source value.
        f64,
    ),
    /// Borrowed or owned arbitrary-precision integer source value.
    #[cfg(feature = "big-integer")]
    BigInteger(
        /// Borrowed or owned arbitrary-precision integer source value.
        Cow<'a, BigInt>,
    ),
    /// Borrowed or owned arbitrary-precision decimal source value.
    #[cfg(feature = "big-decimal")]
    BigDecimal(
        /// Borrowed or owned arbitrary-precision decimal source value.
        Cow<'a, BigDecimal>,
    ),
    /// Borrowed or owned UTF-8 text source value.
    String(
        /// Borrowed or owned UTF-8 text source value.
        Cow<'a, str>,
    ),
    /// Calendar date without a time zone.
    #[cfg(feature = "chrono")]
    Date(
        /// Calendar date without a time zone.
        NaiveDate,
    ),
    /// Clock time without a date or time zone.
    #[cfg(feature = "chrono")]
    Time(
        /// Clock time without a date or time zone.
        NaiveTime,
    ),
    /// Local date and time without a time zone.
    #[cfg(feature = "chrono")]
    DateTime(
        /// Local date and time without a time zone.
        NaiveDateTime,
    ),
    /// UTC instant.
    #[cfg(feature = "chrono")]
    Instant(
        /// UTC instant.
        DateTime<Utc>,
    ),
    /// Non-negative span represented by [`Duration`].
    Duration(
        /// Non-negative span source value.
        Duration,
    ),
    /// Borrowed or owned absolute URL source value.
    #[cfg(feature = "url")]
    Url(
        /// Borrowed or owned absolute URL source value.
        Cow<'a, Url>,
    ),
    /// Borrowed or owned string-to-string map source value.
    StringMap(
        /// Borrowed or owned string-to-string map source value.
        Cow<'a, HashMap<String, String>>,
    ),
    /// Borrowed or owned JSON source value.
    #[cfg(feature = "json")]
    Json(
        /// Borrowed or owned JSON source value.
        Cow<'a, serde_json::Value>,
    ),
}

impl DataConverter<'_> {
    /// Converts this source using the shared default options.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type. A conversion implementation must exist
    ///   for the source wrapper and `T`.
    ///
    /// # Returns
    ///
    /// Returns the converted target value.
    ///
    /// # Errors
    ///
    /// Returns a structured error when the value is missing, the type pair is
    /// unsupported, or the source value violates the target contract.
    #[inline(always)]
    pub fn to<T>(&self) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        self.to_with(DataConversionOptions::default_ref())
    }

    /// Converts this source using explicit options.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Parameters
    ///
    /// * `options` - Policies for string normalization, numeric precision,
    ///   booleans, collections, and durations.
    ///
    /// # Returns
    ///
    /// Returns the converted target value.
    ///
    /// # Errors
    ///
    /// Returns a structured error containing source type, target type, and a
    /// value-free rejection reason.
    #[inline(always)]
    pub fn to_with<T>(
        &self,
        options: &DataConversionOptions,
    ) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        T::convert_from(self, options)
    }

    /// Consumes this source and converts it using the shared default options.
    ///
    /// Consuming the wrapper allows targets to reuse owned source allocations
    /// when the source and target types match. Borrowed sources retain the same
    /// behavior as [`Self::to`].
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Returns
    ///
    /// Returns the converted target value.
    ///
    /// # Errors
    ///
    /// Returns a structured error under the same conditions as [`Self::to`].
    #[inline(always)]
    pub fn into_target<T>(self) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        self.into_target_with(DataConversionOptions::default_ref())
    }

    /// Consumes this source and converts it using explicit options.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Parameters
    ///
    /// * `options` - Policies for string normalization, numeric precision,
    ///   booleans, collections, and durations.
    ///
    /// # Returns
    ///
    /// Returns the converted target value.
    ///
    /// # Errors
    ///
    /// Returns a structured error containing source type, target type, and a
    /// value-free rejection reason.
    #[inline(always)]
    pub fn into_target_with<T>(
        self,
        options: &DataConversionOptions,
    ) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        T::convert_owned(self, options)
    }

    /// Returns the runtime type of the wrapped source.
    ///
    /// For [`Self::Unset`], this returns the declared type stored in the
    /// variant rather than a generic missing-value type.
    ///
    /// # Returns
    ///
    /// Returns the [`DataType`] corresponding to this enum variant.
    #[inline(always)]
    pub const fn data_type(&self) -> DataType {
        for_each_data_type_mapping!(data_converter_data_type_match, self)
    }

    /// Builds a missing-value error for this source and target.
    ///
    /// # Parameters
    ///
    /// * `to` - Requested target type.
    ///
    /// # Returns
    ///
    /// A missing-value error whose source type comes from [`Self::data_type`].
    #[inline(always)]
    fn missing(&self, to: DataType) -> DataConversionError {
        DataConversionError::missing(self.data_type(), to)
    }

    /// Builds an unsupported-pair error for this source and target.
    ///
    /// # Parameters
    ///
    /// * `to` - Requested target type.
    ///
    /// # Returns
    ///
    /// An unsupported-pair error whose source type comes from
    /// [`Self::data_type`].
    #[inline(always)]
    fn unsupported(&self, to: DataType) -> DataConversionError {
        DataConversionError::unsupported(self.data_type(), to)
    }

    /// Builds an invalid-value error for this source and target.
    ///
    /// # Parameters
    ///
    /// * `to` - Requested target type.
    /// * `reason` - Stable, value-independent rejection reason.
    ///
    /// # Returns
    ///
    /// An invalid-value error recording this source's runtime type.
    #[inline(always)]
    fn invalid(
        &self,
        to: DataType,
        reason: InvalidValueReason,
    ) -> DataConversionError {
        DataConversionError::invalid(self.data_type(), to, reason)
    }
}