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 - Type Safety: Enum variants carry static types; failures are expressed
- Zero-Cost Abstractions: Basic types are stored directly; extensive use of
- Named Values:
NamedValue/NamedMultiValuesprovide name binding for - Serde Support: All core types implement
Serialize/Deserialize - Ergonomic Defaults:
get_or,to_or, and list-default APIs accept - Flexible Collection Inputs:
MultiValues::new/set/addaccept direct - Big Number Support: Full support for
BigIntandBigDecimalfor - Extended Types: Native support for
isize/usize,Duration,Url,
supported data types
through Result<T, ValueError>
reference returns to avoid unnecessary copies
configuration/identification scenarios
scalar defaults, borrowed string literals, arrays, slices, vectors, and borrowed vectors
arrays, slices, vectors, borrowed vectors, and borrowed string collections
high-precision calculations
HashMap<String, String>, and serde_json::Value
π¦ Core Types
Value: Single value container withEmpty(DataType)and 28 variantsMultiValues: Multi-value container corresponding toVec<T>enumNamedValue: Name-boundValueprovidingDeref/DerefMutaccess toNamedMultiValues: Name-boundMultiValueswithDeref/DerefMutandValueError&ValueResult<T>: Standard error type and result alias
covering primitives, strings, date-time, big numbers, platform integers, duration, URL, string maps, and JSON
variants, with Empty(DataType)
inner value
to_named_value() conversion
Installation
Add this to your Cargo.toml:
[dependencies]
qubit-value = "0.7"
Usage Examples
Single Value Operations
use qubit_value::{Value, ValueError};
use qubit_datatype::DataType;
use num_bigint::BigInt;
use bigdecimal::BigDecimal;
use std::str::FromStr;
// Generic construction and type-inferred retrieval
let v = Value::new(8080i32);
let port: i32 = v.get()?; // Type inference from variable
assert_eq!(port, 8080);
// Named getter (returns Copy or reference)
assert_eq!(v.get_int32()?, 8080);
// Type inference in function parameters
fn check_port(p: i32) -> bool { p > 1024 }
assert!(check_port(v.get()?)); // Inferred as i32 from function signature
// Cross-type conversion via to<T>()
assert_eq!(v.to::<i64>()?, 8080i64);
assert_eq!(v.to::<String>()?, "8080".to_string());
// Big number with type inference
let big_int = Value::new(BigInt::from(12345678901234567890i64));
let num: BigInt = big_int.get()?; // Type inference
// Empty value and type management
let mut any = Value::Int32(42);
any.clear();
assert!(any.is_empty());
assert_eq!(any.data_type(), DataType::Int32);
any.set_type(DataType::String);
any.set("hello")?;
assert_eq!(any.get_string()?, "hello");
Extended Types
use qubit_value::Value;
use std::time::Duration;
use url::Url;
use std::collections::HashMap;
// Duration
let v = Value::new(Duration::from_secs(30));
let d: Duration = v.get()?;
assert_eq!(d, Duration::from_secs(30));
// Default String conversion uses milliseconds.
let s: String = v.to()?;
assert_eq!(s, "30000ms");
let v2 = Value::String("30s".to_string());
let d2: Duration = v2.to()?;
assert_eq!(d2, Duration::from_secs(30));
// Url
let url = Url::parse("https://example.com").unwrap();
let v = Value::new(url.clone());
let got: Url = v.get()?;
assert_eq!(got, url);
// Parse from string
let v2 = Value::String("https://example.com".to_string());
let got2: Url = v2.to()?;
assert_eq!(got2, url);
// HashMap<String, String>
let mut map = HashMap::new();
map.insert("host".to_string(), "localhost".to_string());
let v = Value::new(map.clone());
let got: HashMap<String, String> = v.get()?;
assert_eq!(got, map);
// JSON escape hatch
let j = serde_json::json!({"key": "value"});
let v = Value::from_json_value(j.clone());
let got: serde_json::Value = v.get()?;
assert_eq!(got, j);
// Serialize any type to JSON
#[derive(serde::Serialize, serde::Deserialize)]
struct Config { host: String, port: u16 }
let cfg = Config { host: "localhost".to_string(), port: 8080 };
let v = Value::from_serializable(&cfg)?;
let restored: Config = v.deserialize_json()?;
Multi-Value Operations
use qubit_value::{MultiValues, ValueError};
use qubit_datatype::DataType;
// Generic construction from a Vec<T>
let mut ports = MultiValues::new(vec![8080i32, 8081, 8082]);
assert_eq!(ports.count(), 3);
assert_eq!(ports.get_int32s()?, &[8080, 8081, 8082]);
// Direct arrays, slices, vectors, and borrowed vectors are accepted
let array_ports = MultiValues::new([8080i32, 8081, 8082]);
let more_ports = [9000i32, 9001];
let borrowed = MultiValues::new(more_ports.as_slice());
let owned = vec![7000i32, 7001];
let borrowed_vec = MultiValues::new(&owned);
// String lists can be built directly from &str collections
let servers = MultiValues::new(["api", "worker", "cache"]);
assert_eq!(servers.get_strings()?, &["api", "worker", "cache"]);
// Generic retrieval with type inference (clones Vec)
let nums: Vec<i32> = ports.get()?;
// Get first element
let first: i32 = ports.get_first()?;
assert_eq!(first, 8080);
// Generic add: single / Vec / slice
ports.add(8083)?;
ports.add(vec![8084, 8085])?;
ports.add(&[8086, 8087][..])?;
ports.add([8088, 8089])?;
// Generic set: replaces entire list
ports.set(vec![9001, 9002])?;
ports.set([9100, 9101])?;
ports.set(&owned)?;
assert_eq!(ports.get_int32s()?, &[7000, 7001]);
// Merge (types must match)
let mut a = MultiValues::Int32(vec![1, 2]);
let b = MultiValues::Int32(vec![3, 4]);
a.merge(&b)?;
assert_eq!(a.get_int32s()?, &[1, 2, 3, 4]);
// Convert to single value (takes first element)
let single = a.to_value();
let first_val: i32 = single.get()?;
assert_eq!(first_val, 1);
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 qubit_datatype::DataType;
use qubit_value::{MultiValues, Value};
// Strict reads with defaults
let value = Value::Empty(DataType::String);
let host: String = value.get_or("localhost")?;
assert_eq!(host, "localhost");
let value = Value::String("8080".to_string());
let port: u16 = value.to_or(9000u16)?;
assert_eq!(port, 8080);
// Multi-value strict reads with collection defaults
let values = MultiValues::Empty(DataType::String);
let paths: Vec<String> = values.get_or(["cache", "tmp"])?;
assert_eq!(paths, vec!["cache".to_string(), "tmp".to_string()]);
// First-value conversion with a scalar default
let values = MultiValues::Empty(DataType::UInt16);
let port: u16 = values.to_or(8080u16)?;
assert_eq!(port, 8080);
// List conversion with array or slice defaults
let values = MultiValues::Empty(DataType::String);
let tags: Vec<String> = values.to_list_or(["blue", "green"])?;
assert_eq!(tags, vec!["blue".to_string(), "green".to_string()]);
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 qubit_datatype::DataType;
use qubit_value::MultiValues;
let array_values = MultiValues::new([1i32, 2, 3]);
let slice_source = [4i32, 5, 6];
let slice_values = MultiValues::new(slice_source.as_slice());
let vec_source = vec![7i32, 8, 9];
let vec_values = MultiValues::new(vec_source.clone());
let borrowed_vec_values = MultiValues::new(&vec_source);
let mut values = MultiValues::Empty(DataType::Int32);
values.set([10, 11, 12])?;
values.add(slice_source.as_slice())?;
values.add(&vec_source)?;
let strings = MultiValues::new(["api", "worker"]);
let fallback: Vec<String> = MultiValues::Empty(DataType::String)
.get_or(["cache", "tmp"])?;
Named Value Operations
use qubit_value::{NamedValue, NamedMultiValues, Value, MultiValues};
// Named single value
let mut nv = NamedValue::new("timeout", Value::new(30i32));
assert_eq!(nv.name(), "timeout");
let timeout: i32 = nv.get()?;
assert_eq!(timeout, 30);
nv.set_name("read_timeout");
nv.set(45i32)?;
assert_eq!(nv.get_int32()?, 45);
// Named multi-value
let mut nmv = NamedMultiValues::new("ports", MultiValues::new(vec![8080i32, 8081]));
nmv.add(8082)?;
let first_port: i32 = nmv.get_first()?;
assert_eq!(first_port, 8080);
// Named multi-value β Named single value (takes first element)
let first_named = nmv.to_named_value();
assert_eq!(first_named.name(), "ports");
let val: i32 = first_named.get()?;
assert_eq!(val, 8080);
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<()>whereMultiValues::add<T, S>(&mut self, values: S)supportsT,Vec<T>,- String collections also accept
Vec<&str>,&Vec<&str>,&[&str],
S can be T, Vec<T>, &Vec<T>, &[T], [T; N], or &[T; N]
&Vec<T>, &[T], [T; N], or &[T; N]
[&str; N], and &[&str; N]
Type Conversion
Value::to<T>(&self) -> ValueResult<T>β converts toTaccording toValue::to_or<T>(&self, default) -> ValueResult<T>β converts toT,Value::to_or_with<T>(&self, default, options) -> ValueResult<T>βMultiValues::to<T>(&self) -> ValueResult<T>β converts the first storedMultiValues::to_or<T>(&self, default) -> ValueResult<T>β converts theMultiValues::to_or_with<T>(&self, default, options) -> ValueResult<T>βMultiValues::to_list<T>(&self) -> ValueResult<Vec<T>>β converts allMultiValues::to_list_with<T>(&self, options) -> ValueResult<Vec<T>>βMultiValues::to_list_or<T>(&self, default) -> ValueResult<Vec<T>>βMultiValues::to_list_or_with<T>(&self, default, options) -> ValueResult<Vec<T>>β
the shared conversion rules. Supports cross-type conversion with range checking where applicable.
or returns the default when the value is empty.
same fallback behavior while using explicit conversion options.
value.
first stored value, or returns the default when no value exists.
same fallback behavior while using explicit conversion options.
stored values.
converts all stored values with explicit conversion options.
converts all stored values, or returns the default when the result is empty.
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; integer variants and BigInteger using the configured duration unit; String with optional ns/us/ms/s/m/h/d suffix, or the configured duration unit when no suffix is present |
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(), - Setters:
set_xxx()methods βset_bool(),set_int32(),
get_string(), get_duration(), get_url(), get_string_map(), get_json(), etc.
set_string(), set_duration(), set_url(), set_string_map(), set_json(), etc.
Multi-Value
- Getters:
get_xxxs()βget_int32s(),get_strings(), - Setters:
set_xxxs()βset_int32s(),set_strings(), etc. - Adders:
add_xxx()βadd_int32(),add_string(),add_duration(), - Slice Operations:
*_slicevariants βset_int32s_slice(),
get_durations(), get_urls(), get_string_maps(), get_jsons(), etc.
add_url(), etc.
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 qubit_value::{ValueError, ValueResult};
use qubit_datatype::DataType;
// Main error variants
ValueError::NoValue // Empty value accessed
ValueError::TypeMismatch { expected, actual }// get<T>() type mismatch
ValueError::ConversionFailed { from, to } // to<T>() unsupported direction
ValueError::ConversionError(String) // to<T>() range/parse failure
ValueError::IndexOutOfBounds { index, len } // multi-value index error
ValueError::JsonSerializationError(String) // JSON serialization failure
ValueError::JsonDeserializationError(String) // 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 conversion uses theUrl: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
configured duration unit, defaulting to milliseconds such as 1500ms. Parsing accepts ns, us, ms, s, m, h, and d suffixes; strings without a suffix are interpreted using the configured duration unit.
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 to - Flexible Inputs:
MultiValues::new/set/addaccept direct arrays, slices, - Borrowed Defaults: Defaulted reads can use borrowed string literals and
String)
vectors, and borrowed vectors for supported element types
borrowed collection values without forcing callers to allocate first
Dependencies
[dependencies]
qubit-datatype = "0.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "2.0"
chrono = { version = "0.4", features = ["serde"] }
url = { version = "2.5", features = ["serde"] }
num-bigint = { version = "0.4", features = ["serde"] }
bigdecimal = { version = "0.4", features = ["serde"] }
Testing
This project maintains comprehensive test coverage with detailed validation of all functionality. Run ./ci-check.sh before publishing or committing changes.
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.