qubit-value 0.13.0

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
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! # Named Multiple Values
//!
//! Provides a lightweight container for binding names to multiple value
//! collections, facilitating human-readable identification of groups of values
//! in configurations, serialization, logging, and other scenarios.

#[cfg(feature = "json")]
use std::io::Write;

#[cfg(feature = "json")]
use qubit_budget::json::JsonDecodeLimits;
#[cfg(feature = "json")]
use qubit_budget::json::JsonDecodeSession;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeLimits;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeSession;
#[cfg(feature = "json")]
use qubit_json::decode::JsonDecoder;
#[cfg(feature = "json")]
use qubit_json::encode::JsonEncoder;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::de::Error as DeserializeError;
use serde::ser::Error as SerializeError;

use self::internal::NamedMultiValuesWireOwned;
use self::internal::NamedMultiValuesWireRef;
use super::multi_values::MultiValues;
use super::named_value::NamedValue;
#[cfg(feature = "json")]
use crate::ValueWireDecodeError;
#[cfg(feature = "json")]
use crate::ValueWireEncodeError;
#[cfg(feature = "json")]
use crate::ValueWireEncodePreflight;
use crate::ValueWireRefV1;
#[cfg(feature = "json")]
use crate::ValueWireV1;

mod internal;

/// Named multiple values
///
/// A container that associates a readable name with a set of `MultiValues`,
/// suitable for organizing data in key-value (name-multiple values) scenarios,
/// such as configuration items, command-line parameter aggregation, structured
/// log fields, etc.
///
/// # Features
///
/// - Provides clear name identification for multiple value collections
/// - Exposes the inner [`MultiValues`] through explicit accessors
/// - Supports `serde` serialization and deserialization
///
/// # Use Cases
///
/// - Aggregating a set of ports, hostnames, etc., as semantically meaningful
///   fields
/// - Outputting named multiple value lists in configurations/logs
///
/// # Deserialization boundaries
///
/// [`Deserialize`] validates the V1 wire schema and requires a collection
/// payload, but it does not create a resource budget by itself. For a complete,
/// untrusted JSON document, use `NamedMultiValues::decode_json_slice` or
/// `NamedMultiValues::decode_json_slice_with_limits`. When this type is
/// embedded in a larger document, deserialize it through a resource-bounded
/// outer decoder. Bounded helpers report target-deserialization failures as
/// `InvalidJson` metadata containing only the Serde category and location.
/// Generic Serde errors retain the surrounding deserializer's semantics and
/// may include input-derived text, such as field names. Reader and writer I/O
/// error sources may also contain application-defined details. Resource limits
/// do not sanitize diagnostics; apply the application's logging policy to all
/// error sources.
///
/// # Examples
///
/// ```rust
/// use qubit_value::{NamedMultiValues, MultiValues};
///
/// // Identify a group of ports with the name "ports"
/// let named = NamedMultiValues::new(
///     "ports",
///     MultiValues::Int32(vec![8080, 8081, 8082])
/// );
///
/// assert_eq!(named.name(), "ports");
/// assert_eq!(named.values().len(), 3);
/// ```
///
/// The wrapper intentionally does not forward [`MultiValues`] methods
/// implicitly:
///
/// ```compile_fail
/// use qubit_value::{MultiValues, NamedMultiValues};
///
/// let named = NamedMultiValues::new("ports", MultiValues::Int32(vec![8080]));
/// let _ = named.len();
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NamedMultiValues {
    /// Owned, human-readable label identifying this collection independently of
    /// its contents.
    name: String,
    /// Owned homogeneous collection stored under the label, including empty or
    /// unset values.
    value: MultiValues,
}

impl NamedMultiValues {
    /// Create a new named multiple values
    ///
    /// Associates a given name with `MultiValues`, generating a container that
    /// can be referenced by name.
    ///
    /// # Type Parameters
    ///
    /// * `impl Into<String>` - Name source converted into owned storage.
    ///
    /// # Use Cases
    ///
    /// - Building configuration fields (e.g., `servers`, `ports`, etc.)
    /// - Binding parsed multiple value results to semantic names
    ///
    /// # Parameters
    ///
    /// * `name` - Name of the multiple values
    /// * `value` - Content of the multiple values
    ///
    /// # Returns
    ///
    /// Returns a newly created named multiple values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_value::{NamedMultiValues, MultiValues};
    ///
    /// let named = NamedMultiValues::new(
    ///     "servers",
    ///     MultiValues::String(vec!["s1".to_string(), "s2".to_string()])
    /// );
    /// assert_eq!(named.name(), "servers");
    /// ```
    #[inline(always)]
    pub fn new(name: impl Into<String>, value: MultiValues) -> Self {
        Self {
            name: name.into(),
            value,
        }
    }

