qubit-datatype 0.14.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// =============================================================================
//    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;
#[cfg(feature = "chrono")]
use chrono::NaiveDate;
#[cfg(feature = "chrono")]
use chrono::NaiveDateTime;
#[cfg(feature = "chrono")]
use chrono::NaiveTime;
#[cfg(feature = "chrono")]
use chrono::Utc;
#[cfg(feature = "big-integer")]
use num_bigint::BigInt;
#[cfg(feature = "json")]
use serde_json::Value;
#[cfg(feature = "url")]
use url::Url;

#[cfg(feature = "json")]
use self::structured::account_json_structure;
use self::structured::account_string_map_structure;
use super::admitted_conversion::AdmittedConversion;
use super::conversion_context::ConversionContext;
use super::conversion_session::ConversionSession;
use super::data_conversion_target::DataConversionTarget;
use super::error::DataConversionError;
use super::error::InvalidValueReason;
use super::options::ConversionLimits;
use super::options::ConversionPolicy;
use crate::datatype::DataType;
use crate::datatype::for_each_data_type_mapping;

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

/// Expands the central data-type mapping table into a source-variant match.
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
/// [`ConversionPolicy`] 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 owned storage into targets that can
/// preserve it 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.
///
/// # Type Parameters
///
/// * `'a` - Lifetime of borrowed string, big-number, URL, map, and JSON sources
///   stored by the converter.
///
/// # Examples
///
/// ```
/// use qubit_datatype::{
///     ConversionLimits,
///     ConversionPolicy,
///     DataConverter,
/// };
///
/// let source = DataConverter::from("42");
/// assert_eq!(source.to::<u16>(), Ok(42));
///
/// let lossy = ConversionPolicy::lossy();
/// let limits = ConversionLimits::default();
/// let value: u16 = DataConverter::from("3.9").to_with(&lossy, &limits).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, Value>,
    ),
}

