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

Allow use of errors in places expecting E: std::error::Error #46

Merged
merged 4 commits into from
Jan 30, 2023
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
28 changes: 19 additions & 9 deletions ssz-rs/examples/another_container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,30 @@ struct ComplexTestStruct {
fn main() {
let mut value = ComplexTestStruct {
a: 51972,
b: List::<u16, 128>::from_iter([48645]),
b: List::<u16, 128>::try_from(vec![48645]).unwrap(),
c: 46,
d: List::<u8, 256>::from_iter([105]),
e: VarTestStruct { a: 1558, b: List::<u16, 1024>::from_iter([39947]), c: 65 },
f: Vector::<FixedTestStruct, 4>::from_iter([
d: List::<u8, 256>::try_from(vec![105]).unwrap(),
e: VarTestStruct { a: 1558, b: List::<u16, 1024>::try_from(vec![39947]).unwrap(), c: 65 },
f: Vector::<FixedTestStruct, 4>::try_from(vec![
FixedTestStruct { a: 70, b: 905948488145107787, c: 2675781419 },
FixedTestStruct { a: 3, b: 12539792087931462647, c: 4719259 },
FixedTestStruct { a: 73, b: 13544872847030609257, c: 2819826618 },
FixedTestStruct { a: 159, b: 16328658841145598323, c: 2375225558 },
]),
g: Vector::<VarTestStruct, 2>::from_iter([
VarTestStruct { a: 30336, b: List::<u16, 1024>::from_iter([30909]), c: 240 },
VarTestStruct { a: 64263, b: List::<u16, 1024>::from_iter([38121]), c: 100 },
]),
])
.unwrap(),
g: Vector::<VarTestStruct, 2>::try_from(vec![
VarTestStruct {
a: 30336,
b: List::<u16, 1024>::try_from(vec![30909]).unwrap(),
c: 240,
},
VarTestStruct {
a: 64263,
b: List::<u16, 1024>::try_from(vec![38121]).unwrap(),
c: 100,
},
])
.unwrap(),
};
let encoding = serialize(&value).expect("can serialize");
let expected_encoding = vec![
Expand Down
4 changes: 2 additions & 2 deletions ssz-rs/examples/container_with_some_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ struct Foo<const N: usize> {
fn main() {
let mut example: Foo<4> = Foo {
a: 16u32,
b: Vector::from_iter([3u32, 2u32, 1u32, 10u32]),
b: Vector::try_from(vec![3u32, 2u32, 1u32, 10u32]).unwrap(),
c: true,
d: Bitlist::from_iter([
true, false, false, true, true, false, true, false, true, true, false, false, true,
true, false, true, false, true, true, false, false, true, true, false, true, false,
true,
]),
e: Bar::B(List::from_iter([true, true, false, false, false, true])),
e: Bar::B(List::try_from(vec![true, true, false, false, false, true]).unwrap()),
f: Bitvector::from_iter([false, true, false, true]),
};

Expand Down
28 changes: 19 additions & 9 deletions ssz-rs/examples/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,30 @@ struct ComplexTestStruct {
fn main() {
let value = ComplexTestStruct {
a: 51972,
b: List::<u16, 128>::from_iter([48645]),
b: List::<u16, 128>::try_from(vec![48645]).unwrap(),
c: 46,
d: List::<u8, 256>::from_iter([105]),
e: VarTestStruct { a: 1558, b: List::<u16, 1024>::from_iter([39947]), c: 65 },
f: Vector::<FixedTestStruct, 4>::from_iter([
d: List::<u8, 256>::try_from(vec![105]).unwrap(),
e: VarTestStruct { a: 1558, b: List::<u16, 1024>::try_from(vec![39947]).unwrap(), c: 65 },
f: Vector::<FixedTestStruct, 4>::try_from(vec![
FixedTestStruct { a: 70, b: 905948488145107787, c: 2675781419 },
FixedTestStruct { a: 3, b: 12539792087931462647, c: 4719259 },
FixedTestStruct { a: 73, b: 13544872847030609257, c: 2819826618 },
FixedTestStruct { a: 159, b: 16328658841145598323, c: 2375225558 },
]),
g: Vector::<VarTestStruct, 2>::from_iter([
VarTestStruct { a: 30336, b: List::<u16, 1024>::from_iter([30909]), c: 240 },
VarTestStruct { a: 64263, b: List::<u16, 1024>::from_iter([38121]), c: 100 },
]),
])
.unwrap(),
g: Vector::<VarTestStruct, 2>::try_from(vec![
VarTestStruct {
a: 30336,
b: List::<u16, 1024>::try_from(vec![30909]).unwrap(),
c: 240,
},
VarTestStruct {
a: 64263,
b: List::<u16, 1024>::try_from(vec![38121]).unwrap(),
c: 100,
},
])
.unwrap(),
h: Bitvector::from_iter([true, false, false, true, false, false, false, true, true]),
i: Bitlist::from_iter([true, false, true, true]),
j: U256::from_bytes_le([12u8; 32]),
Expand Down
2 changes: 1 addition & 1 deletion ssz-rs/scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ where `$TYPE` is one of: `boolean, uints, basic_vector, bitlist, bitvector, cont
or to generate new test code, altogether:

```bash
for TYPE in boolean uints basic_vector bitlist bitvector containers; do truncate --size 0 ../tests/$TYPE.rs && python gen.py $TYPE >> ../tests/$TYPE.rs && rustfmt ../tests/$TYPE.rs; done
for TYPE in boolean uints basic_vector bitlist bitvector containers; do truncate --size 0 ../tests/$TYPE.rs && python gen.py $TYPE >> ../tests/$TYPE.rs && cargo +nightly fmt ../tests/$TYPE.rs; done
```
20 changes: 11 additions & 9 deletions ssz-rs/scripts/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def _map_to_rust_u256(value):
as_bytes = []
for byte in data:
as_bytes.append(byte)
return f"U256({as_bytes})"
return f"U256::from_bytes_le({as_bytes})"


def _map_to_rust_vector(value, rust_type):
Expand All @@ -110,12 +110,14 @@ def _map_to_rust_vector(value, rust_type):
for element in value:
elements.append(_map_to_rust_u256(element))
inline = ", ".join(elements)
return f"{rust_type}::from_iter([{inline}])"
return f"{rust_type}::try_from(Vec::<U256>::from_iter([{inline}])).unwrap()"
elif "u128" in rust_type:
inline = ", ".join(value)
return f"{rust_type}::from_iter([{inline}])"
return f"{rust_type}::try_from(Vec::<u128>::from_iter([{inline}])).unwrap()"
else:
return f"{rust_type}::from_iter({str(value).lower()})"
# bit of a hack...
inner_type = rust_type.split("<")[1].split(",")[0]
return f"{rust_type}::try_from(Vec::<{inner_type}>::from_iter({str(value).lower()})).unwrap()"


def _decode_bitvector(value, bound):
Expand Down Expand Up @@ -155,27 +157,27 @@ def _decode_field_value(name, value, rust_type):
if rust_type == "VarTestStruct":
if name == "B":
inline = ", ".join(map(str, value))
return f"List::<u16, 1024>::from_iter([{inline}])"
return f"List::<u16, 1024>::try_from(Vec::<u16>::from_iter([{inline}])).unwrap()"
else:
return value
elif rust_type == "ComplexTestStruct":
if name == "B":
inline = ", ".join(map(str, value))
return f"List::<u16, 128>::from_iter([{inline}])"
return f"List::<u16, 128>::try_from(Vec::<u16>::from_iter([{inline}])).unwrap()"
elif name == "D":
value = bytes.fromhex(value[2:])
inline = ", ".join(map(str, value))
return f"List::<u8, 256>::from_iter([{inline}])"
return f"List::<u8, 256>::try_from(Vec::<u8>::from_iter([{inline}])).unwrap()"
elif name == "E":
return _map_to_rust_struct(value, "VarTestStruct")
elif name == "F":
inner = [_map_to_rust_struct(v, "FixedTestStruct") for v in value]
inline = ", ".join(inner)
return f"Vector::<FixedTestStruct, 4>::from_iter([{inline}])"
return f"Vector::<FixedTestStruct, 4>::try_from(vec![{inline}]).unwrap()"
elif name == "G":
inner = [_map_to_rust_struct(v, "VarTestStruct") for v in value]
inline = ", ".join(inner)
return f"Vector::<VarTestStruct, 2>::from_iter([{inline}])"
return f"Vector::<VarTestStruct, 2>::try_from(vec![{inline}]).unwrap()"
else:
return value
elif rust_type == "BitsStruct":
Expand Down
23 changes: 15 additions & 8 deletions ssz-rs/scripts/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ssz-rs/scripts/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description = ""
authors = ["Alex Stokes <r.alex.stokes@gmail.com>"]

[tool.poetry.dependencies]
python = "^3.9"
python = "^3.10"
PyYAML = "^6.0"

[tool.poetry.dev-dependencies]
Expand Down
25 changes: 15 additions & 10 deletions ssz-rs/src/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ mod tests {

#[test]
fn encode_container2() {
let value = SomeContainer { a: 5u32, b: true, c: List::from_iter([true, false]) };
let value =
SomeContainer { a: 5u32, b: true, c: List::try_from(vec![true, false]).unwrap() };

let mut buffer = vec![];
let result = value.serialize(&mut buffer).expect("can serialize");
Expand All @@ -104,7 +105,7 @@ mod tests {
let value = AnotherContainer {
a: 5u32,
b: true,
c: List::from_iter([true, false]),
c: List::try_from(vec![true, false]).unwrap(),
d: Default::default(),
e: 12u8,
};
Expand All @@ -121,7 +122,8 @@ mod tests {
fn decode_container() {
let data = vec![5u8, 0u8, 0u8, 0u8, 1u8, 9u8, 0u8, 0u8, 0u8, 1u8, 0u8];
let result = SomeContainer::deserialize(&data).expect("can deserialize");
let value = SomeContainer { a: 5u32, b: true, c: List::from_iter([true, false]) };
let value =
SomeContainer { a: 5u32, b: true, c: List::try_from(vec![true, false]).unwrap() };
assert_eq!(result, value);
}

Expand All @@ -130,8 +132,8 @@ mod tests {
let value = AnotherContainer {
a: 5u32,
b: true,
c: List::from_iter([true, false, false, false, true, true]),
d: Vector::from_iter([true, false, false, true]),
c: List::try_from(vec![true, false, false, false, true, true]).unwrap(),
d: Vector::try_from(vec![true, false, false, true]).unwrap(),
e: 24u8,
};
let mut buffer = vec![];
Expand All @@ -142,10 +144,10 @@ mod tests {
let value = YetAnotherContainer {
a: 5u32,
b: true,
c: List::from_iter([true, false, false, false, true, true]),
d: Vector::from_iter([true, false, false, true]),
c: List::try_from(vec![true, false, false, false, true, true]).unwrap(),
d: Vector::try_from(vec![true, false, false, true]).unwrap(),
e: 24u8,
f: List::from_iter([234u32, 567u32]),
f: List::try_from(vec![234u32, 567u32]).unwrap(),
};
let mut buffer = vec![];
let _ = value.serialize(&mut buffer).expect("can serialize");
Expand All @@ -162,8 +164,11 @@ mod tests {

#[test]
fn can_derive_struct_with_const_generics() {
let value =
VarWithGenericTestStruct { a: 2u16, b: List::<u16, 2>::from_iter([1u16]), c: 16u8 };
let value = VarWithGenericTestStruct {
a: 2u16,
b: List::<u16, 2>::try_from(vec![1u16]).unwrap(),
c: 16u8,
};
let mut buffer = vec![];
let _ = value.serialize(&mut buffer).expect("can serialize");
}
Expand Down
3 changes: 3 additions & 0 deletions ssz-rs/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ impl Display for DeserializeError {
}
}

#[cfg(feature = "std")]
impl std::error::Error for DeserializeError {}

pub trait Deserialize {
fn deserialize(encoding: &[u8]) -> Result<Self, DeserializeError>
where
Expand Down
13 changes: 13 additions & 0 deletions ssz-rs/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub enum Error {
Serialize(SerializeError),
Deserialize(DeserializeError),
Merkleization(MerkleizationError),
Instance(InstanceError),
Type(TypeError),
}

impl From<SerializeError> for Error {
Expand All @@ -32,10 +34,15 @@ impl Display for Error {
Self::Serialize(err) => write!(f, "could not serialize: {err}"),
Self::Deserialize(err) => write!(f, "could not deserialize: {err}"),
Self::Merkleization(err) => write!(f, "merkleization error: {err}"),
Self::Instance(err) => write!(f, "error constructing instance: {err}"),
Self::Type(err) => write!(f, "type error: {err}"),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

#[derive(Debug)]
pub enum TypeError {
InvalidBound(usize),
Expand All @@ -51,6 +58,9 @@ impl Display for TypeError {
}
}

#[cfg(feature = "std")]
impl std::error::Error for TypeError {}

#[derive(Debug)]
pub enum InstanceError {
Exact { required: usize, provided: usize },
Expand All @@ -71,3 +81,6 @@ impl Display for InstanceError {
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for InstanceError {}
Loading