    /// Decodes a complete named collection JSON document with default limits.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete UTF-8 JSON document to decode.
    ///
    /// # Returns
    ///
    /// The decoded named collection.
    ///
    /// # Errors
    ///
    /// Returns a JSON, wire-contract, or resource-limit error.
    #[cfg(feature = "json")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn decode_json_slice(input: &[u8]) -> Result<Self, ValueWireDecodeError> {
        Self::decode_json_slice_with_limits(input, ValueWireV1::default_json_decode_limits())
    }

    /// Decodes a complete named collection JSON document with explicit limits.
    ///
    /// The wrapper name and nested collection share one accounting session.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete UTF-8 JSON document to decode.
    /// * `limits` - Input and decoded-resource limits.
    ///
    /// # Returns
    ///
    /// The decoded named collection.
    ///
    /// # Errors
    ///
    /// Returns a JSON, wire-contract, or resource-limit error.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn decode_json_slice_with_limits(input: &[u8], limits: JsonDecodeLimits) -> Result<Self, ValueWireDecodeError> {
        let session = JsonDecodeSession::from_limits(limits);
        JsonDecoder::new(session)
            .decode_unique_utf8(input)
            .map_err(ValueWireDecodeError::from)
    }

    /// Encodes this named collection into a bounded compact JSON vector with
    /// the default V1 JSON resource profile.
    ///
    /// # Returns
    ///
    /// Compact UTF-8 JSON bytes for the complete named collection.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] for resource or serialization failures.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_vec(&self) -> Result<Vec<u8>, ValueWireEncodeError> {
        self.to_json_vec_with_limits(ValueWireV1::default_json_encode_limits())
    }

    /// Encodes this named collection into a bounded compact JSON vector.
    ///
    /// # Parameters
    ///
    /// * `limits` - Resource limits enforced during JSON encoding.
    ///
    /// # Returns
    ///
    /// Compact UTF-8 JSON bytes for the complete named collection.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when encoding exceeds `limits` or the
    /// named collection cannot be serialized.
    #[cfg(feature = "json")]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_vec_with_limits(&self, limits: JsonEncodeLimits) -> Result<Vec<u8>, ValueWireEncodeError> {
        ValueWireEncodePreflight::new(limits).check_values(self.values())?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .to_vec(self)
            .map_err(ValueWireEncodeError::from)
    }

    /// Encodes this named collection to a writer with the default V1 JSON
    /// profile.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Destination writer type.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete named collection.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete document is written.
    ///
    /// The complete document is buffered and admitted before this method writes
    /// its bytes to the destination. Preflight, serialization, or budget
    /// rejection does not write this document. An I/O error may leave an
    /// accepted prefix in the writer; do not blindly retry a complete
    /// document on the same destination.
    ///
    /// This method does not explicitly flush the writer. Success means the
    /// writer accepted all document bytes, not that they were flushed,
    /// persisted, or received by a remote peer. Pass `&mut writer` to
    /// retain ownership of a buffered writer, then call `flush()` and
    /// handle its error separately. Passing an owned writer may invoke that
    /// writer's drop behavior; errors from an implicit drop-time flush are
    /// not returned by this method.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] for resource, serialization, or writer
    /// failures.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_writer<W>(&self, writer: W) -> Result<(), ValueWireEncodeError>
    where
        W: Write,
    {
        self.to_json_writer_with_limits(writer, ValueWireV1::default_json_encode_limits())
    }

    /// Encodes this named collection to a writer after enforcing JSON budgets.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Destination writer type.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete named collection.
    /// * `limits` - Resource limits enforced during JSON encoding.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete document is written.
    ///
    /// The complete document is buffered and admitted before this method writes
    /// its bytes to the destination. Preflight, serialization, or budget
    /// rejection does not write this document. An I/O error may leave an
    /// accepted prefix in the writer; do not blindly retry a complete
    /// document on the same destination.
    ///
    /// This method does not explicitly flush the writer. Success means the
    /// writer accepted all document bytes, not that they were flushed,
    /// persisted, or received by a remote peer. Pass `&mut writer` to
    /// retain ownership of a buffered writer, then call `flush()` and
    /// handle its error separately. Passing an owned writer may invoke that
    /// writer's drop behavior; errors from an implicit drop-time flush are
    /// not returned by this method.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when encoding exceeds `limits`, the
    /// named collection cannot be serialized, or `writer` rejects output.
    #[cfg(feature = "json")]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_writer_with_limits<W>(
        &self,
        mut writer: W,
        limits: JsonEncodeLimits,
    ) -> Result<(), ValueWireEncodeError>
    where
        W: Write,
    {
        ValueWireEncodePreflight::new(limits).check_values(self.values())?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .write_buffered(&mut writer, self)
            .map_err(ValueWireEncodeError::from)
    }

    /// Borrows the human-readable label without allocating or inspecting the
    /// collection.
    ///
    /// The slice remains valid while this container is borrowed.
    ///
    /// # Returns
    ///
    /// Returns a string slice of the name
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_value::{NamedMultiValues, MultiValues};
    ///
    /// let named = NamedMultiValues::new("items", MultiValues::Int32(vec![1, 2, 3]));
    /// assert_eq!(named.name(), "items");
    /// ```
    #[inline(always)]
    #[must_use = "the borrowed name should be used"]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Borrows the collection without cloning its elements or its label.
    ///
    /// # Returns
    ///
    /// A shared reference to the contained [`MultiValues`].
    #[inline(always)]
    #[must_use = "the borrowed values should be used"]
    pub fn values(&self) -> &MultiValues {
        &self.value
    }

    /// Exclusively borrows the collection so it can be changed without changing
    /// the label.
    ///
    /// # Returns
    ///
    /// An exclusive reference to the contained [`MultiValues`].
    #[inline]
    #[must_use = "the mutable values reference should be used"]
    pub fn values_mut(&mut self) -> &mut MultiValues {
        &mut self.value
    }

    /// Convert this named multi-values into a named single value.
    ///
    /// The returned value keeps the same name and uses the first element from
    /// the inner [`MultiValues`]. If there is no element, the returned value is
    /// `Value::Unset` with the same data type.
    ///
    /// # Returns
    ///
    /// A named clone of the first item, or a named typed unset value.
    #[inline]
    pub fn first_named_value(&self) -> NamedValue {
        NamedValue::new(self.name.as_str(), self.value.first_value())
    }

    /// Replaces the owned label while preserving the collection unchanged.
    ///
    /// Converts the supplied name into owned storage and drops the previous
    /// label.
    ///
    /// # Type Parameters
    ///
    /// * `impl Into<String>` - Name source converted into owned storage.
    ///
    /// # Parameters
    ///
    /// * `name` - Human-readable label to associate with the existing
    ///   collection.
    ///
    /// # Returns
    ///
    /// No return value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_value::{NamedMultiValues, MultiValues};
    ///
    /// let mut named = NamedMultiValues::new("old", MultiValues::Bool(vec![true]));
    /// named.set_name("new");
    /// assert_eq!(named.name(), "new");
    /// ```
    #[inline(always)]
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = name.into();
    }

    /// Replaces the contained values.
    ///
    /// # Parameters
    ///
    /// * `values` - New collection to store under the existing name.
    #[inline]
    pub fn set_values(&mut self, values: MultiValues) {
        self.value = values;
    }

    /// Consumes this wrapper and returns its owned name and values.
    ///
    /// # Returns
    ///
    /// The `(name, values)` pair without cloning either component.
    #[inline(always)]
    #[must_use = "consuming NamedMultiValues without using its parts loses both fields"]
    pub fn into_parts(self) -> (String, MultiValues) {
        (self.name, self.value)
    }

    /// Consumes this container and converts its first item to a named value.
    ///
    /// The owned name and first stored item are moved into the result. An empty
    /// or unset collection produces [`crate::Value::Unset`] with the same data
    /// type.
    ///
    /// # Returns
    ///
    /// A named owned first item, or a named typed unset value.
    #[inline]
    pub fn into_first_named_value(self) -> NamedValue {
        let (name, values) = self.into_parts();
        NamedValue::new(name, values.into_first_value())
    }
}

