qubit-value 0.13.1

Type-safe containers for single, multi-valued, and named runtime values
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Natural JSON projection for value containers.

use std::str::FromStr;

use qubit_budget::json::JsonMeasurement;
use qubit_datatype::ConversionLimits;
use qubit_datatype::ConversionPolicy;
use qubit_datatype::DataConversionError;
use qubit_datatype::DataConverter;
use qubit_datatype::DataListConversionError;
use qubit_datatype::DataType;
use qubit_datatype::InvalidValueReason;
use serde_json::Number;
use serde_json::Value as JsonValue;

use crate::MultiValues;
use crate::MultiValuesRef;
use crate::Value;
use crate::ValueContainer;
use crate::ValueError;
use crate::ValueRef;
use crate::ValueResult;

mod internal;
mod projection_budget;

use self::internal::json_children::JsonChildren;
use self::internal::prepared_projection::PreparedProjection;
use self::internal::prepared_scalar::PreparedScalar;
use self::projection_budget::ProjectionBudget;

/// Checks source big-number limits before decimal formatting can allocate.
macro_rules! check_projection_number {
    (BigInteger, $value:expr, $budget:expr) => {
        $budget
            .limits
            .numeric()
            .big_integer()
            .check($value)
            .map_err(|error| $budget.error(error))?
    };
    (BigDecimal, $value:expr, $budget:expr) => {
        $budget
            .limits
            .numeric()
            .big_decimal()
            .check($value)
            .map_err(|error| $budget.error(error))?
    };
    ($variant:ident, $value:expr, $budget:expr) => {};
}

/// Classifies collections requiring a per-element rendering cache.
macro_rules! cache_projection {
    (String, $class:ident) => {
        false
    };
    ($variant:ident, json_bool) => {
        false
    };
    ($variant:ident, json_number) => {
        false
    };
    ($variant:ident, json_object) => {
        false
    };
    ($variant:ident, json_identity) => {
        false
    };
    ($variant:ident, $class:ident) => {
        true
    };
}

/// Prepares one scalar while retaining only genuinely required allocations.
macro_rules! prepare_payload {
    (String, $class:ident, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        $budget.input($value)?;
        $budget.admit_output_string($value.len(), $depth)?;
        Ok(PreparedScalar::Borrowed($view))
    }};
    ($variant:ident, json_bool, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        let _ = $value;
        $budget.admit(JsonMeasurement::Boolean { depth: $depth })?;
        Ok(PreparedScalar::Borrowed($view))
    }};
    ($variant:ident, json_number, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        $budget.display(&$value, $depth, true)?;
        Ok(PreparedScalar::Borrowed($view))
    }};
    ($variant:ident, json_float32, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        let number = Number::from_str(&$value.to_string()).map_err(|_| {
            DataConversionError::invalid($from, DataType::Json, InvalidValueReason::NonFinite)
        })?;
        $budget.display(&number, $depth, true)?;
        Ok(PreparedScalar::Number(number))
    }};
    ($variant:ident, json_float64, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        let number = Number::from_f64($value).ok_or_else(|| {
            DataConversionError::invalid($from, DataType::Json, InvalidValueReason::NonFinite)
        })?;
        $budget.display(&number, $depth, true)?;
        Ok(PreparedScalar::Number(number))
    }};
    ($variant:ident, json_string, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {
        $budget
            .format(&$value, $depth)
            .map(PreparedScalar::Formatted)
    };
    ($variant:ident, json_duration, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        let text = DataConverter::from($value)
            .to_in::<String>(&mut $budget.conversion)
            .map_err(|error| $budget.duration_conversion_error(error))?;
        $budget.admit_output_string(text.len(), $depth)?;
        Ok(PreparedScalar::Formatted(text))
    }};
    ($variant:ident, json_object, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        $budget.admit(JsonMeasurement::Object {
            depth: $depth,
            entries: $value.len(),
        })?;
        for (key, value) in $value {
            $budget.text(key, $depth, true)?;
            $budget.text(value, $depth.saturating_add(1), false)?;
        }
        Ok(PreparedScalar::Borrowed($view))
    }};
    ($variant:ident, json_identity, $value:expr, $view:expr, $from:expr, $budget:expr, $depth:expr) => {{
        admit_json($value, $depth, $budget)?;
        Ok(PreparedScalar::Borrowed($view))
    }};
}

/// Uses the owned type table to prepare borrowed scalar payloads.
macro_rules! prepare_scalar_match {
    ($view:expr, $budget:expr, $depth:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal $(, $_wire:tt)*)),+ $(,)?) => {
        match $view {
            ValueRef::Unset(_) => {
                $budget.admit(JsonMeasurement::Null { depth: $depth })?;
                Ok(PreparedScalar::Borrowed($view))
            }
            $($(#[$cfg])* ValueRef::$variant(value) => {
                check_projection_number!($variant, value, $budget);
                prepare_payload!($variant, $json_class, value, $view, $data_type, $budget, $depth)
            },)+
        }
    };
}

