Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impl versionize for statically sized arrays #1450

Merged
merged 3 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion utils/tfhe-versionable/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::convert::Infallible;
use std::error::Error;
use std::fmt::Display;
use std::marker::PhantomData;
use std::num::Wrapping;
use std::sync::Arc;

pub use derived_traits::{Version, VersionsDispatch};
Expand Down Expand Up @@ -81,6 +82,12 @@ pub enum UnversionizeError {
from_type: String,
source: Box<dyn Error + Send + Sync>,
},

/// The length of a statically sized array is wrong
ArrayLength {
expected_size: usize,
found_size: usize,
},
}

impl Display for UnversionizeError {
Expand All @@ -97,6 +104,15 @@ impl Display for UnversionizeError {
Self::Conversion { from_type, source } => {
write!(f, "Failed to convert from {from_type}: {source}")
}
Self::ArrayLength {
expected_size,
found_size,
} => {
write!(
f,
"Expected array of size {expected_size}, found array of size {found_size}"
)
}
}
}
}
Expand All @@ -106,6 +122,7 @@ impl Error for UnversionizeError {
match self {
UnversionizeError::Upgrade { source, .. } => Some(source.as_ref()),
UnversionizeError::Conversion { source, .. } => Some(source.as_ref()),
UnversionizeError::ArrayLength { .. } => None,
}
}
}
Expand Down Expand Up @@ -228,6 +245,30 @@ impl_scalar_versionize!(f64);

impl_scalar_versionize!(char);

impl<T: Versionize> Versionize for Wrapping<T> {
type Versioned<'vers> = Wrapping<T::Versioned<'vers>> where T: 'vers;

fn versionize(&self) -> Self::Versioned<'_> {
Wrapping(self.0.versionize())
}
}

impl<T: VersionizeOwned> VersionizeOwned for Wrapping<T> {
type VersionedOwned = Wrapping<T::VersionedOwned>;

fn versionize_owned(self) -> Self::VersionedOwned {
Wrapping(T::versionize_owned(self.0))
}
}

impl<T: Unversionize> Unversionize for Wrapping<T> {
fn unversionize(versioned: Self::VersionedOwned) -> Result<Self, UnversionizeError> {
Ok(Wrapping(T::unversionize(versioned.0)?))
}
}

impl<T: NotVersioned> NotVersioned for Wrapping<T> {}

impl<T: Versionize> Versionize for Box<T> {
type Versioned<'vers> = T::Versioned<'vers> where T: 'vers;

Expand Down Expand Up @@ -262,7 +303,7 @@ impl<T: VersionizeVec + Clone> VersionizeOwned for Box<[T]> {
type VersionedOwned = T::VersionedVec;

fn versionize_owned(self) -> Self::VersionedOwned {
T::versionize_vec(self.iter().cloned().collect())
T::versionize_vec(self.to_vec())
}
}

Expand Down Expand Up @@ -312,6 +353,37 @@ impl<T: UnversionizeVec> Unversionize for Vec<T> {
}
}

// Since serde doesn't support arbitrary length arrays with const generics, the array
// is converted to a slice/vec.
impl<const N: usize, T: VersionizeSlice> Versionize for [T; N] {
type Versioned<'vers> = T::VersionedSlice<'vers> where T: 'vers;

fn versionize(&self) -> Self::Versioned<'_> {
T::versionize_slice(self)
}
}

impl<const N: usize, T: VersionizeVec + Clone> VersionizeOwned for [T; N] {
type VersionedOwned = T::VersionedVec;

fn versionize_owned(self) -> Self::VersionedOwned {
T::versionize_vec(self.to_vec())
}
}

impl<const N: usize, T: UnversionizeVec + Clone> Unversionize for [T; N] {
fn unversionize(versioned: Self::VersionedOwned) -> Result<Self, UnversionizeError> {
let v = T::unversionize_vec(versioned)?;
let boxed_slice = v.into_boxed_slice();
TryInto::<Box<[T; N]>>::try_into(boxed_slice)
.map(|array| *array)
.map_err(|slice| UnversionizeError::ArrayLength {
expected_size: N,
found_size: slice.len(),
})
}
}

impl Versionize for String {
type Versioned<'vers> = &'vers str;

Expand Down
74 changes: 74 additions & 0 deletions utils/tfhe-versionable/tests/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! Test the impl of Versionize for various types

use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::marker::PhantomData;
use std::num::Wrapping;
use std::sync::Arc;

use aligned_vec::{ABox, AVec};
use num_complex::Complex;
use tfhe_versionable::{Unversionize, Versionize};

use backward_compat::MyStructVersions;

#[derive(PartialEq, Clone, Debug, Versionize)]
#[versionize(MyStructVersions)]
pub struct MyStruct {
wrap: Wrapping<bool>,
base_box: Box<u8>,
sliced_box: Box<[u16; 50]>,
base_vec: Vec<u32>,
s: String,
opt: Option<u64>,
phantom: PhantomData<u128>,
arc: Arc<i8>,
complex: Complex<i16>,
aligned_box: ABox<i32>,
aligned_vec: AVec<i64>,
never: (),
tuple: (f32, f64),
set: HashSet<i128>,
map: HashMap<char, bool>,
}

mod backward_compat {
use tfhe_versionable::VersionsDispatch;

use super::MyStruct;

#[derive(VersionsDispatch)]
#[allow(unused)]
pub enum MyStructVersions {
V0(MyStruct),
}
}

#[test]
fn test_types() {
let stru = MyStruct {
wrap: Wrapping(false),
base_box: Box::new(42),
sliced_box: vec![11; 50].into_boxed_slice().try_into().unwrap(),
base_vec: vec![1234, 5678],
s: String::from("test"),
opt: Some(0xdeadbeef),
phantom: PhantomData,
arc: Arc::new(-1),
complex: Complex::new(-37, -45),
aligned_box: ABox::new(0, -98765),
aligned_vec: AVec::from_slice(0, &[1, 2, 3, 4]),
never: (),
tuple: (3.14, 2.71),
set: HashSet::from_iter([1, 2, 3].into_iter()),
map: HashMap::from_iter([('t', true), ('e', false), ('s', true)].into_iter()),
};

let mut ser = Vec::new();
ciborium::ser::into_writer(&stru.versionize(), &mut ser).unwrap();

let unser =
MyStruct::unversionize(ciborium::de::from_reader(&mut Cursor::new(&ser)).unwrap()).unwrap();

assert_eq!(stru, unser);
}
Loading