Qubit Value
A type-safe value container framework built on qubit_datatype::DataType,
providing unified abstractions for single values, multi-values, and named values
with generic construction/access/mutation, type conversion, and complete serde
serialization support.
Overview
Qubit Value provides a comprehensive solution for handling dynamically-typed values in a type-safe manner. It bridges the gap between static typing and runtime flexibility, offering powerful abstractions for value storage, retrieval, and conversion while maintaining Rust's safety guarantees.
Configuration Object Support: If you need configuration objects based on different types of multi-value designs, consider using the qubit-config crate, which provides comprehensive configuration management functionality. You can find more information on GitHub and crates.io.
Features
🎯 Core Design
- Enum-Based Architecture: Uses
Value/MultiValuesenums to represent all supported data types - Type Safety: Enum variants carry static types; failures are expressed
through
Result<T, ValueError> - Zero-Cost Abstractions: Basic types are stored directly; extensive use of reference returns to avoid unnecessary copies
- Named Values:
NamedValue/NamedMultiValuesprovide name binding for configuration/identification scenarios - Serde Support: All core types implement
Serialize/Deserialize - Ergonomic Defaults:
get_or,to_or, and list-default APIs accept scalar defaults, borrowed string literals, arrays, slices, vectors, and borrowed vectors - Flexible Collection Inputs:
MultiValues::new/set/addaccept direct arrays, slices, vectors, borrowed vectors, and borrowed string collections - Big Number Support: Full support for
BigIntandBigDecimalfor high-precision calculations - Extended Types: Native support for
isize/usize,Duration,Url,HashMap<String, String>, andserde_json::Value
📦 Core Types
Value: Single value container withEmpty(DataType)and 28 variants covering primitives, strings, date-time, big numbers, platform integers, duration, URL, string maps, and JSONMultiValues: Multi-value container corresponding toVec<T>enum variants, withEmpty(DataType)NamedValue: Name-boundValueprovidingDeref/DerefMutaccess to inner valueNamedMultiValues: Name-boundMultiValueswithDeref/DerefMutandto_named_value()conversionValueError&ValueResult<T>: Standard error type and result alias
Installation
Add this to your Cargo.toml:
[]
= "0.7"
Usage Examples
Single Value Operations
use ;
use DataType;
use BigInt;
use BigDecimal;
use FromStr;
// Generic construction and type-inferred retrieval
let v = new;
let port: i32 = v.get?; // Type inference from variable
assert_eq!;
// Named getter (returns Copy or reference)
assert_eq!;
// Type inference in function parameters
assert!; // Inferred as i32 from function signature
// Cross-type conversion via to<T>()
assert_eq!;
assert_eq!;
// Big number with type inference
let big_int = new;
let num: BigInt = big_int.get?; // Type inference
// Empty value and type management
let mut any = Int32;
any.clear;
assert!;
assert_eq!;
any.set_type;
any.set?;
assert_eq!;
Extended Types
use Value;
use Duration;
use Url;
use HashMap;
// Duration
let v = new;
let d: Duration = v.get?;
assert_eq!;
// String round-trip: "<nanoseconds>ns"
let s: String = v.to?;
assert_eq!;
let v2 = String;
let d2: Duration = v2.to?;
assert_eq!;
// Url
let url = parse.unwrap;
let v = new;
let got: Url = v.get?;
assert_eq!;
// Parse from string
let v2 = String;
let got2: Url = v2.to?;
assert_eq!;
// HashMap<String, String>
let mut map = new;
map.insert;
let v = new;
let got: = v.get?;
assert_eq!;
// JSON escape hatch
let j = json!;
let v = from_json_value;
let got: Value = v.get?;
assert_eq!;
// Serialize any type to JSON
let cfg = Config ;
let v = from_serializable?;
let restored: Config = v.deserialize_json?;
Multi-Value Operations
use ;
use DataType;
// Generic construction from a Vec<T>
let mut ports = new;
assert_eq!;
assert_eq!;
// Direct arrays, slices, vectors, and borrowed vectors are accepted
let array_ports = new;
let more_ports = ;
let borrowed = new;
let owned = vec!;
let borrowed_vec = new;
// String lists can be built directly from &str collections
let servers = new;
assert_eq!;
// Generic retrieval with type inference (clones Vec)
let nums: = ports.get?;
// Get first element
let first: i32 = ports.get_first?;
assert_eq!;
// Generic add: single / Vec / slice
ports.add?;
ports.add?;
ports.add?;
ports.add?;
// Generic set: replaces entire list
ports.set?;
ports.set?;
ports.set?;
assert_eq!;
// Merge (types must match)
let mut a = Int32;
let b = Int32;
a.merge?;
assert_eq!;
// Convert to single value (takes first element)
let single = a.to_value;
let first_val: i32 = single.get?;
assert_eq!;
Defaulted Reads and Conversions
Defaulted APIs use the fallback only when the value is empty or the list has no items. Type mismatches and failed conversions still return errors.
use DataType;
use ;
// Strict reads with defaults
let value = Empty;
let host: String = value.get_or?;
assert_eq!;
let value = String;
let port: u16 = value.to_or?;
assert_eq!;
// Multi-value strict reads with collection defaults
let values = Empty;
let paths: = values.get_or?;
assert_eq!;
// First-value conversion with a scalar default
let values = Empty;
let port: u16 = values.to_or?;
assert_eq!;
// List conversion with array or slice defaults
let values = Empty;
let tags: = values.to_list_or?;
assert_eq!;
Collection Argument Forms
The collection-style APIs accept the convenient forms you normally have at the
call site. This applies to MultiValues::new, MultiValues::set,
MultiValues::add, and defaulted list reads such as get_or and
to_list_or.
use DataType;
use MultiValues;
let array_values = new;
let slice_source = ;
let slice_values = new;
let vec_source = vec!;
let vec_values = new;
let borrowed_vec_values = new;
let mut values = Empty;
values.set?;
values.add?;
values.add?;
let strings = new;
let fallback: = Empty
.get_or?;
Named Value Operations
use ;
// Named single value
let mut nv = new;
assert_eq!;
let timeout: i32 = nv.get?;
assert_eq!;
nv.set_name;
nv.set?;
assert_eq!;
// Named multi-value
let mut nmv = new;
nmv.add?;
let first_port: i32 = nmv.get_first?;
assert_eq!;
// Named multi-value → Named single value (takes first element)
let first_named = nmv.to_named_value;
assert_eq!;
let val: i32 = first_named.get?;
assert_eq!;
API Reference
Generic API
Construction
- Single Value:
Value::new<T>(t) -> Value - Multi-Value:
MultiValues::new<S>(values) -> MultiValues
MultiValues::new accepts Vec<T>, &Vec<T>, &[T], [T; N], and
&[T; N]. For string values it also accepts Vec<&str>, &Vec<&str>,
&[&str], [&str; N], and &[&str; N], producing Vec<String> internally.
Supported T for new: bool, char, i8, i16, i32, i64, i128,
u8, u16, u32, u64, u128, f32, f64, String, &str,
NaiveDate, NaiveTime, NaiveDateTime, DateTime<Utc>, BigInt,
BigDecimal, isize, usize, Duration, Url,
HashMap<String, String>, serde_json::Value.
Retrieval
- Single Value:
Value::get<T>(&self) -> ValueResult<T> - Single Value with Default:
Value::get_or<T>(&self, default) -> ValueResult<T> - Multi-Value:
MultiValues::get<T>(&self) -> ValueResult<Vec<T>> - Multi-Value with Default:
MultiValues::get_or<T>(&self, default) -> ValueResult<Vec<T>> - First Element:
MultiValues::get_first<T>(&self) -> ValueResult<T> - First Element with Default:
MultiValues::get_first_or<T>(&self, default) -> ValueResult<T>
get<T>() performs strict type matching — the stored variant must be
exactly T. For cross-type conversion use to<T>() instead.
Mutation
- Single Value:
Value::set<T>(&mut self, t) -> ValueResult<()> - Multi-Value:
MultiValues::set<T, S>(&mut self, values: S) -> ValueResult<()>whereScan beT,Vec<T>,&Vec<T>,&[T],[T; N], or&[T; N]MultiValues::add<T, S>(&mut self, values: S)supportsT,Vec<T>,&Vec<T>,&[T],[T; N], or&[T; N]- String collections also accept
Vec<&str>,&Vec<&str>,&[&str],[&str; N], and&[&str; N]
Type Conversion
Value::to<T>(&self) -> ValueResult<T>— converts toTaccording to the rules defined byValueConverter<T>. Supports cross-type conversion with range checking where applicable.Value::to_or<T>(&self, default) -> ValueResult<T>— converts toT, or returns the default when the value is empty.Value::to_or_with<T>(&self, default, options) -> ValueResult<T>— same fallback behavior while using explicit conversion options.MultiValues::to<T>(&self) -> ValueResult<T>— converts the first stored value.MultiValues::to_or<T>(&self, default) -> ValueResult<T>— converts the first stored value, or returns the default when no value exists.MultiValues::to_or_with<T>(&self, default, options) -> ValueResult<T>— same fallback behavior while using explicit conversion options.MultiValues::to_list<T>(&self) -> ValueResult<Vec<T>>— converts all stored values.MultiValues::to_list_with<T>(&self, options) -> ValueResult<Vec<T>>— converts all stored values with explicit conversion options.MultiValues::to_list_or<T>(&self, default) -> ValueResult<Vec<T>>— converts all stored values, or returns the default when the result is empty.MultiValues::to_list_or_with<T>(&self, default, options) -> ValueResult<Vec<T>>— same list fallback behavior while using explicit conversion options.
Supported target types and their accepted source variants:
Target T |
Accepted source variants |
|---|---|
bool |
Bool; integer variants (0=false, non-zero=true); String values 1, 0, true, false (true/false are case-insensitive) |
i8 |
Int8; Bool; Char; all integer variants; Float32/64; String; BigInteger/BigDecimal |
i16 |
Int16; Bool; Char; all integer variants; Float32/64; String; BigInteger/BigDecimal |
i32 |
Int32; Bool; Char; all integer variants; Float32/64; String; BigInteger/BigDecimal |
i64 |
Int64; Bool; Char; all integer variants; Float32/64; String; BigInteger/BigDecimal |
i128 |
Int128; Bool; Char; all integer variants; Float32/64; String; BigInteger/BigDecimal |
isize |
IntSize; Bool; Char; all integer variants; Float32/64; String; BigInteger/BigDecimal |
u8 |
UInt8; Bool; Char; all integer variants (range checked); String |
u16 |
UInt8/16/32/64/128; Bool; Char; signed integer variants (range checked); String |
u32 |
UInt8/16/32/64/128; Bool; Char; signed integer variants (range checked); String |
u64 |
UInt8/16/32/64/128; Bool; Char; signed integer variants (range checked); String |
u128 |
UInt8/16/32/64/128; Bool; Char; signed integer variants (range checked); String |
usize |
UIntSize; Bool; Char; all integer variants (range checked); String |
f32 |
Float32/64; Bool; Char; all integer variants; String; BigInteger/BigDecimal |
f64 |
Float64; Bool; Char; all numeric variants; String; BigInteger/BigDecimal |
char |
Char |
String |
all variants (integers/floats/bool/char/date-time/Duration/Url/StringMap/Json) |
NaiveDate |
Date |
NaiveTime |
Time |
NaiveDateTime |
DateTime |
DateTime<Utc> |
Instant |
BigInt |
BigInteger |
BigDecimal |
BigDecimal |
Duration |
Duration; String (format: <nanoseconds>ns) |
Url |
Url; String |
HashMap<String, String> |
StringMap |
serde_json::Value |
Json; String (parsed as JSON); StringMap |
Named API
Single Value
- Getters:
get_xxx()methods —get_bool(),get_int32(),get_string(),get_duration(),get_url(),get_string_map(),get_json(), etc. - Setters:
set_xxx()methods —set_bool(),set_int32(),set_string(),set_duration(),set_url(),set_string_map(),set_json(), etc.
Multi-Value
- Getters:
get_xxxs()—get_int32s(),get_strings(),get_durations(),get_urls(),get_string_maps(),get_jsons(), etc. - Setters:
set_xxxs()—set_int32s(),set_strings(), etc. - Adders:
add_xxx()—add_int32(),add_string(),add_duration(),add_url(), etc. - Slice Operations:
*_slicevariants —set_int32s_slice(),add_strings_slice(), etc.
JSON Utilities (on Value)
Value::from_json_value(serde_json::Value) -> ValueValue::from_serializable<T: Serialize>(value: &T) -> ValueResult<Value>Value::deserialize_json<T: DeserializeOwned>(&self) -> ValueResult<T>
Utility Methods
Single Value
data_type()— get the data typeis_empty()— check if emptyclear()— clear the value (preserves type)set_type()— change the type
Multi-Value
count()— get element countis_empty()— check if emptyclear()— clear all values (preserves type)set_type()— change the typemerge()— merge with another multi-value (types must match)to_value()— convert to single value (takes first element)
Error Types
use ;
use DataType;
// Main error variants
NoValue // Empty value accessed
TypeMismatch // get<T>() type mismatch
ConversionFailed // to<T>() unsupported direction
ConversionError // to<T>() range/parse failure
IndexOutOfBounds // multi-value index error
JsonSerializationError // JSON serialization failure
JsonDeserializationError // JSON deserialization failure
All operations that may fail return ValueResult<T> = Result<T, ValueError>.
Supported Data Types
Basic Scalar Types
- Signed integers:
i8,i16,i32,i64,i128 - Unsigned integers:
u8,u16,u32,u64,u128 - Platform integers:
isize,usize - Floats:
f32,f64 - Other:
bool,char
String
String(stored directly)
Date/Time Types
NaiveDate,NaiveTime,NaiveDateTime,DateTime<Utc>(viachrono)
Big Number Types
BigInt,BigDecimal(vianum-bigintandbigdecimal)
Extended Types
isize/usize: Platform-dependent integersDuration:std::time::Duration; string representation<ns>nsUrl:url::Url; string representation is the URL textHashMap<String, String>: String map; string representation is JSONserde_json::Value: JSON escape hatch for complex/custom types
Serialization Support
All types implement Serialize/Deserialize:
Value,MultiValues,NamedValue,NamedMultiValues
Full type information is preserved during serialization and validated during deserialization.
Performance Notes
- Reference Returns:
get_string()returns&strto avoid cloning - Borrow Support:
Value::new()andset()accept&str(converted toString) - Smart Dispatch:
MultiValues::new/set/addaccept direct arrays, slices, vectors, and borrowed vectors, then dispatch to the optimal internal path - Borrowed Defaults: Defaulted reads can use borrowed string literals and borrowed collection values without forcing callers to allocate first
Dependencies
[]
= "0.2"
= { = "1.0", = ["derive"] }
= "1.0"
= "2.0"
= { = "0.4", = ["serde"] }
= { = "2.5", = ["serde"] }
= "0.2"
= { = "0.4", = ["serde"] }
= { = "0.4", = ["serde"] }
Testing & Code Coverage
This project maintains comprehensive test coverage with detailed validation of all functionality. For coverage reports and testing instructions, see the COVERAGE.md documentation.
License
Copyright (c) 2025 - 2026 Haixing Hu, Qubit Co. Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
See LICENSE for the full license text.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Author
Haixing Hu - Qubit Co. Ltd.
For more information about Qubit open source projects, visit our GitHub organization.