/// Admits one scalar before allocating a cached rich rendering.
///
/// # Type Parameters
///
/// - `'a`: Lifetime of the source storage retained by the prepared scalar.
///
/// # Parameters
///
/// - `view`: Borrowed scalar payload to admit and prepare.
/// - `budget`: Shared operation accounting, updated as input and output are
///   admitted.
/// - `depth`: Root-inclusive depth of this scalar in the projected JSON.
///
/// # Returns
///
/// A borrowed payload or cached rendering whose resource costs have been
/// admitted.
///
/// # Errors
///
/// Returns an error when conversion fails or a configured resource limit is
/// exceeded.
fn prepare_scalar<'a>(
    view: ValueRef<'a>,
    budget: &mut ProjectionBudget<'_>,
    depth: usize,
) -> ValueResult<PreparedScalar<'a>> {
    budget.item()?;
    for_each_value_type!(prepare_scalar_match, view, budget, depth)
}

/// Determines whether a homogeneous collection needs a cache before iteration.
macro_rules! collection_cache_match {
    ($view:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal $(, $_wire:tt)*)),+ $(,)?) => {
        match $view {
            MultiValuesRef::Unset(_) => false,
            $($(#[$cfg])* MultiValuesRef::$variant(_) => cache_projection!($variant, $json_class),)+
        }
    };
}

/// Admits the full collection before materializing any final JSON output.
///
/// # Type Parameters
///
/// - `'a`: Lifetime of the source storage retained by borrowed collection and
///   scalar projections.
///
/// # Parameters
///
/// - `view`: Borrowed homogeneous collection, including its unset state.
/// - `budget`: Shared operation accounting, updated for the shape and each
///   element.
///
/// # Returns
///
/// An admitted collection projection, retaining rendered elements only when
/// needed; an unset collection remains a null projection.
///
/// # Errors
///
/// Returns an error when preparing an element fails or a configured resource
/// limit is exceeded.
///
/// # Panics
///
/// Panics if an index below the collection's reported length cannot be read.
fn prepare_collection<'a>(
    view: MultiValuesRef<'a>,
    budget: &mut ProjectionBudget<'_>,
) -> ValueResult<PreparedProjection<'a>> {
    if matches!(view, MultiValuesRef::Unset(_)) {
        budget.item()?;
        budget.admit(JsonMeasurement::Null { depth: 1 })?;
        return Ok(PreparedProjection::BorrowedCollection(view));
    }
    budget.admit(JsonMeasurement::Array {
        depth: 1,
        items: view.len(),
    })?;
    let cache = for_each_value_type!(collection_cache_match, view);
    let mut prepared = Vec::new();
    for index in 0..view.len() {
        budget.source_index = Some(index);
        let item = view
            .get(index)
            .expect("index is inside the source collection");
        let scalar = prepare_scalar(item, budget, 2).map_err(|error| match error {
            ValueError::Conversion(source) => DataListConversionError::new(index, source).into(),
            error => error,
        })?;
        if cache {
            prepared.push(scalar);
        }
    }
    Ok(if cache {
        PreparedProjection::Collection(prepared)
    } else {
        PreparedProjection::BorrowedCollection(view)
    })
}

/// Traverses nested JSON iteratively, charging keys and leaf text before
/// cloning.
///
/// # Parameters
///
/// - `value`: Borrowed JSON tree to inspect without cloning.
/// - `depth`: Root-inclusive depth of the tree root in the projected output.
/// - `budget`: Shared operation accounting, updated for every visited node and
///   key.
///
/// # Returns
///
/// Unit after the entire tree has been admitted and its numbers validated.
///
/// # Errors
///
/// Returns an error when a configured resource limit is exceeded or a JSON
/// number is outside the supported projection range.
fn admit_json(
    value: &JsonValue,
    depth: usize,
    budget: &mut ProjectionBudget<'_>,
) -> ValueResult<()> {
    let mut frames = Vec::<JsonChildren<'_>>::new();
    let mut next = Some((None, value, depth));
    while let Some((key, value, depth)) = next.take() {
        if let Some(key) = key {
            budget.text(key, depth, true)?;
        }
        match value {
            JsonValue::Null => budget.admit(JsonMeasurement::Null { depth })?,
            JsonValue::Bool(_) => budget.admit(JsonMeasurement::Boolean { depth })?,
            JsonValue::Number(value) => {
                budget.display(value, depth, true)?;
                validate_projected_json_number(value)?;
            }
            JsonValue::String(value) => budget.text(value, depth, false)?,
            JsonValue::Array(values) => {
                budget.admit(JsonMeasurement::Array {
                    depth,
                    items: values.len(),
                })?;
                frames.push(JsonChildren::Array(values.iter(), depth.saturating_add(1)));
            }
            JsonValue::Object(values) => {
                budget.admit(JsonMeasurement::Object {
                    depth,
                    entries: values.len(),
                })?;
                frames.push(JsonChildren::Object(values.iter(), depth.saturating_add(1)));
            }
        }
        while let Some(frame) = frames.last_mut() {
            if let Some(child) = frame.next() {
                next = Some(child);
                break;
            }
            frames.pop();
        }
    }
    Ok(())
}

