Skip to main content

triblespace_core/
value.rs

1//! Value type and conversion traits for schema types. For a deeper look at
2//! portability goals, common formats, and schema design, refer to the
3//! "Portability & Common Formats" chapter in the project book.
4//!
5//! # Example
6//!
7//! ```
8//! use triblespace_core::value::{Value, ValueSchema, ToValue, TryFromValue};
9//! use triblespace_core::metadata::ConstId;
10//! use triblespace_core::id::Id;
11//! use triblespace_core::macros::id_hex;
12//! use std::convert::{TryInto, Infallible};
13//!
14//! // Define a new schema type.
15//! // We're going to define an unsigned integer type that is stored as a little-endian 32-byte array.
16//! // Note that makes our example easier, as we don't have to worry about sign-extension or padding bytes.
17//! pub struct MyNumber;
18//!
19//! // Implement the ValueSchema trait for the schema type.
20//! impl ConstId for MyNumber {
21//!    const ID: Id = id_hex!("345EAC0C5B5D7D034C87777280B88AE2");
22//! }
23//! impl ValueSchema for MyNumber {
24//!    type ValidationError = ();
25//!    // Every bit pattern is valid for this schema.
26//! }
27//!
28//! // Implement conversion functions for the schema type.
29//! // Use `Error = Infallible` when the conversion cannot fail.
30//! impl TryFromValue<'_, MyNumber> for u32 {
31//!    type Error = Infallible;
32//!    fn try_from_value(v: &Value<MyNumber>) -> Result<Self, Infallible> {
33//!      Ok(u32::from_le_bytes(v.raw[0..4].try_into().unwrap()))
34//!    }
35//! }
36//!
37//! impl ToValue<MyNumber> for u32 {
38//!   fn to_value(self) -> Value<MyNumber> {
39//!      // Convert the Rust type to the schema type, i.e. a 32-byte array.
40//!      let mut bytes = [0; 32];
41//!      bytes[0..4].copy_from_slice(&self.to_le_bytes());
42//!      Value::new(bytes)
43//!   }
44//! }
45//!
46//! // Use the schema type to store and retrieve a Rust type.
47//! let value: Value<MyNumber> = MyNumber::value_from(42u32);
48//! let i: u32 = value.from_value();
49//! assert_eq!(i, 42);
50//!
51//! // You can also implement conversion functions for other Rust types.
52//! impl TryFromValue<'_, MyNumber> for u64 {
53//!   type Error = Infallible;
54//!   fn try_from_value(v: &Value<MyNumber>) -> Result<Self, Infallible> {
55//!    Ok(u64::from_le_bytes(v.raw[0..8].try_into().unwrap()))
56//!   }
57//! }
58//!
59//! impl ToValue<MyNumber> for u64 {
60//!  fn to_value(self) -> Value<MyNumber> {
61//!   let mut bytes = [0; 32];
62//!   bytes[0..8].copy_from_slice(&self.to_le_bytes());
63//!   Value::new(bytes)
64//!   }
65//! }
66//!
67//! let value: Value<MyNumber> = MyNumber::value_from(42u64);
68//! let i: u64 = value.from_value();
69//! assert_eq!(i, 42);
70//!
71//! // And use a value round-trip to convert between Rust types.
72//! let value: Value<MyNumber> = MyNumber::value_from(42u32);
73//! let i: u64 = value.from_value();
74//! assert_eq!(i, 42);
75//! ```
76
77pub mod schemas;
78
79use crate::metadata::ConstId;
80
81use core::fmt;
82use std::borrow::Borrow;
83use std::cmp::Ordering;
84use std::fmt::Debug;
85use std::hash::Hash;
86use std::marker::PhantomData;
87
88use hex::ToHex;
89use zerocopy::Immutable;
90use zerocopy::IntoBytes;
91use zerocopy::KnownLayout;
92use zerocopy::TryFromBytes;
93use zerocopy::Unaligned;
94
95/// The length of a value in bytes.
96pub const VALUE_LEN: usize = 32;
97
98/// A raw value is simply a 32-byte array.
99pub type RawValue = [u8; VALUE_LEN];
100
101/// A value is a 32-byte array that can be (de)serialized as a Rust type.
102/// The schema type parameter is an abstract type that represents the meaning
103/// and valid bit patterns of the bytes.
104///
105/// # Example
106///
107/// ```
108/// use triblespace_core::prelude::*;
109/// use valueschemas::R256;
110/// use num_rational::Ratio;
111///
112/// let ratio = Ratio::new(1, 2);
113/// let value: Value<R256> = R256::value_from(ratio);
114/// let ratio2: Ratio<i128> = value.try_from_value().unwrap();
115/// assert_eq!(ratio, ratio2);
116/// ```
117#[derive(TryFromBytes, IntoBytes, Unaligned, Immutable, KnownLayout)]
118#[repr(transparent)]
119pub struct Value<T: ValueSchema> {
120    pub raw: RawValue,
121    _schema: PhantomData<T>,
122}
123
124impl<S: ValueSchema> Value<S> {
125    /// Create a new value from a 32-byte array.
126    ///
127    /// # Example
128    ///
129    /// ```
130    /// use triblespace_core::value::{Value, ValueSchema};
131    /// use triblespace_core::value::schemas::UnknownValue;
132    ///
133    /// let bytes = [0; 32];
134    /// let value = Value::<UnknownValue>::new(bytes);
135    /// ```
136    pub fn new(value: RawValue) -> Self {
137        Self {
138            raw: value,
139            _schema: PhantomData,
140        }
141    }
142
143    /// Validate this value using its schema.
144    pub fn validate(self) -> Result<Self, S::ValidationError> {
145        S::validate(self)
146    }
147
148    /// Check if this value conforms to its schema.
149    pub fn is_valid(&self) -> bool {
150        S::validate(*self).is_ok()
151    }
152
153    /// Transmute a value from one schema type to another.
154    /// This is a safe operation, as the bytes are not changed.
155    /// The schema type is only changed in the type system.
156    /// This is a zero-cost operation.
157    /// This is useful when you have a value with an abstract schema type,
158    /// but you know the concrete schema type.
159    pub fn transmute<O>(self) -> Value<O>
160    where
161        O: ValueSchema,
162    {
163        Value::new(self.raw)
164    }
165
166    /// Transmute a value reference from one schema type to another.
167    /// This is a safe operation, as the bytes are not changed.
168    /// The schema type is only changed in the type system.
169    /// This is a zero-cost operation.
170    /// This is useful when you have a value reference with an abstract schema type,
171    /// but you know the concrete schema type.
172    pub fn as_transmute<O>(&self) -> &Value<O>
173    where
174        O: ValueSchema,
175    {
176        unsafe { std::mem::transmute(self) }
177    }
178
179    /// Transmute a raw value reference to a value reference.
180    ///
181    /// # Example
182    ///
183    /// ```
184    /// use triblespace_core::value::{Value, ValueSchema};
185    /// use triblespace_core::value::schemas::UnknownValue;
186    /// use std::borrow::Borrow;
187    ///
188    /// let bytes = [0; 32];
189    /// let value: Value<UnknownValue> = Value::new(bytes);
190    /// let value_ref: &Value<UnknownValue> = &value;
191    /// let raw_value_ref: &[u8; 32] = value_ref.borrow();
192    /// let value_ref2: &Value<UnknownValue> = Value::as_transmute_raw(raw_value_ref);
193    /// assert_eq!(&value, value_ref2);
194    /// ```
195    pub fn as_transmute_raw(value: &RawValue) -> &Self {
196        unsafe { std::mem::transmute(value) }
197    }
198
199    /// Deserialize a value with an abstract schema type to a concrete Rust type.
200    ///
201    /// This method only works for infallible conversions (where `Error = Infallible`).
202    /// For fallible conversions, use the [Value::try_from_value] method.
203    ///
204    /// # Example
205    ///
206    /// ```
207    /// use triblespace_core::prelude::*;
208    /// use valueschemas::F64;
209    ///
210    /// let value: Value<F64> = (3.14f64).to_value();
211    /// let concrete: f64 = value.from_value();
212    /// ```
213    pub fn from_value<'a, T>(&'a self) -> T
214    where
215        T: TryFromValue<'a, S, Error = std::convert::Infallible>,
216    {
217        match <T as TryFromValue<'a, S>>::try_from_value(self) {
218            Ok(v) => v,
219            Err(e) => match e {},
220        }
221    }
222
223    /// Deserialize a value with an abstract schema type to a concrete Rust type.
224    ///
225    /// This method returns an error if the conversion is not possible.
226    /// This might happen if the bytes are not valid for the schema type or if the
227    /// rust type can't represent the specific value of the schema type,
228    /// e.g. if the schema type is a fractional number and the rust type is an integer.
229    ///
230    /// For infallible conversions, use the [Value::from_value] method.
231    ///
232    /// # Example
233    ///
234    /// ```
235    /// use triblespace_core::prelude::*;
236    /// use valueschemas::R256;
237    /// use num_rational::Ratio;
238    ///
239    /// let value: Value<R256> = R256::value_from(Ratio::new(1, 2));
240    /// let concrete: Result<Ratio<i128>, _> = value.try_from_value();
241    /// ```
242    ///
243    pub fn try_from_value<'a, T>(&'a self) -> Result<T, <T as TryFromValue<'a, S>>::Error>
244    where
245        T: TryFromValue<'a, S>,
246    {
247        <T as TryFromValue<'a, S>>::try_from_value(self)
248    }
249}
250
251impl<T: ValueSchema> Copy for Value<T> {}
252
253impl<T: ValueSchema> Clone for Value<T> {
254    fn clone(&self) -> Self {
255        *self
256    }
257}
258
259impl<T: ValueSchema> PartialEq for Value<T> {
260    fn eq(&self, other: &Self) -> bool {
261        self.raw == other.raw
262    }
263}
264
265impl<T: ValueSchema> Eq for Value<T> {}
266
267impl<T: ValueSchema> Hash for Value<T> {
268    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
269        self.raw.hash(state);
270    }
271}
272
273impl<T: ValueSchema> Ord for Value<T> {
274    fn cmp(&self, other: &Self) -> Ordering {
275        self.raw.cmp(&other.raw)
276    }
277}
278
279impl<T: ValueSchema> PartialOrd for Value<T> {
280    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
281        Some(self.cmp(other))
282    }
283}
284
285impl<S: ValueSchema> Borrow<RawValue> for Value<S> {
286    fn borrow(&self) -> &RawValue {
287        &self.raw
288    }
289}
290
291impl<T: ValueSchema> Debug for Value<T> {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        write!(
294            f,
295            "Value<{}>({})",
296            std::any::type_name::<T>(),
297            ToHex::encode_hex::<String>(&self.raw)
298        )
299    }
300}
301
302/// A trait that represents an abstract schema type that can be (de)serialized as a [Value].
303///
304/// This trait is usually implemented on a type-level empty struct,
305/// but may contain additional information about the schema type as associated constants or types.
306/// The [Handle](crate::value::schemas::hash::Handle) type for example contains type information about the hash algorithm,
307/// and the schema of the referenced blob.
308///
309/// See the [value](crate::value) module for more information.
310/// See the [BlobSchema](crate::blob::BlobSchema) trait for the counterpart trait for blobs.
311pub trait ValueSchema: ConstId + Sized + 'static {
312    type ValidationError;
313
314    /// Check if the given value conforms to this schema.
315    fn validate(value: Value<Self>) -> Result<Value<Self>, Self::ValidationError> {
316        Ok(value)
317    }
318
319    /// Create a new value from a concrete Rust type.
320    /// This is a convenience method that calls the [ToValue] trait.
321    /// This method might panic if the conversion is not possible.
322    ///
323    /// See the [ValueSchema::value_try_from] method for a conversion that returns a result.
324    fn value_from<T: ToValue<Self>>(t: T) -> Value<Self> {
325        t.to_value()
326    }
327
328    /// Create a new value from a concrete Rust type.
329    /// This is a convenience method that calls the [TryToValue] trait.
330    /// This method might return an error if the conversion is not possible.
331    ///
332    /// See the [ValueSchema::value_from] method for a conversion that always succeeds (or panics).
333    fn value_try_from<T: TryToValue<Self>>(
334        t: T,
335    ) -> Result<Value<Self>, <T as TryToValue<Self>>::Error> {
336        t.try_to_value()
337    }
338}
339
340/// A trait for converting a Rust type to a [Value] with a specific schema type.
341/// This trait is implemented on the concrete Rust type.
342///
343/// This might cause a panic if the conversion is not possible,
344/// see [TryToValue] for a conversion that returns a result.
345///
346/// This is the counterpart to the [TryFromValue] trait.
347///
348/// See [ToBlob](crate::blob::ToBlob) for the counterpart trait for blobs.
349pub trait ToValue<S: ValueSchema> {
350    /// Convert the Rust type to a [Value] with a specific schema type.
351    /// This might cause a panic if the conversion is not possible.
352    ///
353    /// See the [TryToValue] trait for a conversion that returns a result.
354    fn to_value(self) -> Value<S>;
355}
356
357/// A trait for converting a Rust type to a [Value] with a specific schema type.
358/// This trait is implemented on the concrete Rust type.
359///
360/// This might return an error if the conversion is not possible,
361/// see [ToValue] for cases where the conversion is guaranteed to succeed (or panic).
362///
363/// This is the counterpart to the [TryFromValue] trait.
364///
365pub trait TryToValue<S: ValueSchema> {
366    type Error;
367    /// Convert the Rust type to a [Value] with a specific schema type.
368    /// This might return an error if the conversion is not possible.
369    ///
370    /// See the [ToValue] trait for a conversion that always succeeds (or panics).
371    fn try_to_value(self) -> Result<Value<S>, Self::Error>;
372}
373
374/// A trait for converting a [Value] with a specific schema type to a Rust type.
375/// This trait is implemented on the concrete Rust type.
376///
377/// Values are 32-byte arrays that represent data at a deserialization boundary.
378/// Conversions may fail depending on the schema and target type. Use
379/// `Error = Infallible` for conversions that genuinely cannot fail (e.g.
380/// `ethnum::U256` from `U256BE`), and a real error type for narrowing
381/// conversions (e.g. `u64` from `U256BE`).
382///
383/// This is the counterpart to the [TryToValue] trait.
384///
385/// See [TryFromBlob](crate::blob::TryFromBlob) for the counterpart trait for blobs.
386pub trait TryFromValue<'a, S: ValueSchema>: Sized {
387    type Error;
388    /// Convert the [Value] with a specific schema type to the Rust type.
389    fn try_from_value(v: &'a Value<S>) -> Result<Self, Self::Error>;
390}
391
392impl<S: ValueSchema> ToValue<S> for Value<S> {
393    fn to_value(self) -> Value<S> {
394        self
395    }
396}
397
398impl<S: ValueSchema> ToValue<S> for &Value<S> {
399    fn to_value(self) -> Value<S> {
400        *self
401    }
402}
403
404impl<'a, S: ValueSchema> TryFromValue<'a, S> for Value<S> {
405    type Error = std::convert::Infallible;
406    fn try_from_value(v: &'a Value<S>) -> Result<Self, std::convert::Infallible> {
407        Ok(*v)
408    }
409}
410
411impl<'a, S: ValueSchema> TryFromValue<'a, S> for () {
412    type Error = std::convert::Infallible;
413    fn try_from_value(_v: &'a Value<S>) -> Result<Self, std::convert::Infallible> {
414        Ok(())
415    }
416}