Skip to content

Commit 996893a

Browse files
authored
fix(codec): calculate length of encoded array (#654)
1 parent 1234f61 commit 996893a

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

pallas-codec/src/lib.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ macro_rules! codec_by_datatype {
4242
) -> Result<(), minicbor::encode::Error<W::Error>> {
4343
match self {
4444
$( $enum_name::$many_f ($( $vars ),+) => {
45-
e.array(2)?;
45+
// Counting the number of `$vars`:
46+
let length: u64 = 0 $(+ { let _ = $vars; 1 })+;
47+
e.array(length)?;
4648
$( e.encode_with($vars, ctx)?; )+
4749
}, )?
4850
$( $enum_name::$one_f(__x666) => {
@@ -55,3 +57,44 @@ macro_rules! codec_by_datatype {
5557
}
5658
}
5759
}
60+
61+
#[cfg(test)]
62+
mod tests {
63+
use super::minicbor::{self, decode, encode, Decode, Encode};
64+
65+
#[derive(Clone, Debug)]
66+
enum Thing {
67+
Coin(u32),
68+
Change(bool),
69+
Multiasset(bool, u64, i32),
70+
}
71+
72+
codec_by_datatype! {
73+
Thing,
74+
U8 | U16 | U32 => Coin,
75+
Bool => Change,
76+
(b, u, i => Multiasset)
77+
}
78+
79+
#[cfg(test)]
80+
pub fn roundtrip_codec<T: Encode<()> + for<'a> Decode<'a, ()> + std::fmt::Debug>(
81+
query: T,
82+
) -> () {
83+
let mut cbor = Vec::new();
84+
match encode(query, &mut cbor) {
85+
Ok(_) => (),
86+
Err(err) => panic!("Unable to encode data ({:?})", err),
87+
};
88+
println!("{:-<70}\nResulting CBOR: {:02x?}", "", cbor);
89+
90+
let query: T = decode(&cbor).unwrap();
91+
println!("Decoded data: {:?}", query);
92+
}
93+
94+
#[test]
95+
fn roundtrip_codec_by_datatype() {
96+
roundtrip_codec(Thing::Coin(0xfafa));
97+
roundtrip_codec(Thing::Change(false));
98+
roundtrip_codec(Thing::Multiasset(true, 10, -20));
99+
}
100+
}

0 commit comments

Comments
 (0)