ciphercore_base/
data_values.rs

1//! Definition of the [Value] struct and related functions, which handle data values within CipherCore.
2use std::convert::TryInto;
3use std::fmt;
4use std::fmt::Debug;
5use std::hash::{Hash, Hasher};
6use std::ops::Not;
7use std::sync::Arc;
8
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10
11use crate::bytes::{vec_to_bytes, vec_u128_from_bytes, vec_u64_to_bytes};
12use crate::data_types::{array_type, get_size_in_bits, get_types_vector, ScalarType, Type, BIT};
13use crate::errors::Result;
14
15use crate::version::{VersionedData, DATA_VERSION};
16
17#[cfg(feature = "py-binding")]
18use pywrapper_macro::{impl_wrapper, struct_wrapper};
19
20#[derive(Clone, Debug, Serialize, Deserialize)]
21enum SerializableValueBody {
22    Bytes(Vec<u8>),
23    Vector(Vec<SerializableValue>),
24}
25
26#[derive(Clone, Debug, Serialize, Deserialize)]
27struct SerializableValue {
28    body: Arc<SerializableValueBody>,
29}
30
31impl SerializableValue {
32    pub fn from_bytes(bytes: Vec<u8>) -> Self {
33        Self {
34            body: Arc::new(SerializableValueBody::Bytes(bytes)),
35        }
36    }
37
38    pub fn from_vector(v: Vec<SerializableValue>) -> Self {
39        Self {
40            body: Arc::new(SerializableValueBody::Vector(v)),
41        }
42    }
43
44    pub fn access<FB, FV, R>(&self, f_bytes: FB, f_vector: FV) -> Result<R>
45    where
46        FB: FnOnce(&[u8]) -> Result<R>,
47        FV: FnOnce(&Vec<SerializableValue>) -> Result<R>,
48    {
49        match self.body.as_ref() {
50            SerializableValueBody::Bytes(bytes) => f_bytes(bytes),
51            SerializableValueBody::Vector(v) => f_vector(v),
52        }
53    }
54
55    pub fn from_value(value: &Value) -> Self {
56        value
57            .access(
58                |bytes| Ok(SerializableValue::from_bytes(bytes.to_vec())),
59                |vector| {
60                    let mut v_new = vec![];
61                    for item in vector {
62                        v_new.push(SerializableValue::from_value(item));
63                    }
64                    Ok(SerializableValue::from_vector(v_new))
65                },
66            )
67            .expect("Error during conversion from Value to SerializableValue!")
68    }
69}
70
71/// Bytes are in the little-endian form
72#[derive(Clone, Debug, PartialEq, Eq)]
73enum ValueBody {
74    Bytes(Vec<u8>),
75    Vector(Vec<Value>),
76}
77
78impl Value {
79    /// Creates a fully disjoint clone of `self` via recursive traversal.
80    ///
81    /// # Returns
82    ///
83    /// Clone of `self`
84    pub fn deep_clone(&self) -> Value {
85        self.access(
86            |bytes| Ok(Value::from_bytes(bytes.to_vec())),
87            |vector| {
88                let mut v_new = vec![];
89                for item in vector {
90                    v_new.push(item.deep_clone());
91                }
92                Ok(Value::from_vector(v_new))
93            },
94        )
95        .unwrap()
96    }
97
98    /// Hashes `self` via recursive traversal.
99    ///
100    /// # Arguments
101    ///
102    /// `state` - hasher used for hashing
103    pub fn deep_hash<H: Hasher>(&self, state: &mut H) {
104        // Can't use `self.access()` here,
105        // since both branches require write access to `state`.
106        match self.body.as_ref() {
107            ValueBody::Bytes(data) => {
108                data.hash(state);
109            }
110            ValueBody::Vector(elements) => {
111                for element in elements {
112                    element.deep_hash(state);
113                }
114            }
115        }
116    }
117}
118
119/// A structure that stores pointer to a value that corresponds to an input, output or an intermediate result of
120/// a computation.
121///
122/// A value is:
123///   * Either a vector of bytes (for scalars or arrays);
124///   * Or a vector of pointers to other values (for vectors, tuples or named tuples).
125///
126/// Overall, a value can be seen as a rooted tree of byte vectors.
127///
128/// [Clone] trait duplicates the pointer, not the underlying value (see [Value::deep_clone] for deep cloning).
129///
130/// [PartialEq] trait performs the deep recursive comparison.
131#[derive(PartialEq, Eq, Clone)]
132#[cfg_attr(feature = "py-binding", struct_wrapper)]
133pub struct Value {
134    body: Arc<ValueBody>,
135}
136
137impl Serialize for Value {
138    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
139    where
140        S: Serializer,
141    {
142        let versioned_value = self
143            .to_versioned_data()
144            .expect("Error during conversion from Value into VersionedData");
145        versioned_value.serialize(serializer)
146    }
147}
148
149impl<'de> Deserialize<'de> for Value {
150    fn deserialize<D>(deserializer: D) -> std::result::Result<Value, D::Error>
151    where
152        D: Deserializer<'de>,
153    {
154        let versioned_value = VersionedData::deserialize(deserializer)?;
155        if !versioned_value.check_version(DATA_VERSION) {
156            Err(runtime_error!(
157                "Value version doesn't match the requirement"
158            ))
159            .map_err(serde::de::Error::custom)
160        } else {
161            let serializable_value =
162                serde_json::from_str::<SerializableValue>(versioned_value.get_data_string())
163                    .expect("Error during conversion from String to SerializableValue!");
164            Value::from_serializable_value(serializable_value).map_err(serde::de::Error::custom)
165        }
166    }
167}
168
169impl fmt::Display for Value {
170    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171        match serde_json::to_string(&self) {
172            Ok(s) => write!(f, "{s}"),
173            Err(_err) => Err(fmt::Error::default()),
174        }
175    }
176}
177
178fn recursively_pretty_print_value(
179    val: &Value,
180    f: &mut fmt::Formatter,
181    indent: &str,
182) -> fmt::Result {
183    match val.body.as_ref() {
184        ValueBody::Bytes(bytes) => {
185            write!(f, "{indent}[")?;
186            let l = bytes.len();
187            for byte in &bytes[..usize::min(l, 256)] {
188                write!(f, "{byte:02x}")?;
189            }
190            if l > 256 {
191                write!(f, "...")?;
192            }
193            writeln!(f, "],")?;
194        }
195        ValueBody::Vector(vals) => {
196            writeln!(f, "{indent}[")?;
197            let l = vals.len();
198            for val in &vals[..usize::min(l, 8)] {
199                recursively_pretty_print_value(val, f, &format!("{indent}  "))?;
200            }
201            if l > 8 {
202                writeln!(f, "{indent}...")?;
203            }
204            writeln!(f, "{indent}],")?;
205        }
206    }
207    Ok(())
208}
209
210impl Debug for Value {
211    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212        recursively_pretty_print_value(self, f, "")
213    }
214}
215
216#[cfg_attr(feature = "py-binding", impl_wrapper)]
217impl Value {
218    /// Constructs a value from a given byte buffer.
219    ///
220    /// Not recommended to be used directly (instead, please use higher-level wrappers such as [Value::from_scalar]).
221    ///
222    /// # Arguments
223    ///
224    /// `bytes` - byte vector
225    ///
226    /// # Returns
227    ///
228    /// New value
229    pub fn from_bytes(bytes: Vec<u8>) -> Self {
230        Self {
231            body: Arc::new(ValueBody::Bytes(bytes)),
232        }
233    }
234
235    /// Constructs a value from a vector of other values.
236    ///
237    /// # Arguments
238    ///
239    /// `v` - vector of values
240    ///
241    /// # Returns
242    ///
243    /// New value constructed from `v`
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// # use ciphercore_base::data_values::Value;
249    /// let v = Value::from_vector(
250    ///     vec![
251    ///         Value::from_bytes(vec![1, 2, 3]),
252    ///         Value::from_bytes(vec![4, 5, 6]),
253    ///         Value::from_vector(vec![])]);
254    /// ```
255    pub fn from_vector(v: Vec<Value>) -> Self {
256        Self {
257            body: Arc::new(ValueBody::Vector(v)),
258        }
259    }
260
261    /// Returns bytes if the value is a vector of bytes else returns None.
262    ///
263    /// # Returns
264    ///
265    /// Vector of bytes or None.
266    #[cfg_attr(not(feature = "py-binding"), allow(dead_code))]
267    fn get_bytes(&self) -> Option<Vec<u8>> {
268        self.access(|bytes| Ok(Some(bytes.to_vec())), |_sub_values| Ok(None))
269            .unwrap()
270    }
271
272    /// Returns vector of Value if the value is vector of pointers to other values else returns None.
273    ///
274    /// # Returns
275    ///
276    /// Vector of Value or None.
277    #[cfg_attr(not(feature = "py-binding"), allow(dead_code))]
278    fn get_sub_values(&self) -> Option<Vec<Value>> {
279        self.access(|_bytes| Ok(None), |sub_values| Ok(Some(sub_values.clone())))
280            .unwrap()
281    }
282}
283
284impl Value {
285    /// Constructs a value from a given bit or integer scalar.
286    ///
287    /// # Arguments
288    ///
289    /// * `x` - scalar to be converted to a value, can be of any standard integer type
290    /// * `st` - scalar type corresponding to `x`
291    ///
292    /// # Returns
293    ///
294    /// New value constructed from `x`
295    ///
296    /// # Examples
297    ///
298    /// ```
299    /// # use ciphercore_base::data_values::Value;
300    /// # use ciphercore_base::data_types::INT32;
301    /// let v = Value::from_scalar(-123456, INT32).unwrap();
302    /// v.access_bytes(|bytes| {
303    ///     assert_eq!(*bytes, vec![192, 29, 254, 255]);
304    ///     Ok(())
305    /// }).unwrap();
306    /// ```
307    pub fn from_scalar<T: TryInto<u128> + Not<Output = T> + TryInto<u8> + Copy>(
308        x: T,
309        st: ScalarType,
310    ) -> Result<Self> {
311        let v = vec![x];
312        Ok(Value::from_bytes(vec_to_bytes(&v, st)?))
313    }
314
315    /// Constructs a value from a flattened bit or integer array.
316    ///
317    /// # Arguments
318    ///
319    /// * `x` - array to be converted to a value, can have entries of any standard integer type
320    /// * `st` - scalar type corresponding to the entries of `x`
321    ///
322    /// # Returns
323    ///
324    /// New value constructed from `x`
325    ///
326    /// # Examples
327    ///
328    /// ```
329    /// # use ciphercore_base::data_values::Value;
330    /// # use ciphercore_base::data_types::BIT;
331    /// let v = Value::from_flattened_array(&[0, 1, 1, 0, 1, 0, 0, 1], BIT).unwrap();
332    /// v.access_bytes(|bytes| {
333    ///     assert_eq!(*bytes, vec![150]);
334    ///     Ok(())
335    /// }).unwrap();
336    /// ```
337    pub fn from_flattened_array<T: TryInto<u128> + Not<Output = T> + TryInto<u8> + Copy>(
338        x: &[T],
339        st: ScalarType,
340    ) -> Result<Value> {
341        Ok(Value::from_bytes(vec_to_bytes(x, st)?))
342    }
343
344    /// Constructs a value from a flattened bit or integer array.
345    ///
346    /// # Arguments
347    ///
348    /// * `x` - array to be converted to a value, can have entries of any standard integer type
349    /// * `st` - scalar type corresponding to the entries of `x`
350    ///
351    /// # Returns
352    ///
353    /// New value constructed from `x`
354    ///
355    /// # Examples
356    ///
357    /// ```
358    /// # use ciphercore_base::data_values::Value;
359    /// # use ciphercore_base::data_types::BIT;
360    /// let v = Value::from_flattened_array_u64(&[0, 1, 1, 0, 1, 0, 0, 1], BIT).unwrap();
361    /// v.access_bytes(|bytes| {
362    ///     assert_eq!(*bytes, vec![150]);
363    ///     Ok(())
364    /// }).unwrap();
365    /// ```
366    pub fn from_flattened_array_u64<T: TryInto<u64> + Not<Output = T> + TryInto<u8> + Copy>(
367        x: &[T],
368        st: ScalarType,
369    ) -> Result<Value> {
370        Ok(Value::from_bytes(vec_u64_to_bytes(x, st)?))
371    }
372
373    /// Constructs a value from a multi-dimensional bit or integer array.
374    ///
375    /// # Arguments
376    ///
377    /// * `x` - array to be converted to a value, can have entries of any standard integer type
378    /// * `st` - scalar type corresponding to the entries of `x`
379    ///
380    /// # Returns
381    ///
382    /// New value constructed from `x`
383    ///
384    /// # Examples
385    ///
386    /// ```
387    /// # use ciphercore_base::data_values::Value;
388    /// # use ciphercore_base::data_types::BIT;
389    /// # use ndarray::array;
390    /// let a = array![[0, 1, 1, 0], [1, 0, 0, 1]].into_dyn();
391    /// let v = Value::from_ndarray(a, BIT).unwrap();
392    /// v.access_bytes(|bytes| {
393    ///     assert_eq!(*bytes, vec![150]);
394    ///     Ok(())
395    /// }).unwrap();
396    /// ```
397    pub fn from_ndarray<T: TryInto<u128> + Not<Output = T> + TryInto<u8> + Copy>(
398        a: ndarray::ArrayD<T>,
399        st: ScalarType,
400    ) -> Result<Value> {
401        match a.as_slice() {
402            Some(x) => Value::from_flattened_array(x, st),
403            None => Err(runtime_error!("Not a contiguous ndarray!")),
404        }
405    }
406
407    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `u8`.
408    ///
409    /// # Arguments
410    ///
411    /// `st` - scalar type used to interpret `self`
412    ///
413    /// # Result
414    ///
415    /// Resulting scalar cast to `u8`
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// # use ciphercore_base::data_values::Value;
421    /// # use ciphercore_base::data_types::INT32;
422    /// let v = Value::from_scalar(-123456, INT32).unwrap();
423    /// assert_eq!(v.to_u8(INT32).unwrap(), -123456i32 as u8);
424    /// ```
425    pub fn to_u8(&self, st: ScalarType) -> Result<u8> {
426        Ok(self.to_u128(st)? as u8)
427    }
428
429    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `bool`.
430    ///
431    /// # Result
432    ///
433    /// Resulting scalar cast to `bool`
434    ///
435    /// # Examples
436    ///
437    /// ```
438    /// # use ciphercore_base::data_values::Value;
439    /// # use ciphercore_base::data_types::UINT8;
440    /// let v = Value::from_scalar(156, UINT8).unwrap();
441    /// assert_eq!(v.to_bit().unwrap(), false);
442    /// ```
443    pub fn to_bit(&self) -> Result<bool> {
444        Ok(self.to_flattened_array_u8(array_type(vec![1], BIT))?[0] != 0)
445    }
446
447    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `i8`.
448    ///
449    /// # Arguments
450    ///
451    /// `st` - scalar type used to interpret `self`
452    ///
453    /// # Result
454    ///
455    /// Resulting scalar cast to `i8`
456    ///
457    /// # Examples
458    ///
459    /// ```
460    /// # use ciphercore_base::data_values::Value;
461    /// # use ciphercore_base::data_types::INT32;
462    /// let v = Value::from_scalar(-123456, INT32).unwrap();
463    /// assert_eq!(v.to_i8(INT32).unwrap(), -123456i32 as i8);
464    /// ```
465    pub fn to_i8(&self, st: ScalarType) -> Result<i8> {
466        Ok(self.to_u128(st)? as i8)
467    }
468
469    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `u16`.
470    ///
471    /// # Arguments
472    ///
473    /// `st` - scalar type used to interpret `self`
474    ///
475    /// # Result
476    ///
477    /// Resulting scalar cast to `u16`
478    ///
479    /// # Examples
480    ///
481    /// ```
482    /// # use ciphercore_base::data_values::Value;
483    /// # use ciphercore_base::data_types::INT32;
484    /// let v = Value::from_scalar(-123456, INT32).unwrap();
485    /// assert_eq!(v.to_u16(INT32).unwrap(), -123456i32 as u16);
486    /// ```
487    pub fn to_u16(&self, st: ScalarType) -> Result<u16> {
488        Ok(self.to_u128(st)? as u16)
489    }
490
491    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `i16`.
492    ///
493    /// # Arguments
494    ///
495    /// `st` - scalar type used to interpret `self`
496    ///
497    /// # Result
498    ///
499    /// Resulting scalar cast to `i16`
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// # use ciphercore_base::data_values::Value;
505    /// # use ciphercore_base::data_types::INT32;
506    /// let v = Value::from_scalar(-123456, INT32).unwrap();
507    /// assert_eq!(v.to_i16(INT32).unwrap(), -123456i32 as i16);
508    /// ```
509    pub fn to_i16(&self, st: ScalarType) -> Result<i16> {
510        Ok(self.to_u128(st)? as i16)
511    }
512
513    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `u32`.
514    ///
515    /// # Arguments
516    ///
517    /// `st` - scalar type used to interpret `self`
518    ///
519    /// # Result
520    ///
521    /// Resulting scalar cast to `u32`
522    ///
523    /// # Examples
524    ///
525    /// ```
526    /// # use ciphercore_base::data_values::Value;
527    /// # use ciphercore_base::data_types::INT32;
528    /// let v = Value::from_scalar(-123456, INT32).unwrap();
529    /// assert_eq!(v.to_u32(INT32).unwrap(), -123456i32 as u32);
530    /// ```
531    pub fn to_u32(&self, st: ScalarType) -> Result<u32> {
532        Ok(self.to_u128(st)? as u32)
533    }
534
535    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `i32`.
536    ///
537    /// # Arguments
538    ///
539    /// `st` - scalar type used to interpret `self`
540    ///
541    /// # Result
542    ///
543    /// Resulting scalar cast to `i32`
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// # use ciphercore_base::data_values::Value;
549    /// # use ciphercore_base::data_types::INT32;
550    /// let v = Value::from_scalar(-123456, INT32).unwrap();
551    /// assert_eq!(v.to_i32(INT32).unwrap(), -123456i32 as i32);
552    /// ```
553    pub fn to_i32(&self, st: ScalarType) -> Result<i32> {
554        Ok(self.to_u128(st)? as i32)
555    }
556
557    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `u64`.
558    ///
559    /// # Arguments
560    ///
561    /// `st` - scalar type used to interpret `self`
562    ///
563    /// # Result
564    ///
565    /// Resulting scalar cast to `u64`
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// # use ciphercore_base::data_values::Value;
571    /// # use ciphercore_base::data_types::INT32;
572    /// let v = Value::from_scalar(-123456, INT32).unwrap();
573    /// assert_eq!(v.to_u64(INT32).unwrap(), -123456i32 as u64);
574    /// ```
575    pub fn to_u64(&self, st: ScalarType) -> Result<u64> {
576        Ok(self.to_u128(st)? as u64)
577    }
578
579    /// Converts `self` to a scalar if it is a byte vector, then cast the result to `i64`.
580    ///
581    /// # Arguments
582    ///
583    /// `st` - scalar type used to interpret `self`
584    ///
585    /// # Result
586    ///
587    /// Resulting scalar cast to `i64`
588    ///
589    /// # Examples
590    ///
591    /// ```
592    /// # use ciphercore_base::data_values::Value;
593    /// # use ciphercore_base::data_types::INT32;
594    /// let v = Value::from_scalar(-123456, INT32).unwrap();
595    /// assert_eq!(v.to_i64(INT32).unwrap(), -123456i32 as i64);
596    /// ```
597    pub fn to_i64(&self, st: ScalarType) -> Result<i64> {
598        Ok(self.to_u128(st)? as i64)
599    }
600
601    /// Converts `self` to a scalar if it is a byte vector, then casts the result to `u128`.
602    ///
603    /// # Arguments
604    ///
605    /// `st` - scalar type used to interpret `self`
606    ///
607    /// # Result
608    ///
609    /// Resulting scalar cast to `u128`
610    ///
611    /// # Examples
612    ///
613    /// ```
614    /// # use ciphercore_base::data_values::Value;
615    /// # use ciphercore_base::data_types::INT32;
616    /// let v = Value::from_scalar(-123456, INT32).unwrap();
617    /// assert_eq!(v.to_u128(INT32).unwrap(), -123456i32 as u128);
618    /// ```
619    pub fn to_u128(&self, st: ScalarType) -> Result<u128> {
620        let v = self.access_bytes(|bytes| vec_u128_from_bytes(bytes, st))?;
621        if v.len() != 1 && (v.len() != 8 || st != BIT) {
622            return Err(runtime_error!("Not a scalar"));
623        }
624        Ok(v[0])
625    }
626
627    /// Converts `self` to a scalar if it is a byte vector, then cast the result to `i128`.
628    ///
629    /// # Arguments
630    ///
631    /// `st` - scalar type used to interpret `self`
632    ///
633    /// # Result
634    ///
635    /// Resulting scalar cast to `i128`
636    ///
637    /// # Examples
638    ///
639    /// ```
640    /// # use ciphercore_base::data_values::Value;
641    /// # use ciphercore_base::data_types::INT32;
642    /// let v = Value::from_scalar(-123456, INT32).unwrap();
643    /// assert_eq!(v.to_i128(INT32).unwrap(), -123456i32 as i128);
644    /// ```
645    pub fn to_i128(&self, st: ScalarType) -> Result<i128> {
646        Ok(self.to_u128(st)? as i128)
647    }
648
649    /// Converts `self` to a vector of values or return an error if `self` is a byte vector.
650    ///
651    /// # Returns
652    ///
653    /// Extracted vector of values
654    ///
655    /// # Examples
656    ///
657    /// ```
658    /// # use ciphercore_base::data_values::Value;
659    /// let v = Value::from_vector(
660    ///     vec![
661    ///         Value::from_vector(vec![]),
662    ///         Value::from_bytes(vec![1, 2, 3])]);
663    /// let vv = v.to_vector().unwrap();
664    /// assert_eq!(vv.len(), 2);
665    /// vv[0].access_vector(|v| {
666    ///     assert_eq!(*v, Vec::<Value>::new());
667    ///     Ok(())
668    /// }).unwrap();
669    /// vv[1].access_bytes(|bytes| {
670    ///     assert_eq!(*bytes, vec![1, 2, 3]);
671    ///     Ok(())
672    /// }).unwrap();
673    /// ```
674    pub fn to_vector(&self) -> Result<Vec<Value>> {
675        if let ValueBody::Vector(contents) = self.body.as_ref() {
676            Ok(contents.clone())
677        } else {
678            Err(runtime_error!("Not a vector!"))
679        }
680    }
681
682    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `u8`.
683    ///
684    /// # Arguments
685    ///
686    /// `t` - array type used to interpret `self`
687    ///
688    /// # Result
689    ///
690    /// Resulting flattened array with entries cast to `u8`
691    ///
692    /// # Examples
693    ///
694    /// ```
695    /// # use ciphercore_base::data_values::Value;
696    /// # use ciphercore_base::data_types::{array_type, INT32};
697    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
698    /// let a = v.to_flattened_array_u8(array_type(vec![2], INT32)).unwrap();
699    /// assert_eq!(a, vec![-123i32 as u8, 123i32 as u8]);
700    /// ```
701    pub fn to_flattened_array_u8(&self, t: Type) -> Result<Vec<u8>> {
702        Ok(self
703            .to_flattened_array_u128(t)?
704            .into_iter()
705            .map(|x| x as u8)
706            .collect())
707    }
708
709    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `i8`.
710    ///
711    /// # Arguments
712    ///
713    /// `t` - array type used to interpret `self`
714    ///
715    /// # Result
716    ///
717    /// Resulting flattened array with entries cast to `i8`
718    ///
719    /// # Examples
720    ///
721    /// ```
722    /// # use ciphercore_base::data_values::Value;
723    /// # use ciphercore_base::data_types::{array_type, INT32};
724    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
725    /// let a = v.to_flattened_array_i8(array_type(vec![2], INT32)).unwrap();
726    /// assert_eq!(a, vec![-123i32 as i8, 123i32 as i8]);
727    /// ```
728    pub fn to_flattened_array_i8(&self, t: Type) -> Result<Vec<i8>> {
729        Ok(self
730            .to_flattened_array_u128(t)?
731            .into_iter()
732            .map(|x| x as i8)
733            .collect())
734    }
735
736    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `u16`.
737    ///
738    /// # Arguments
739    ///
740    /// `t` - array type used to interpret `self`
741    ///
742    /// # Result
743    ///
744    /// Resulting flattened array with entries cast to `u16`
745    ///
746    /// # Examples
747    ///
748    /// ```
749    /// # use ciphercore_base::data_values::Value;
750    /// # use ciphercore_base::data_types::{array_type, INT32};
751    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
752    /// let a = v.to_flattened_array_u16(array_type(vec![2], INT32)).unwrap();
753    /// assert_eq!(a, vec![-123i32 as u16, 123i32 as u16]);
754    /// ```
755    pub fn to_flattened_array_u16(&self, t: Type) -> Result<Vec<u16>> {
756        Ok(self
757            .to_flattened_array_u128(t)?
758            .into_iter()
759            .map(|x| x as u16)
760            .collect())
761    }
762
763    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `i16`.
764    ///
765    /// # Arguments
766    ///
767    /// `t` - array type used to interpret `self`
768    ///
769    /// # Result
770    ///
771    /// Resulting flattened array with entries cast to `i16`
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// # use ciphercore_base::data_values::Value;
777    /// # use ciphercore_base::data_types::{array_type, INT32};
778    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
779    /// let a = v.to_flattened_array_i16(array_type(vec![2], INT32)).unwrap();
780    /// assert_eq!(a, vec![-123i32 as i16, 123i32 as i16]);
781    /// ```
782    pub fn to_flattened_array_i16(&self, t: Type) -> Result<Vec<i16>> {
783        Ok(self
784            .to_flattened_array_u128(t)?
785            .into_iter()
786            .map(|x| x as i16)
787            .collect())
788    }
789
790    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `u32`.
791    ///
792    /// # Arguments
793    ///
794    /// `t` - array type used to interpret `self`
795    ///
796    /// # Result
797    ///
798    /// Resulting flattened array with entries cast to `u32`
799    ///
800    /// # Examples
801    ///
802    /// ```
803    /// # use ciphercore_base::data_values::Value;
804    /// # use ciphercore_base::data_types::{array_type, INT32};
805    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
806    /// let a = v.to_flattened_array_u32(array_type(vec![2], INT32)).unwrap();
807    /// assert_eq!(a, vec![-123i32 as u32, 123i32 as u32]);
808    /// ```
809    pub fn to_flattened_array_u32(&self, t: Type) -> Result<Vec<u32>> {
810        Ok(self
811            .to_flattened_array_u128(t)?
812            .into_iter()
813            .map(|x| x as u32)
814            .collect())
815    }
816
817    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `i32`.
818    ///
819    /// # Arguments
820    ///
821    /// `t` - array type used to interpret `self`
822    ///
823    /// # Result
824    ///
825    /// Resulting flattened array with entries cast to `i32`
826    ///
827    /// # Examples
828    ///
829    /// ```
830    /// # use ciphercore_base::data_values::Value;
831    /// # use ciphercore_base::data_types::{array_type, INT32};
832    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
833    /// let a = v.to_flattened_array_i32(array_type(vec![2], INT32)).unwrap();
834    /// assert_eq!(a, vec![-123i32, 123i32]);
835    /// ```
836    pub fn to_flattened_array_i32(&self, t: Type) -> Result<Vec<i32>> {
837        Ok(self
838            .to_flattened_array_u128(t)?
839            .into_iter()
840            .map(|x| x as i32)
841            .collect())
842    }
843
844    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `u64`.
845    ///
846    /// # Arguments
847    ///
848    /// `t` - array type used to interpret `self`
849    ///
850    /// # Result
851    ///
852    /// Resulting flattened array with entries cast to `u64`
853    ///
854    /// # Examples
855    ///
856    /// ```
857    /// # use ciphercore_base::data_values::Value;
858    /// # use ciphercore_base::data_types::{array_type, INT32};
859    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
860    /// let a = v.to_flattened_array_u64(array_type(vec![2], INT32)).unwrap();
861    /// assert_eq!(a, vec![-123i32 as u64, 123i32 as u64]);
862    /// ```
863    pub fn to_flattened_array_u64(&self, t: Type) -> Result<Vec<u64>> {
864        Ok(self
865            .to_flattened_array_u128(t)?
866            .into_iter()
867            .map(|x| x as u64)
868            .collect())
869    }
870
871    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `i64`.
872    ///
873    /// # Arguments
874    ///
875    /// `t` - array type used to interpret `self`
876    ///
877    /// # Result
878    ///
879    /// Resulting flattened array with entries cast to `i64`
880    ///
881    /// # Examples
882    ///
883    /// ```
884    /// # use ciphercore_base::data_values::Value;
885    /// # use ciphercore_base::data_types::{array_type, INT32};
886    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
887    /// let a = v.to_flattened_array_i64(array_type(vec![2], INT32)).unwrap();
888    /// assert_eq!(a, vec![-123, 123]);
889    /// ```
890    pub fn to_flattened_array_i64(&self, t: Type) -> Result<Vec<i64>> {
891        Ok(self
892            .to_flattened_array_u128(t)?
893            .into_iter()
894            .map(|x| x as i64)
895            .collect())
896    }
897
898    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `u128`.
899    ///
900    /// # Arguments
901    ///
902    /// `t` - array type used to interpret `self`
903    ///
904    /// # Result
905    ///
906    /// Resulting flattened array with entries cast to `u128`
907    ///
908    /// # Examples
909    ///
910    /// ```
911    /// # use ciphercore_base::data_values::Value;
912    /// # use ciphercore_base::data_types::{array_type, INT32};
913    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
914    /// let a = v.to_flattened_array_u128(array_type(vec![2], INT32)).unwrap();
915    /// assert_eq!(a, vec![-123i32 as u128, 123i32 as u128]);
916    /// ```
917    pub fn to_flattened_array_u128(&self, t: Type) -> Result<Vec<u128>> {
918        if !t.is_array() {
919            return Err(runtime_error!(
920                "Trying to extract array from a value of a wrong type"
921            ));
922        }
923        if !self.check_type(t.clone())? {
924            return Err(runtime_error!("Type and value mismatch"));
925        }
926        let st = t.get_scalar_type();
927        if let ValueBody::Bytes(bytes) = self.body.as_ref() {
928            let mut result = vec_u128_from_bytes(bytes, st)?;
929            if st == BIT {
930                let num_values: u64 = t.get_dimensions().iter().product();
931                result.truncate(num_values as usize);
932            }
933            Ok(result)
934        } else {
935            Err(runtime_error!("Invalid Value"))
936        }
937    }
938
939    /// Converts `self` to a flattened array if it is a byte vector, then cast the array entries to `i128`.
940    ///
941    /// # Arguments
942    ///
943    /// `t` - array type used to interpret `self`
944    ///
945    /// # Result
946    ///
947    /// Resulting flattened array with entries cast to `i128`
948    ///
949    /// # Examples
950    ///
951    /// ```
952    /// # use ciphercore_base::data_values::Value;
953    /// # use ciphercore_base::data_types::{array_type, INT32};
954    /// let v = Value::from_flattened_array(&[-123, 123], INT32).unwrap();
955    /// let a = v.to_flattened_array_i128(array_type(vec![2], INT32)).unwrap();
956    /// assert_eq!(a, vec![-123, 123]);
957    /// ```
958    pub fn to_flattened_array_i128(&self, t: Type) -> Result<Vec<i128>> {
959        Ok(self
960            .to_flattened_array_u128(t)?
961            .into_iter()
962            .map(|x| x as i128)
963            .collect())
964    }
965
966    /// Checks if `self` is a valid value for a given type.
967    ///
968    /// # Arguments
969    ///
970    /// `t` - a type to check a value against
971    ///
972    /// # Returns
973    ///
974    /// `true` if `self` is a valid value of type `t`, `false` otherwise
975    ///
976    /// # Examples
977    ///
978    /// ```
979    /// # use ciphercore_base::data_values::Value;
980    /// # use ciphercore_base::data_types::{scalar_type, INT32, array_type, UINT32, UINT8, BIT, UINT16, UINT64};
981    /// assert!(Value::from_bytes(vec![1, 2, 3, 4]).check_type(scalar_type(INT32)).unwrap());
982    /// assert!(Value::from_bytes(vec![1, 2, 3, 4]).check_type(scalar_type(UINT32)).unwrap());
983    /// assert!(Value::from_bytes(vec![1, 2, 3, 4]).check_type(array_type(vec![2, 2], UINT8)).unwrap());
984    /// assert!(Value::from_bytes(vec![1, 2, 3, 4]).check_type(array_type(vec![4, 8], BIT)).unwrap());
985    /// assert!(!Value::from_bytes(vec![1, 2, 3, 4]).check_type(array_type(vec![3, 5], BIT)).unwrap());
986    /// assert!(!Value::from_bytes(vec![1, 2, 3, 4]).check_type(array_type(vec![5], UINT8)).unwrap());
987    /// assert!(!Value::from_bytes(vec![1, 2, 3, 4]).check_type(array_type(vec![3], UINT16)).unwrap());
988    /// assert!(!Value::from_bytes(vec![1, 2, 3, 4]).check_type(scalar_type(UINT64)).unwrap());
989    /// ```
990    pub fn check_type(&self, t: Type) -> Result<bool> {
991        let s = get_size_in_bits(t.clone())?;
992        match t {
993            Type::Scalar(_) | Type::Array(_, _) => match self.body.as_ref() {
994                ValueBody::Bytes(bytes) => Ok(bytes.len() as u64 == (s + 7) / 8),
995                _ => Ok(false),
996            },
997            Type::Vector(_, _) | Type::Tuple(_) | Type::NamedTuple(_) => {
998                let ts = get_types_vector(t)?;
999                match self.body.as_ref() {
1000                    ValueBody::Vector(children) => {
1001                        if ts.len() != children.len() {
1002                            return Ok(false);
1003                        }
1004                        for i in 0..ts.len() {
1005                            if !children[i].check_type((*ts[i]).clone())? {
1006                                return Ok(false);
1007                            }
1008                        }
1009                        Ok(true)
1010                    }
1011                    _ => Ok(false),
1012                }
1013            }
1014        }
1015    }
1016
1017    /// Runs a given closure if `self` corresponds to a byte vector, and panic otherwise.
1018    ///
1019    /// # Arguments
1020    ///
1021    /// `f` - a closure, that takes a reference to a slice of bytes, to run
1022    ///
1023    /// # Returns
1024    ///
1025    /// Return value of `f`
1026    ///
1027    /// # Panics
1028    ///
1029    /// Panics if `self` is a vector of values.
1030    ///
1031    /// # Examples
1032    ///
1033    /// ```
1034    /// # use ciphercore_base::data_values::Value;
1035    ///
1036    /// let v = Value::from_bytes(vec![1, 2, 3]);
1037    /// v.access_bytes(|bytes| {
1038    ///     assert_eq!(*bytes, vec![1, 2, 3]);
1039    ///     Ok(())
1040    /// }).unwrap();
1041    /// ```
1042    pub fn access_bytes<F, R>(&self, f: F) -> Result<R>
1043    where
1044        F: FnOnce(&[u8]) -> Result<R>,
1045    {
1046        if let ValueBody::Bytes(bytes) = self.body.as_ref() {
1047            f(bytes)
1048        } else {
1049            panic!("Value::access_bytes() on an invalid Value");
1050        }
1051    }
1052
1053    /// Runs a given closure if `self` corresponds to a vector of values, and panic otherwise.
1054    ///
1055    /// # Arguments
1056    ///
1057    /// `f` - a closure, that takes a reference to a vector of values, to run
1058    ///
1059    /// # Returns
1060    ///
1061    /// Return value of `f`
1062    ///
1063    /// # Panics
1064    ///
1065    /// Panics if `self` is a byte vector.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// # use ciphercore_base::data_values::Value;
1071    ///
1072    /// let v = Value::from_vector(vec![]);
1073    /// v.access_vector(|vector| {
1074    ///     assert!(vector.is_empty());
1075    ///     Ok(())
1076    /// }).unwrap();
1077    /// ```
1078    pub fn access_vector<F, R>(&self, f: F) -> Result<R>
1079    where
1080        F: FnOnce(&Vec<Value>) -> Result<R>,
1081    {
1082        if let ValueBody::Vector(v) = self.body.as_ref() {
1083            f(v)
1084        } else {
1085            panic!("Value::access_vector() on an invalid Value");
1086        }
1087    }
1088
1089    /// Runs one closure if `self` corresponds to a byte vector,
1090    /// and another closure if `self` corresponds to a vector of values.
1091    ///
1092    /// # Arguments
1093    ///
1094    /// * `f_bytes` - a closure, that takes a reference to a slice of bytes, to run if `self` corresponds to a byte vector
1095    /// * `f_vector` - a closure, that takes a reference to a vector of values, to run if `self` corresponds to a vector of values
1096    ///
1097    /// # Returns
1098    ///
1099    /// Return value of the called closure
1100    ///
1101    /// # Examples
1102    ///
1103    /// ```
1104    /// # use ciphercore_base::data_values::Value;
1105    ///
1106    /// let v1 = Value::from_vector(vec![]);
1107    /// let v2 = Value::from_bytes(vec![1, 2, 3]);
1108    /// v1.access(|bytes| {
1109    ///     assert!(false);
1110    ///     Ok(())
1111    /// },
1112    /// |vector| {
1113    ///     assert!(vector.is_empty());
1114    ///     Ok(())
1115    /// }).unwrap();
1116    /// v2.access(|bytes| {
1117    ///     assert_eq!(*bytes, vec![1, 2, 3]);
1118    ///     Ok(())
1119    /// },
1120    /// |vector| {
1121    ///     assert!(false);
1122    ///     Ok(())
1123    /// }).unwrap();
1124    /// ```
1125    pub fn access<FB, FV, R>(&self, f_bytes: FB, f_vector: FV) -> Result<R>
1126    where
1127        FB: FnOnce(&[u8]) -> Result<R>,
1128        FV: FnOnce(&Vec<Value>) -> Result<R>,
1129    {
1130        match self.body.as_ref() {
1131            ValueBody::Bytes(bytes) => f_bytes(bytes),
1132            ValueBody::Vector(v) => f_vector(v),
1133        }
1134    }
1135
1136    /// Generates a value of a given type with all-zero bytes.
1137    ///
1138    /// # Arguments
1139    ///
1140    /// `t` - the type of a new value
1141    ///
1142    /// # Returns
1143    ///
1144    /// "Zero" value of type `t`
1145    ///
1146    /// # Examples
1147    ///
1148    /// ```
1149    /// # use ciphercore_base::data_values::Value;
1150    /// # use ciphercore_base::data_types::{array_type, INT32};
1151    /// # use ciphercore_base::data_values::ToNdarray;
1152    /// # use ndarray::array;
1153    /// let v = Value::zero_of_type(array_type(vec![2, 2], INT32));
1154    /// let a = ToNdarray::<u8>::to_ndarray(&v,array_type(vec![2, 2], INT32) ).unwrap();
1155    /// assert_eq!(a, array![[0, 0], [0, 0]].into_dyn());
1156    /// ```
1157    pub fn zero_of_type(t: Type) -> Value {
1158        match t {
1159            Type::Scalar(_) | Type::Array(_, _) => {
1160                let s = get_size_in_bits(t.clone()).unwrap();
1161                Value::from_bytes(vec![0; ((s + 7) / 8) as usize])
1162            }
1163            Type::Vector(len, t1) => {
1164                Value::from_vector(vec![Value::zero_of_type((*t1).clone()); len as usize])
1165            }
1166            Type::Tuple(element_types) => Value::from_vector(
1167                element_types
1168                    .iter()
1169                    .map(|t| Value::zero_of_type((**t).clone()))
1170                    .collect(),
1171            ),
1172            Type::NamedTuple(element_types) => Value::from_vector(
1173                element_types
1174                    .iter()
1175                    .map(|(_, t)| Value::zero_of_type((**t).clone()))
1176                    .collect(),
1177            ),
1178        }
1179    }
1180
1181    /// Generates a value of a given type with all-one bytes.
1182    ///
1183    /// # Arguments
1184    ///
1185    /// `t` - the type of a new value
1186    ///
1187    /// # Returns
1188    ///
1189    /// "One" value of type `t`
1190    ///
1191    /// # Examples
1192    ///
1193    /// ```
1194    /// # use ciphercore_base::data_values::Value;
1195    /// # use ciphercore_base::data_types::{array_type, INT32};
1196    /// # use ciphercore_base::data_values::ToNdarray;
1197    /// # use ndarray::array;
1198    /// let v = Value::one_of_type(array_type(vec![2, 2], INT32)).unwrap();
1199    /// let a = ToNdarray::<u8>::to_ndarray(&v,array_type(vec![2, 2], INT32) ).unwrap();
1200    /// assert_eq!(a, array![[1, 1], [1, 1]].into_dyn());
1201    /// ```
1202    pub fn one_of_type(t: Type) -> Result<Value> {
1203        match t {
1204            Type::Scalar(st) => Ok(Value::from_bytes(vec_to_bytes(&[1], st)?)),
1205            Type::Array(shape, st) => {
1206                let n: u64 = shape.iter().product();
1207                Ok(Value::from_bytes(vec_to_bytes(&vec![1; n as usize], st)?))
1208            }
1209            Type::Vector(len, t1) => Ok(Value::from_vector(vec![
1210                Value::one_of_type((*t1).clone())?;
1211                len as usize
1212            ])),
1213            Type::Tuple(element_types) => Ok(Value::from_vector(
1214                element_types
1215                    .iter()
1216                    .map(|t| Value::one_of_type((**t).clone()))
1217                    .collect::<Result<_>>()?,
1218            )),
1219            Type::NamedTuple(element_types) => Ok(Value::from_vector(
1220                element_types
1221                    .iter()
1222                    .map(|(_, t)| Value::one_of_type((**t).clone()))
1223                    .collect::<Result<_>>()?,
1224            )),
1225        }
1226    }
1227
1228    fn from_serializable_value(value: SerializableValue) -> Result<Value> {
1229        value.access(
1230            |bytes| Ok(Value::from_bytes(bytes.to_vec())),
1231            |vector| {
1232                let mut v_new = vec![];
1233                for item in vector {
1234                    v_new.push(Value::from_serializable_value(item.clone())?);
1235                }
1236                Ok(Value::from_vector(v_new))
1237            },
1238        )
1239    }
1240
1241    fn to_versioned_data(&self) -> Result<VersionedData> {
1242        VersionedData::create_versioned_data(
1243            DATA_VERSION,
1244            serde_json::to_string(&SerializableValue::from_value(self))?,
1245        )
1246    }
1247}
1248
1249pub trait ToNdarray<T> {
1250    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<T>>;
1251}
1252
1253/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `u8`.
1254///
1255/// # Arguments
1256///
1257/// `t` - array type used to interpret `self`
1258///
1259/// # Result
1260///
1261/// Resulting multi-dimensional array with entries cast to `u8`
1262///
1263/// # Examples
1264///
1265/// ```
1266/// # use ciphercore_base::data_values::Value;
1267/// # use ciphercore_base::data_values::ToNdarray;
1268/// # use ciphercore_base::data_types::{INT32, array_type};
1269/// # use ndarray::array;
1270/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1271/// let v = Value::from_ndarray(a, INT32).unwrap();
1272/// let a = ToNdarray::<u8>::to_ndarray(&v, array_type(vec![2, 2], INT32)).unwrap();
1273/// assert_eq!(a, array![[-123i32 as u8, 123i32 as u8], [-456i32 as u8, 456i32 as u8]].into_dyn());
1274/// ```
1275impl ToNdarray<u8> for Value {
1276    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<u8>> {
1277        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1278        Ok(arr.map(|x| *x as u8))
1279    }
1280}
1281
1282/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `i8`.
1283///
1284/// # Arguments
1285///
1286/// `t` - array type used to interpret `self`
1287///
1288/// # Result
1289///
1290/// Resulting multi-dimensional array with entries cast to `i8`
1291///
1292/// # Examples
1293///
1294/// ```
1295/// # use ciphercore_base::data_values::Value;
1296/// # use ciphercore_base::data_types::{INT32, array_type};
1297/// # use ciphercore_base::data_values::ToNdarray;
1298/// # use ndarray::array;
1299/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1300/// let v = Value::from_ndarray(a, INT32).unwrap();
1301/// let a = ToNdarray::<i8>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1302/// assert_eq!(a, array![[-123i32 as i8, 123i32 as i8], [-456i32 as i8, 456i32 as i8]].into_dyn());
1303/// ```
1304impl ToNdarray<i8> for Value {
1305    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<i8>> {
1306        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1307        Ok(arr.map(|x| *x as i8))
1308    }
1309}
1310
1311/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `u16`.
1312///
1313/// # Arguments
1314///
1315/// `t` - array type used to interpret `self`
1316///
1317/// # Result
1318///
1319/// Resulting multi-dimensional array with entries cast to `u16`
1320///
1321/// # Examples
1322///
1323/// ```
1324/// # use ciphercore_base::data_values::Value;
1325/// # use ciphercore_base::data_types::{INT32, array_type};
1326/// # use ciphercore_base::data_values::ToNdarray;
1327/// # use ndarray::array;
1328/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1329/// let v = Value::from_ndarray(a, INT32).unwrap();
1330/// let a = ToNdarray::<u16>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1331/// assert_eq!(a, array![[-123i32 as u16, 123i32 as u16], [-456i32 as u16, 456i32 as u16]].into_dyn());
1332/// ```
1333impl ToNdarray<u16> for Value {
1334    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<u16>> {
1335        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1336        Ok(arr.map(|x| *x as u16))
1337    }
1338}
1339
1340/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `i16`.
1341///
1342/// # Arguments
1343///
1344/// `t` - array type used to interpret `self`
1345///
1346/// # Result
1347///
1348/// Resulting multi-dimensional array with entries cast to `i16`
1349///
1350/// # Examples
1351///
1352/// ```
1353/// # use ciphercore_base::data_values::Value;
1354/// # use ciphercore_base::data_types::{INT32, array_type};
1355/// # use ciphercore_base::data_values::ToNdarray;
1356/// # use ndarray::array;
1357/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1358/// let v = Value::from_ndarray(a, INT32).unwrap();
1359/// let a = ToNdarray::<i16>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1360/// assert_eq!(a, array![[-123i32 as i16, 123i32 as i16], [-456i32 as i16, 456i32 as i16]].into_dyn());
1361/// ```
1362impl ToNdarray<i16> for Value {
1363    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<i16>> {
1364        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1365        Ok(arr.map(|x| *x as i16))
1366    }
1367}
1368
1369/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `u32`.
1370///
1371/// # Arguments
1372///
1373/// `t` - array type used to interpret `self`
1374///
1375/// # Result
1376///
1377/// Resulting multi-dimensional array with entries cast to `u32`
1378///
1379/// # Examples
1380///
1381/// ```
1382/// # use ciphercore_base::data_values::Value;
1383/// # use ciphercore_base::data_types::{INT32, array_type};
1384/// # use ciphercore_base::data_values::ToNdarray;
1385/// # use ndarray::array;
1386/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1387/// let v = Value::from_ndarray(a, INT32).unwrap();
1388/// let a = ToNdarray::<u32>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1389/// assert_eq!(a, array![[-123i32 as u32, 123i32 as u32], [-456i32 as u32, 456i32 as u32]].into_dyn());
1390/// ```
1391impl ToNdarray<u32> for Value {
1392    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<u32>> {
1393        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1394        Ok(arr.map(|x| *x as u32))
1395    }
1396}
1397
1398/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `i32`.
1399///
1400/// # Arguments
1401///
1402/// `t` - array type used to interpret `self`
1403///
1404/// # Result
1405///
1406/// Resulting multi-dimensional array with entries cast to `i32`
1407///
1408/// # Examples
1409///
1410/// ```
1411/// # use ciphercore_base::data_values::Value;
1412/// # use ciphercore_base::data_types::{INT32, array_type};
1413/// # use ciphercore_base::data_values::ToNdarray;
1414/// # use ndarray::array;
1415/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1416/// let v = Value::from_ndarray(a, INT32).unwrap();
1417/// let a = ToNdarray::<i32>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1418/// assert_eq!(a, array![[-123i32, 123i32], [-456i32, 456i32]].into_dyn());
1419/// ```
1420impl ToNdarray<i32> for Value {
1421    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<i32>> {
1422        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1423        Ok(arr.map(|x| *x as i32))
1424    }
1425}
1426
1427/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `u64`.
1428///
1429/// # Arguments
1430///
1431/// `t` - array type used to interpret `self`
1432///
1433/// # Result
1434///
1435/// Resulting multi-dimensional array with entries cast to `u64`
1436///
1437/// # Examples
1438///
1439/// ```
1440/// # use ciphercore_base::data_values::Value;
1441/// # use ciphercore_base::data_values::ToNdarray;
1442/// # use ciphercore_base::data_types::{INT32, array_type};
1443/// # use ndarray::array;
1444/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1445/// let v = Value::from_ndarray(a, INT32).unwrap();
1446/// let a = ToNdarray::<u64>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1447/// assert_eq!(a, array![[-123i32 as u64, 123i32 as u64], [-456i32 as u64, 456i32 as u64]].into_dyn());
1448/// ```
1449impl ToNdarray<u64> for Value {
1450    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<u64>> {
1451        match t.clone() {
1452            Type::Array(shape, _) => {
1453                let arr = self.to_flattened_array_u64(t)?;
1454                // TODO: for performance reasons, we should use the actual type, not u64.
1455                let ndarr = ndarray::Array::from_vec(arr);
1456                let shape: Vec<usize> = shape.iter().map(|x| *x as usize).collect();
1457                Ok(ndarr.into_shape(shape)?)
1458            }
1459            _ => Err(runtime_error!("Not an array type")),
1460        }
1461    }
1462}
1463
1464/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `u128`.
1465///
1466/// # Arguments
1467///
1468/// `t` - array type used to interpret `self`
1469///
1470/// # Result
1471///
1472/// Resulting multi-dimensional array with entries cast to `u64`
1473///
1474/// # Examples
1475///
1476/// ```
1477/// # use ciphercore_base::data_values::Value;
1478/// # use ciphercore_base::data_values::ToNdarray;
1479/// # use ciphercore_base::data_types::{INT32, array_type};
1480/// # use ndarray::array;
1481/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1482/// let v = Value::from_ndarray(a, INT32).unwrap();
1483/// let a = ToNdarray::<u128>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1484/// assert_eq!(a, array![[-123i32 as u128, 123i32 as u128], [-456i32 as u128, 456i32 as u128]].into_dyn());
1485/// ```
1486impl ToNdarray<u128> for Value {
1487    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<u128>> {
1488        match t.clone() {
1489            Type::Array(shape, _) => {
1490                let arr = self.to_flattened_array_u128(t)?;
1491                // TODO: for performance reasons, we should use the actual type, not u128.
1492                let ndarr = ndarray::Array::from_vec(arr);
1493                let shape: Vec<usize> = shape.iter().map(|x| *x as usize).collect();
1494                Ok(ndarr.into_shape(shape)?)
1495            }
1496            _ => Err(runtime_error!("Not an array type")),
1497        }
1498    }
1499}
1500
1501/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `u64`.
1502///
1503/// # Arguments
1504///
1505/// `t` - array type used to interpret `self`
1506///
1507/// # Result
1508///
1509/// Resulting multi-dimensional array with entries cast to `u64`
1510///
1511/// # Examples
1512///
1513/// ```
1514/// # use ciphercore_base::data_values::Value;
1515/// # use ciphercore_base::data_values::ToNdarray;
1516/// # use ciphercore_base::data_types::{BIT, array_type};
1517/// # use ndarray::array;
1518/// let a = array![[false, true], [true, false]].into_dyn();
1519/// let v = Value::from_ndarray(a.clone(), BIT).unwrap();
1520/// let converted = ToNdarray::<bool>::to_ndarray(&v,array_type(vec![2, 2], BIT)).unwrap();
1521/// assert_eq!(converted, a);
1522/// ```
1523impl ToNdarray<bool> for Value {
1524    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<bool>> {
1525        match t.clone() {
1526            Type::Array(shape, _) => {
1527                let arr = self
1528                    .to_flattened_array_u8(t)?
1529                    .iter()
1530                    .map(|x| *x != 0)
1531                    .collect();
1532                let ndarr = ndarray::Array::from_vec(arr);
1533                let shape: Vec<usize> = shape.iter().map(|x| *x as usize).collect();
1534                Ok(ndarr.into_shape(shape)?)
1535            }
1536            _ => Err(runtime_error!("Not an array type")),
1537        }
1538    }
1539}
1540
1541/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `i64`.
1542///
1543/// # Arguments
1544///
1545/// `t` - array type used to interpret `self`
1546///
1547/// # Result
1548///
1549/// Resulting multi-dimensional array with entries cast to `i64`
1550///
1551/// # Examples
1552///
1553/// ```
1554/// # use ciphercore_base::data_values::Value;
1555/// # use ciphercore_base::data_types::{INT32, array_type};
1556/// # use ciphercore_base::data_values::ToNdarray;
1557/// # use ndarray::array;
1558/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1559/// let v = Value::from_ndarray(a, INT32).unwrap();
1560/// let a = ToNdarray::<i64>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1561/// assert_eq!(a, array![[-123i32 as i64, 123i32 as i64], [-456i32 as i64, 456i32 as i64]].into_dyn());
1562/// ```
1563impl ToNdarray<i64> for Value {
1564    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<i64>> {
1565        let arr = ToNdarray::<u64>::to_ndarray(self, t)?;
1566        Ok(arr.map(|x| *x as i64))
1567    }
1568}
1569
1570/// Converts `self` to a multi-dimensional array if it is a byte vector, then cast the array entries to `i128`.
1571///
1572/// # Arguments
1573///
1574/// `t` - array type used to interpret `self`
1575///
1576/// # Result
1577///
1578/// Resulting multi-dimensional array with entries cast to `i128`
1579///
1580/// # Examples
1581///
1582/// ```
1583/// # use ciphercore_base::data_values::Value;
1584/// # use ciphercore_base::data_types::{INT32, array_type};
1585/// # use ciphercore_base::data_values::ToNdarray;
1586/// # use ndarray::array;
1587/// let a = array![[-123, 123], [-456, 456]].into_dyn();
1588/// let v = Value::from_ndarray(a, INT32).unwrap();
1589/// let a = ToNdarray::<i128>::to_ndarray(&v,array_type(vec![2, 2], INT32)).unwrap();
1590/// assert_eq!(a, array![[-123i32 as i128, 123i32 as i128], [-456i32 as i128, 456i32 as i128]].into_dyn());
1591/// ```
1592impl ToNdarray<i128> for Value {
1593    fn to_ndarray(&self, t: Type) -> Result<ndarray::ArrayD<i128>> {
1594        let arr = ToNdarray::<u128>::to_ndarray(self, t)?;
1595        Ok(arr.map(|x| *x as i128))
1596    }
1597}
1598
1599#[cfg(test)]
1600mod tests {
1601    use super::*;
1602    use crate::constants::type_size_limit_constants;
1603    use crate::data_types::{
1604        array_type, named_tuple_type, scalar_type, tuple_type, vector_type, BIT, INT32, INT64,
1605        INT8, UINT16, UINT32, UINT64, UINT8,
1606    };
1607    use std::panic::{catch_unwind, AssertUnwindSafe};
1608
1609    fn check_type_test_worker(v: &Value, t: Type) {
1610        assert!(v.check_type(t).unwrap());
1611    }
1612
1613    fn check_type_test_worker_fail(v: &Value, t: Type) {
1614        assert!(!v.check_type(t).unwrap());
1615    }
1616
1617    #[test]
1618    fn check_type_test() {
1619        let v = Value::from_bytes(vec![0]);
1620        check_type_test_worker(&v, scalar_type(BIT));
1621        check_type_test_worker(&v, scalar_type(UINT8));
1622        check_type_test_worker(&v, scalar_type(INT8));
1623        check_type_test_worker_fail(&v, scalar_type(INT32));
1624        let v = Value::from_bytes(vec![0, 0, 0, 0]);
1625        check_type_test_worker(&v, scalar_type(INT32));
1626        check_type_test_worker_fail(&v, scalar_type(INT64));
1627        let v = Value::from_bytes(vec![0, 0, 0, 0, 0, 0, 0, 0]);
1628        check_type_test_worker(&v, scalar_type(INT64));
1629        let v = Value::from_vector(vec![]);
1630        check_type_test_worker_fail(&v, scalar_type(BIT));
1631        let v = Value::from_vector(vec![
1632            Value::from_bytes(vec![0]),
1633            Value::from_bytes(vec![0, 0, 0, 0]),
1634        ]);
1635        check_type_test_worker(&v, tuple_type(vec![scalar_type(BIT), scalar_type(INT32)]));
1636        check_type_test_worker(
1637            &v,
1638            named_tuple_type(vec![
1639                ("field 1".to_owned(), scalar_type(BIT)),
1640                ("field 2".to_owned(), scalar_type(INT32)),
1641            ]),
1642        );
1643        let v = Value::from_vector(vec![Value::from_bytes(vec![0]), Value::from_bytes(vec![0])]);
1644        check_type_test_worker(&v, vector_type(2, scalar_type(BIT)));
1645        check_type_test_worker_fail(&v, tuple_type(vec![]));
1646        let v = Value::from_bytes(vec![0, 0, 0]);
1647        check_type_test_worker_fail(&v, tuple_type(vec![]));
1648    }
1649
1650    #[test]
1651    fn eq_test() {
1652        let a = Value::from_bytes(vec![10, 10]);
1653        let b = Value::from_bytes(vec![10, 10]);
1654        assert_eq!(a, b);
1655        let a = Value::from_vector(vec![Value::from_bytes(vec![10])]);
1656        let b = Value::from_vector(vec![Value::from_bytes(vec![10])]);
1657        assert_eq!(a, b);
1658        let a = Value::from_vector(vec![
1659            Value::from_bytes(vec![10]),
1660            Value::from_bytes(vec![7]),
1661        ]);
1662        let b = Value::from_vector(vec![
1663            Value::from_bytes(vec![10]),
1664            Value::from_bytes(vec![10]),
1665        ]);
1666        assert!(a != b);
1667        let a = Value::from_vector(vec![
1668            Value::from_bytes(vec![10]),
1669            Value::from_bytes(vec![7]),
1670        ]);
1671        let b = Value::from_bytes(vec![10, 10]);
1672        assert!(a != b);
1673        assert!(b != a);
1674        let a = Value::from_vector(vec![Value::from_bytes(vec![10])]);
1675        let b = Value::from_vector(vec![
1676            Value::from_bytes(vec![10]),
1677            Value::from_bytes(vec![10]),
1678        ]);
1679        assert!(a != b);
1680    }
1681
1682    #[test]
1683    fn test_get_bytes() {
1684        let v = Value::from_bytes(vec![0, 1, 2, 3]);
1685        v.access_bytes(|bytes| {
1686            assert_eq!(bytes, vec![0, 1, 2, 3]);
1687            Ok(())
1688        })
1689        .unwrap();
1690
1691        let v = Value::from_vector(vec![Value::from_bytes(vec![0]), Value::from_bytes(vec![0])]);
1692        let e = catch_unwind(AssertUnwindSafe(|| v.access_bytes(|_| Ok(()))));
1693        assert!(e.is_err());
1694    }
1695
1696    #[test]
1697    fn test_serialization() {
1698        let v = Value::from_vector(vec![
1699            Value::from_bytes(vec![1, 2, 3, 4, 5]),
1700            Value::from_bytes(vec![6, 7, 8]),
1701        ]);
1702        let se = serde_json::to_string(&v).unwrap();
1703        assert_eq!(
1704            se,
1705            format!("{{\"version\":{},\"data\":\"{{\\\"body\\\":{{\\\"Vector\\\":[{{\\\"body\\\":{{\\\"Bytes\\\":[1,2,3,4,5]}}}},{{\\\"body\\\":{{\\\"Bytes\\\":[6,7,8]}}}}]}}}}\"}}", DATA_VERSION)
1706        );
1707        let de: Value = serde_json::from_str(&se).unwrap();
1708        assert_eq!(v, de);
1709        assert!(serde_json::from_str::<Value>("{{{").is_err());
1710    }
1711
1712    #[test]
1713    #[should_panic(expected = "Value version doesn't match the requirement")]
1714    fn test_version_value() {
1715        let invalid_versioned_value = VersionedData::create_versioned_data(
1716            DATA_VERSION - 1,
1717            serde_json::to_string(&SerializableValue::from_vector(vec![
1718                SerializableValue::from_bytes(vec![1, 2, 3, 4, 5]),
1719                SerializableValue::from_bytes(vec![6, 7, 8]),
1720            ]))
1721            .unwrap(),
1722        )
1723        .unwrap();
1724        let se = serde_json::to_string(&invalid_versioned_value).unwrap();
1725        let _de: Value = serde_json::from_str(&se).unwrap();
1726    }
1727
1728    #[test]
1729    #[should_panic(expected = "Value version doesn't match the requirement")]
1730    fn test_unsupported_version_value() {
1731        let invalid_versioned_value = VersionedData::create_versioned_data(
1732            DATA_VERSION - 1,
1733            "{\"Unsupported_field\": Unsupported_value}".to_string(),
1734        )
1735        .unwrap();
1736        let se = serde_json::to_string(&invalid_versioned_value).unwrap();
1737        let _de: Value = serde_json::from_str(&se).unwrap();
1738    }
1739
1740    #[test]
1741    fn test_extract_scalar_bit() {
1742        let v = Value::from_scalar(1, BIT).unwrap();
1743        let result = v.to_u64(BIT).unwrap();
1744        assert_eq!(result, 1);
1745    }
1746
1747    #[test]
1748    fn test_create_extract_scalar() {
1749        assert_eq!(Value::from_scalar(0, BIT).unwrap().to_u64(BIT).unwrap(), 0);
1750        assert_eq!(Value::from_scalar(1, BIT).unwrap().to_u64(BIT).unwrap(), 1);
1751        assert_eq!(
1752            Value::from_scalar(-73, INT32)
1753                .unwrap()
1754                .to_i32(INT32)
1755                .unwrap(),
1756            -73
1757        );
1758        assert_eq!(
1759            Value::from_scalar(-73, INT32)
1760                .unwrap()
1761                .to_i32(UINT32)
1762                .unwrap(),
1763            -73
1764        );
1765        assert_eq!(
1766            Value::from_scalar(187263, INT32)
1767                .unwrap()
1768                .to_i32(INT32)
1769                .unwrap(),
1770            187263
1771        );
1772        assert_eq!(
1773            Value::from_scalar(187263, UINT32)
1774                .unwrap()
1775                .to_u32(UINT32)
1776                .unwrap(),
1777            187263
1778        );
1779        assert_eq!(
1780            Value::from_flattened_array(&vec![0, 0, 0, 0, 0, 0, 0, 0], BIT)
1781                .unwrap()
1782                .to_u64(BIT)
1783                .unwrap(),
1784            0
1785        );
1786        assert_eq!(
1787            Value::from_flattened_array(&vec![1, 0, 0, 0, 0, 0, 0, 0], BIT)
1788                .unwrap()
1789                .to_u64(BIT)
1790                .unwrap(),
1791            1
1792        );
1793        assert_eq!(
1794            Value::from_flattened_array(&vec![1, 0, 0, 1, 0, 1, 0, 0], BIT)
1795                .unwrap()
1796                .to_u64(BIT)
1797                .unwrap(),
1798            1
1799        );
1800        assert!(
1801            Value::from_flattened_array(&vec![0, 0, 0, 0, 0, 0, 0, 0, 0], BIT)
1802                .unwrap()
1803                .to_u64(BIT)
1804                .is_err()
1805        );
1806        assert!(Value::from_flattened_array(&vec![123, 456], UINT32)
1807            .unwrap()
1808            .to_u64(UINT32)
1809            .is_err());
1810    }
1811
1812    #[test]
1813    fn test_create_extract_vector() {
1814        let v = Value::from_vector(vec![
1815            Value::from_scalar(0, BIT).unwrap(),
1816            Value::from_scalar(-73, INT32).unwrap(),
1817        ]);
1818        let entries = v.to_vector().unwrap();
1819        assert_eq!(entries.len(), 2);
1820        assert_eq!(entries[0].to_u64(BIT).unwrap(), 0);
1821        assert_eq!(entries[1].to_i32(INT32).unwrap(), -73);
1822        assert!(Value::from_scalar(-73, INT32).unwrap().to_vector().is_err());
1823    }
1824
1825    #[test]
1826    fn test_create_extract_array() {
1827        let t = array_type(vec![1], BIT);
1828        assert_eq!(
1829            Value::from_flattened_array(&vec![0], t.get_scalar_type())
1830                .unwrap()
1831                .to_flattened_array_u64(t.clone())
1832                .unwrap(),
1833            vec![0]
1834        );
1835        assert_eq!(
1836            Value::from_flattened_array(&vec![1], t.get_scalar_type())
1837                .unwrap()
1838                .to_flattened_array_u64(t.clone())
1839                .unwrap(),
1840            vec![1]
1841        );
1842        assert_eq!(
1843            Value::from_flattened_array(&vec![1, 0, 0, 1], t.get_scalar_type())
1844                .unwrap()
1845                .to_flattened_array_u64(t.clone())
1846                .unwrap(),
1847            vec![1]
1848        );
1849        assert_eq!(
1850            Value::from_flattened_array(&vec![0, 0, 0, 1, 0, 0, 0, 0], t.get_scalar_type())
1851                .unwrap()
1852                .to_flattened_array_u64(t.clone())
1853                .unwrap(),
1854            vec![0]
1855        );
1856        assert!(Value::from_flattened_array(
1857            &vec![0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1],
1858            t.get_scalar_type()
1859        )
1860        .unwrap()
1861        .to_flattened_array_u64(t.clone())
1862        .is_err());
1863        let t = array_type(vec![3, 3], BIT);
1864        assert_eq!(
1865            Value::from_flattened_array(&vec![0, 1, 1, 0, 1, 0, 0, 1, 0], t.get_scalar_type())
1866                .unwrap()
1867                .to_flattened_array_u64(t.clone())
1868                .unwrap(),
1869            vec![0, 1, 1, 0, 1, 0, 0, 1, 0]
1870        );
1871        assert!(
1872            Value::from_flattened_array(&vec![0, 1, 1, 0, 1, 0, 0, 1], t.get_scalar_type())
1873                .unwrap()
1874                .to_flattened_array_u64(t.clone())
1875                .is_err()
1876        );
1877        assert!(Value::from_flattened_array(
1878            &vec![0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
1879            t.get_scalar_type()
1880        )
1881        .unwrap()
1882        .to_flattened_array_u64(t.clone())
1883        .is_err());
1884        let t = array_type(vec![2, 3], INT32);
1885        assert_eq!(
1886            Value::from_flattened_array(&vec![1, 2, 3, 4, 5, 6], t.get_scalar_type())
1887                .unwrap()
1888                .to_flattened_array_u64(t.clone())
1889                .unwrap(),
1890            vec![1, 2, 3, 4, 5, 6]
1891        );
1892        assert!(
1893            Value::from_flattened_array(&vec![1, 2, 3, 4, 5, 6, 7], t.get_scalar_type())
1894                .unwrap()
1895                .to_flattened_array_u64(t.clone())
1896                .is_err()
1897        );
1898        assert!(
1899            Value::from_flattened_array(&vec![1, 2, 3, 4, 5], t.get_scalar_type())
1900                .unwrap()
1901                .to_flattened_array_u64(t.clone())
1902                .is_err()
1903        );
1904    }
1905
1906    #[test]
1907    fn test_zero_value_of_type() {
1908        let types = vec![
1909            scalar_type(BIT),
1910            scalar_type(INT32),
1911            scalar_type(UINT64),
1912            array_type(vec![2, 3], BIT),
1913            array_type(vec![1, 7], INT32),
1914            array_type(vec![10, 10], UINT64),
1915            tuple_type(vec![]),
1916            tuple_type(vec![scalar_type(BIT), scalar_type(BIT)]),
1917            tuple_type(vec![scalar_type(INT32), scalar_type(BIT)]),
1918            tuple_type(vec![tuple_type(vec![]), array_type(vec![5, 5], INT32)]),
1919            vector_type(10, tuple_type(vec![])),
1920            vector_type(
1921                10,
1922                tuple_type(vec![vector_type(5, scalar_type(INT32)), scalar_type(BIT)]),
1923            ),
1924            named_tuple_type(vec![
1925                ("field 1".to_string(), scalar_type(BIT)),
1926                ("field 2".to_string(), scalar_type(INT32)),
1927            ]),
1928        ];
1929        for t in types {
1930            assert!(Value::zero_of_type(t.clone())
1931                .check_type(t.clone())
1932                .unwrap());
1933        }
1934    }
1935
1936    #[test]
1937    fn test_one_value_of_type() -> Result<()> {
1938        let types = vec![
1939            scalar_type(BIT),
1940            scalar_type(INT32),
1941            scalar_type(UINT64),
1942            array_type(vec![2, 3], BIT),
1943            array_type(vec![1, 7], INT32),
1944            array_type(vec![10, 10], UINT64),
1945            tuple_type(vec![]),
1946            tuple_type(vec![scalar_type(BIT), scalar_type(BIT)]),
1947            tuple_type(vec![scalar_type(INT32), scalar_type(BIT)]),
1948            tuple_type(vec![tuple_type(vec![]), array_type(vec![5, 5], INT32)]),
1949            vector_type(10, tuple_type(vec![])),
1950            vector_type(
1951                10,
1952                tuple_type(vec![vector_type(5, scalar_type(INT32)), scalar_type(BIT)]),
1953            ),
1954            named_tuple_type(vec![
1955                ("field 1".to_string(), scalar_type(BIT)),
1956                ("field 2".to_string(), scalar_type(INT32)),
1957            ]),
1958        ];
1959        for t in types {
1960            let v = Value::one_of_type(t.clone())?;
1961            assert!(v.check_type(t.clone())?, "\nvalue: {v:?}\ntype: {t:?}");
1962        }
1963        Ok(())
1964    }
1965
1966    #[test]
1967    fn test_get_types_vector() {
1968        let t = vector_type(100, scalar_type(UINT16));
1969        let result = get_types_vector(t);
1970        assert!(result.is_ok());
1971        let t = vector_type(
1972            type_size_limit_constants::TYPES_VECTOR_LENGTH_LIMIT as u64 + 1,
1973            scalar_type(UINT16),
1974        );
1975        let result = get_types_vector(t);
1976        assert!(result.is_err());
1977    }
1978
1979    #[test]
1980    fn test_deep_clone() {
1981        || -> Result<()> {
1982            let v = Value::from_vector(vec![
1983                Value::from_scalar(123, INT64)?,
1984                Value::from_flattened_array(&[-1, 1, -2, 2], INT64)?,
1985            ]);
1986            let v1 = v.deep_clone();
1987            assert!(!Arc::ptr_eq(&v.body, &v1.body));
1988            let vv = v.to_vector()?;
1989            let vv1 = v1.to_vector()?;
1990            assert_eq!(vv.len(), 2);
1991            assert_eq!(vv1.len(), 2);
1992            assert!(!Arc::ptr_eq(&vv[0].body, &vv1[0].body));
1993            assert!(!Arc::ptr_eq(&vv[1].body, &vv1[1].body));
1994            let vv_a = vv[0].to_i64(INT64)?;
1995            let vv_b = vv[1].to_flattened_array_i64(array_type(vec![2, 2], INT64))?;
1996            let vv1_a = vv1[0].to_i64(INT64)?;
1997            let vv1_b = vv1[1].to_flattened_array_i64(array_type(vec![2, 2], INT64))?;
1998            assert_eq!(vv_a, 123);
1999            assert_eq!(vv_b, &[-1, 1, -2, 2]);
2000            assert_eq!(vv1_a, 123);
2001            assert_eq!(vv1_b, &[-1, 1, -2, 2]);
2002            Ok(())
2003        }()
2004        .unwrap();
2005    }
2006
2007    #[test]
2008    fn test_from_ndarray() {
2009        || -> Result<()> {
2010            let a = ndarray::Array::from_shape_vec((2, 3), vec![10, -20, 30, 40, -50, 60])?;
2011            let v = Value::from_ndarray(a.into_dyn(), INT32)?;
2012            let b = v.to_flattened_array_i32(array_type(vec![2, 3], INT32))?;
2013            assert_eq!(b, &[10, -20, 30, 40, -50, 60]);
2014            Ok(())
2015        }()
2016        .unwrap();
2017    }
2018
2019    #[test]
2020    fn test_to_scalar() {
2021        || -> Result<()> {
2022            let v = Value::from_scalar(-123456, INT32)?;
2023            assert_eq!(v.to_u8(INT32)?, (-123456i32) as u8);
2024            assert_eq!(v.to_i8(INT32)?, (-123456i32) as i8);
2025            assert_eq!(v.to_u16(INT32)?, (-123456i32) as u16);
2026            assert_eq!(v.to_i16(INT32)?, (-123456i32) as i16);
2027            assert_eq!(v.to_u32(INT32)?, (-123456i32) as u32);
2028            assert_eq!(v.to_i32(INT32)?, (-123456i32) as i32);
2029            assert_eq!(v.to_u64(INT32)?, (-123456i32) as u64);
2030            assert_eq!(v.to_i64(INT32)?, (-123456i32) as i64);
2031
2032            assert_eq!(Value::from_scalar(156, UINT8)?.to_bit()?, false);
2033            assert_eq!(Value::from_scalar(157, UINT8)?.to_bit()?, true);
2034            Ok(())
2035        }()
2036        .unwrap();
2037    }
2038
2039    #[test]
2040    fn test_to_flattened_array() {
2041        || -> Result<()> {
2042            let v = Value::from_scalar(-123456, INT32)?;
2043            assert_eq!(
2044                v.to_flattened_array_u8(array_type(vec![1], INT32))?,
2045                &[(-123456i32) as u8]
2046            );
2047            assert_eq!(
2048                v.to_flattened_array_i8(array_type(vec![1], INT32))?,
2049                &[(-123456i32) as i8]
2050            );
2051            assert_eq!(
2052                v.to_flattened_array_u16(array_type(vec![1], INT32))?,
2053                &[(-123456i32) as u16]
2054            );
2055            assert_eq!(
2056                v.to_flattened_array_i16(array_type(vec![1], INT32))?,
2057                &[(-123456i32) as i16]
2058            );
2059            assert_eq!(
2060                v.to_flattened_array_u32(array_type(vec![1], INT32))?,
2061                &[(-123456i32) as u32]
2062            );
2063            assert_eq!(
2064                v.to_flattened_array_i32(array_type(vec![1], INT32))?,
2065                &[(-123456i32) as i32]
2066            );
2067            assert_eq!(
2068                v.to_flattened_array_u64(array_type(vec![1], INT32))?,
2069                &[(-123456i32) as u64]
2070            );
2071            assert_eq!(
2072                v.to_flattened_array_i64(array_type(vec![1], INT32))?,
2073                &[(-123456i32) as i64]
2074            );
2075            Ok(())
2076        }()
2077        .unwrap();
2078    }
2079
2080    #[test]
2081    fn test_to_ndarray() {
2082        || -> Result<()> {
2083            {
2084                let v = Value::from_scalar(1, BIT)?;
2085                let a = ToNdarray::<bool>::to_ndarray(&v, array_type(vec![1], BIT))?;
2086                assert_eq!(a.shape(), &[1]);
2087                assert_eq!(a[[0]], true);
2088            }
2089            {
2090                let v = Value::from_scalar(0, BIT)?;
2091                let a = ToNdarray::<bool>::to_ndarray(&v, array_type(vec![1], BIT))?;
2092                assert_eq!(a.shape(), &[1]);
2093                assert_eq!(a[[0]], false);
2094            }
2095            let v = Value::from_scalar(-123456, INT32)?;
2096            {
2097                let a = ToNdarray::<u8>::to_ndarray(&v, array_type(vec![1], INT32))?;
2098                assert_eq!(a.shape(), &[1]);
2099                assert_eq!(a[[0]], -123456i32 as u8);
2100            }
2101            {
2102                let a = ToNdarray::<i8>::to_ndarray(&v, array_type(vec![1], INT32))?;
2103                assert_eq!(a.shape(), &[1]);
2104                assert_eq!(a[[0]], -123456i32 as i8);
2105            }
2106            {
2107                let a = ToNdarray::<u16>::to_ndarray(&v, array_type(vec![1], INT32))?;
2108                assert_eq!(a.shape(), &[1]);
2109                assert_eq!(a[[0]], -123456i32 as u16);
2110            }
2111            {
2112                let a = ToNdarray::<i16>::to_ndarray(&v, array_type(vec![1], INT32))?;
2113                assert_eq!(a.shape(), &[1]);
2114                assert_eq!(a[[0]], -123456i32 as i16);
2115            }
2116            {
2117                let a = ToNdarray::<u32>::to_ndarray(&v, array_type(vec![1], INT32))?;
2118                assert_eq!(a.shape(), &[1]);
2119                assert_eq!(a[[0]], -123456i32 as u32);
2120            }
2121            {
2122                let a = ToNdarray::<i32>::to_ndarray(&v, array_type(vec![1], INT32))?;
2123                assert_eq!(a.shape(), &[1]);
2124                assert_eq!(a[[0]], -123456i32 as i32);
2125            }
2126            {
2127                let a = ToNdarray::<u64>::to_ndarray(&v, array_type(vec![1], INT32))?;
2128                assert_eq!(a.shape(), &[1]);
2129                assert_eq!(a[[0]], -123456i32 as u64);
2130            }
2131            {
2132                let a = ToNdarray::<i64>::to_ndarray(&v, array_type(vec![1], INT32))?;
2133                assert_eq!(a.shape(), &[1]);
2134                assert_eq!(a[[0]], -123456i32 as i64);
2135            }
2136            Ok(())
2137        }()
2138        .unwrap();
2139    }
2140}