impl From<NamedValue> for NamedMultiValues {
    /// Construct `NamedMultiValues` from `NamedValue`
    ///
    /// Reuses the name and promotes the single value to a `MultiValues`
    /// containing only one element.
    ///
    /// # Parameters
    ///
    /// * `named` - Named scalar consumed to transfer its name and value.
    ///
    /// # Returns
    ///
    /// A named collection containing the promoted scalar.
    #[inline]
    fn from(named: NamedValue) -> Self {
        let (name, value) = named.into_parts();
        let value = MultiValues::from(value);
        Self { name, value }
    }
}

impl Serialize for NamedMultiValues {
    /// Serializes the name and its explicitly versioned collection.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Serde serializer that determines the output representation.
    ///
    /// # Parameters
    ///
    /// * `serializer` - Destination receiving the named V1 collection envelope.
    ///
    /// # Returns
    ///
    /// The serializer's success value after writing the envelope.
    ///
    /// # Errors
    ///
    /// Returns `S::Error` if wire conversion or serialization fails.
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let value = ValueWireRefV1::try_from(self.values()).map_err(SerializeError::custom)?;
        NamedMultiValuesWireRef {
            name: self.name(),
            value,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for NamedMultiValues {
    /// Deserializes a named collection from the V1 wire contract.
    ///
    /// This implementation validates the wire schema and collection shape, but
    /// inherits resource accounting from `deserializer`. Callers handling a
    /// complete, untrusted JSON document should use the bounded JSON helpers on
    /// [`NamedMultiValues`] instead of an unbounded Serde entry point.
    /// Generic deserializer errors may contain input-derived text. The bounded
    /// helpers instead expose only Serde category and location for target
    /// deserialization failures; resource limits do not sanitize other errors.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Serde deserializer that supplies the input and any outer budget.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source containing one named V1 collection envelope.
    ///
    /// # Returns
    ///
    /// The decoded name and homogeneous collection.
    ///
    /// # Errors
    ///
    /// Returns `D::Error` for an invalid V1 envelope, an unsupported payload,
    /// or a payload whose shape is not a collection.
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let NamedMultiValuesWireOwned { name, value } = NamedMultiValuesWireOwned::deserialize(deserializer)?;
        let value = value
            .into_container()
            .into_collection()
            .map_err(|_| DeserializeError::custom("named multi-values wire payload must contain a collection"))?;
        Ok(Self::new(name, value))
    }
}