Skip to content
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
118 changes: 118 additions & 0 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ serde_crate = { workspace = true, optional = true }

[dev-dependencies]
amplify = { workspace = true, features = ["proc_attr", "hex"] }
ciborium = "0.2.2"
half = "<2.5.0"
serde_json = "1.0.140"
serde_yaml = "0.9.34"
strict_encoding_test = { path = "./test_helpers" }

[target.'cfg(target_arch = "wasm32")'.dependencies]
Expand Down
4 changes: 2 additions & 2 deletions rust/src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ pub struct TupleReader<'parent, R: ReadRaw> {
parent: &'parent mut StrictReader<R>,
}

impl<'parent, R: ReadRaw> ReadTuple for TupleReader<'parent, R> {
impl<R: ReadRaw> ReadTuple for TupleReader<'_, R> {
fn read_field<T: StrictDecode>(&mut self) -> Result<T, DecodeError> {
self.read_fields += 1;
T::strict_decode(self.parent)
Expand All @@ -247,7 +247,7 @@ pub struct StructReader<'parent, R: ReadRaw> {
parent: &'parent mut StrictReader<R>,
}

impl<'parent, R: ReadRaw> ReadStruct for StructReader<'parent, R> {
impl<R: ReadRaw> ReadStruct for StructReader<'_, R> {
fn read_field<T: StrictDecode>(&mut self, field: FieldName) -> Result<T, DecodeError> {
self.named_fields.push(field);
T::strict_decode(self.parent)
Expand Down
104 changes: 103 additions & 1 deletion rust/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,84 @@
}

#[derive(Clone, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"))]
pub struct Variant {
pub name: VariantName,
pub tag: u8,
}
impl_strict_struct!(Variant, STRICT_TYPES_LIB; name, tag);

#[cfg(feature = "serde")]
// The manual serde implementation is needed due to `Variant` bein used as a key in maps (like enum
// or union fields), and serde text implementations such as JSON can't serialize map keys if they
// are not strings. This solves the issue, by putting string serialization of `Variant` for
// human-readable serializers
mod _serde {
use std::str::FromStr;

use serde_crate::ser::SerializeStruct;
use serde_crate::{Deserialize, Deserializer, Serialize, Serializer};

use super::*;

impl Serialize for Variant {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
if serializer.is_human_readable() {
serializer.serialize_str(&format!("{}:{}", self.name, self.tag))
} else {
let mut s = serializer.serialize_struct("Variant", 2)?;
s.serialize_field("name", &self.name)?;
s.serialize_field("tag", &self.tag)?;
s.end()
}
}
}

impl<'de> Deserialize<'de> for Variant {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> {
if deserializer.is_human_readable() {
let s = String::deserialize(deserializer)?;
let mut split = s.split(':');
let (name, tag) = (split.next(), split.next());
if split.next().is_some() {
return Err(serde::de::Error::custom(format!(
"Invalid variant format: '{}'. Expected 'name:tag'",
s
)));

Check warning on line 131 in rust/src/util.rs

View check run for this annotation

Codecov / codecov/patch

rust/src/util.rs#L128-L131

Added lines #L128 - L131 were not covered by tests
}
match (name, tag) {
(Some(name), Some(tag)) => {
let name = VariantName::from_str(name).map_err(|e| {
serde::de::Error::custom(format!("Invalid variant name: {}", e))
})?;

Check warning on line 137 in rust/src/util.rs

View check run for this annotation

Codecov / codecov/patch

rust/src/util.rs#L136-L137

Added lines #L136 - L137 were not covered by tests
let tag = tag.parse::<u8>().map_err(|e| {
serde::de::Error::custom(format!("Invalid variant tag: {}", e))
})?;

Check warning on line 140 in rust/src/util.rs

View check run for this annotation

Codecov / codecov/patch

rust/src/util.rs#L139-L140

Added lines #L139 - L140 were not covered by tests
Ok(Variant { name, tag })
}
_ => Err(serde::de::Error::custom(format!(
"Invalid variant format: '{}'. Expected 'name:tag'",
s
))),

Check warning on line 146 in rust/src/util.rs

View check run for this annotation

Codecov / codecov/patch

rust/src/util.rs#L143-L146

Added lines #L143 - L146 were not covered by tests
}
} else {
#[cfg_attr(
feature = "serde",
derive(Deserialize),
serde(crate = "serde_crate", rename = "Variant")
)]
struct VariantFields {
name: VariantName,
tag: u8,
}
let VariantFields { name, tag } = VariantFields::deserialize(deserializer)?;
Ok(Variant { name, tag })
}
}
}
}

impl Variant {
pub fn named(tag: u8, name: VariantName) -> Variant { Variant { name, tag } }

Expand Down Expand Up @@ -138,3 +209,34 @@
Ok(())
}
}

#[cfg(test)]
mod test {
#![allow(unused)]

use std::io::Cursor;

use crate::*;

#[cfg(feature = "serde")]
#[test]
fn variant_serde_roundtrip() {
let variant_orig = Variant::strict_dumb();

// CBOR
let mut buf = Vec::new();
ciborium::into_writer(&variant_orig, &mut buf).unwrap();
let variant_post: Variant = ciborium::from_reader(Cursor::new(&buf)).unwrap();
assert_eq!(variant_orig, variant_post);

// JSON
let variant_str = serde_json::to_string(&variant_orig).unwrap();
let variant_post: Variant = serde_json::from_str(&variant_str).unwrap();
assert_eq!(variant_orig, variant_post);

// YAML
let variant_str = serde_yaml::to_string(&variant_orig).unwrap();
let variant_post: Variant = serde_yaml::from_str(&variant_str).unwrap();
assert_eq!(variant_orig, variant_post);
}
}