impl<'source> DataConverter<'source> {
    /// 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(ConversionPolicy::default_ref(), ConversionLimits::default_ref())
    }

    /// Converts this source using an explicit policy and limits.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Parameters
    ///
    /// * `policy` - Policies for string normalization, numeric precision,
    ///   booleans, collections, and durations.
    /// * `limits` - Value-level and operation-level resource limits.
    ///
    /// # 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, policy: &ConversionPolicy, limits: &ConversionLimits) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        let mut session = ConversionSession::new(policy, limits);
        self.to_in(&mut session)
    }

    /// Converts this source using an existing conversion session.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Parameters
    ///
    /// * `session` - Session whose policy and cumulative budgets are reused.
    ///
    /// # Returns
    ///
    /// Returns the converted target value.
    ///
    /// # Errors
    ///
    /// Returns a structured error under the same conditions as [`Self::to`].
    #[inline(always)]
    pub fn to_in<T>(&self, session: &mut ConversionSession<'_>) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        session
            .consume_item()
            .map_err(|limit| DataConversionError::limit_exceeded(self.data_type(), T::DATA_TYPE, limit))?;
        self.charge_input_for_target(T::DATA_TYPE, session)?;

        let context = ConversionContext::new(session, self.data_type(), T::DATA_TYPE);
        T::convert(AdmittedConversion::new(self.borrowed(), context))
    }

    /// Consumes this source and converts it using the shared default options.
    ///
    /// Consuming the wrapper allows targets to reuse owned source allocations
    /// when the conversion can preserve them. 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(ConversionPolicy::default_ref(), ConversionLimits::default_ref())
    }

    /// Consumes this source and converts it using an explicit policy and
    /// limits.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Parameters
    ///
    /// * `policy` - Policies for string normalization, numeric precision,
    ///   booleans, collections, and durations.
    /// * `limits` - Value-level and operation-level resource limits.
    ///
    /// # 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,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        let mut session = ConversionSession::new(policy, limits);
        self.into_target_in(&mut session)
    }

    /// Consumes this source and converts it using an existing session.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Requested target type.
    ///
    /// # Parameters
    ///
    /// * `session` - Session whose policy and cumulative budgets are reused.
    ///
    /// # Returns
    ///
    /// Returns the converted target value.
    ///
    /// # Errors
    ///
    /// Returns a structured error under the same conditions as [`Self::to`].
    #[inline(always)]
    pub fn into_target_in<T>(self, session: &mut ConversionSession<'_>) -> Result<T, DataConversionError>
    where
        T: DataConversionTarget,
    {
        let from = self.data_type();
        session
            .consume_item()
            .map_err(|limit| DataConversionError::limit_exceeded(from, T::DATA_TYPE, limit))?;
        self.charge_input_for_target(T::DATA_TYPE, session)?;
        let context = ConversionContext::new(session, from, T::DATA_TYPE);
        T::convert(AdmittedConversion::new(self, context))
    }

    /// Charges textual input and supported structured values before a target
    /// parser can allocate or recurse.
    fn charge_input_for_target(
        &self,
        target: DataType,
        session: &mut ConversionSession<'_>,
    ) -> Result<(), DataConversionError> {
        match self {
            Self::String(value) => {
                session
                    .consume_input_bytes_usize(value.len())
                    .map_err(|limit| DataConversionError::measured_limit(self.data_type(), target, limit))?;
            }
            #[cfg(feature = "json")]
            Self::Json(value) if target == DataType::Json => {
                account_json_structure(value, self.data_type(), target, session)?;
            }
            Self::StringMap(value) if target == DataType::StringMap => {
                account_string_map_structure(value, 1, session)
                    .map_err(|limit| DataConversionError::measured_limit(self.data_type(), target, limit))?;
            }
            #[cfg(feature = "json")]
            Self::StringMap(value) if target == DataType::Json => {
                account_string_map_structure(value, 1, session)
                    .map_err(|limit| DataConversionError::measured_limit(self.data_type(), target, limit))?;
            }
            _ => {}
        }
        Ok(())
    }

    /// Reborrows heap-backed storage while copying only scalar values.
    #[inline(always)]
    fn borrowed<'borrowed>(&'borrowed self) -> DataConverter<'borrowed>
    where
        'source: 'borrowed,
    {
        match self {
            Self::Unset(value) => Self::Unset(*value),
            Self::Bool(value) => Self::Bool(*value),
            Self::Char(value) => Self::Char(*value),
            Self::Int8(value) => Self::Int8(*value),
            Self::Int16(value) => Self::Int16(*value),
            Self::Int32(value) => Self::Int32(*value),
            Self::Int64(value) => Self::Int64(*value),
            Self::Int128(value) => Self::Int128(*value),
            Self::UInt8(value) => Self::UInt8(*value),
            Self::UInt16(value) => Self::UInt16(*value),
            Self::UInt32(value) => Self::UInt32(*value),
            Self::UInt64(value) => Self::UInt64(*value),
            Self::UInt128(value) => Self::UInt128(*value),
            Self::Float32(value) => Self::Float32(*value),
            Self::Float64(value) => Self::Float64(*value),
            Self::String(value) => DataConverter::String(Cow::Borrowed(value.as_ref())),
            #[cfg(feature = "big-integer")]
            Self::BigInteger(value) => DataConverter::BigInteger(Cow::Borrowed(value.as_ref())),
            #[cfg(feature = "big-decimal")]
            Self::BigDecimal(value) => DataConverter::BigDecimal(Cow::Borrowed(value.as_ref())),
            #[cfg(feature = "chrono")]
            Self::Date(value) => Self::Date(*value),
            #[cfg(feature = "chrono")]
            Self::Time(value) => Self::Time(*value),
            #[cfg(feature = "chrono")]
            Self::DateTime(value) => Self::DateTime(*value),
            #[cfg(feature = "chrono")]
            Self::Instant(value) => Self::Instant(*value),
            Self::Duration(value) => Self::Duration(*value),
            #[cfg(feature = "url")]
            Self::Url(value) => DataConverter::Url(Cow::Borrowed(value.as_ref())),
            Self::StringMap(value) => DataConverter::StringMap(Cow::Borrowed(value.as_ref())),
            #[cfg(feature = "json")]
            Self::Json(value) => DataConverter::Json(Cow::Borrowed(value.as_ref())),
        }
    }

    /// 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.
    #[must_use = "the source data type is returned"]
    #[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)
    }
}