/// Checks an already budget-admitted JSON number against the projection range.
///
/// # Parameters
///
/// - `number`: Admitted number to validate as an integer or finite
///   floating-point value.
///
/// # Returns
///
/// Unit when the number fits the supported projection range.
///
/// # Errors
///
/// Returns a conversion error for an out-of-range integer or non-finite float.
fn validate_projected_json_number(number: &Number) -> ValueResult<()> {
    if number.as_i64().is_some() || number.as_u64().is_some() {
        return Ok(());
    }
    let text = number.to_string();
    let fractional = text.bytes().any(|byte| matches!(byte, b'.' | b'e' | b'E'));
    let reason = if fractional {
        if text.parse::<f64>().is_ok_and(f64::is_finite) {
            return Ok(());
        }
        InvalidValueReason::NonFinite
    } else {
        let fits = if text.starts_with('-') {
            text.parse::<i64>().is_ok()
        } else {
            text.parse::<u64>().is_ok()
        };
        if fits {
            return Ok(());
        }
        InvalidValueReason::OutOfRange
    };
    Err(DataConversionError::invalid(DataType::Json, DataType::Json, reason).into())
}

/// Projects a scalar after complete bounded preparation.
///
/// Returns conversion or resource errors before final JSON allocation.
///
/// # Parameters
///
/// - `value`: Borrowed scalar source; its storage is preserved.
/// - `policy`: Conversion policy used when rendering rich scalar payloads.
/// - `limits`: Per-value and cumulative resource limits for this operation.
///
/// # Returns
///
/// The owned natural JSON projection after all preparation costs are admitted.
///
/// # Errors
///
/// Returns an error when conversion fails or a configured resource limit is
/// exceeded.
pub(crate) fn value_to_json_value_with(
    value: &Value,
    policy: &ConversionPolicy,
    limits: &ConversionLimits,
) -> ValueResult<JsonValue> {
    let mut budget = ProjectionBudget::new(value.data_type(), policy, limits);
    Ok(PreparedProjection::Scalar(prepare_scalar(value.view(), &mut budget, 1)?).materialize())
}

/// Projects a collection after complete bounded preparation, preserving its
/// shape.
///
/// # Parameters
///
/// - `values`: Borrowed homogeneous source collection; its storage is
///   preserved.
/// - `policy`: Conversion policy used when rendering rich element payloads.
/// - `limits`: Per-value and cumulative resource limits shared by the
///   collection.
///
/// # Returns
///
/// An owned JSON array, or JSON null for an unset collection.
///
/// # Errors
///
/// Returns an error when conversion fails or a configured resource limit is
/// exceeded.
pub(crate) fn multi_values_to_json_value_with(
    values: &MultiValues,
    policy: &ConversionPolicy,
    limits: &ConversionLimits,
) -> ValueResult<JsonValue> {
    let mut budget = ProjectionBudget::new(values.data_type(), policy, limits);
    Ok(prepare_collection(values.view(), &mut budget)?.materialize())
}

/// Projects scalar or collection storage without conflating cardinalities.
///
/// # Parameters
///
/// - `container`: Borrowed scalar or collection source; its storage is
///   preserved.
/// - `policy`: Conversion policy forwarded to the selected projection.
/// - `limits`: Resource limits forwarded to the selected projection.
///
/// # Returns
///
/// The owned JSON projection preserving the source's scalar or collection
/// shape.
///
/// # Errors
///
/// Returns an error when conversion fails or a configured resource limit is
/// exceeded.
#[inline]
pub(crate) fn value_container_to_json_value_with(
    container: &ValueContainer,
    policy: &ConversionPolicy,
    limits: &ConversionLimits,
) -> ValueResult<JsonValue> {
    match container {
        ValueContainer::Scalar(value) => value_to_json_value_with(value, policy, limits),
        ValueContainer::Collection(values) => {
            multi_values_to_json_value_with(values, policy, limits)
        }
    }
}