Skip to content

Commit 0f5863a

Browse files
committed
util: add support for option with custom encoding
1 parent de384ff commit 0f5863a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

lightning/src/util/ser_macros.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,9 @@ macro_rules! _init_tlv_based_struct_field {
852852
($field: ident, (required_vec, encoding: ($fieldty: ty, $encoding: ident))) => {
853853
$crate::_init_tlv_based_struct_field!($field, required)
854854
};
855+
($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
856+
$crate::_init_tlv_based_struct_field!($field, option)
857+
};
855858
($field: ident, optional_vec) => {
856859
$field.unwrap()
857860
};
@@ -1924,4 +1927,31 @@ mod tests {
19241927
LengthReadable::read_from_fixed_length_buffer(&mut &encoded[..]).unwrap();
19251928
assert_eq!(decoded, instance);
19261929
}
1930+
1931+
#[test]
1932+
fn test_option_with_encoding() {
1933+
// Ensure that serializing an option with a specified encoding will survive a ser round
1934+
// trip for Some and None options.
1935+
#[derive(PartialEq, Eq, Debug)]
1936+
struct MyCustomStruct {
1937+
tlv_field: Option<u64>,
1938+
}
1939+
1940+
impl_writeable_msg!(MyCustomStruct, {}, {
1941+
(1, tlv_field, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
1942+
});
1943+
1944+
for tlv_field in [None, Some(0u64), Some(255u64)] {
1945+
let instance = MyCustomStruct { tlv_field };
1946+
let encoded = instance.encode();
1947+
let decoded: MyCustomStruct =
1948+
LengthReadable::read_from_fixed_length_buffer(&mut &encoded[..]).unwrap();
1949+
assert_eq!(
1950+
decoded,
1951+
MyCustomStruct { tlv_field },
1952+
"option custom encoding failed for: {:?}",
1953+
tlv_field
1954+
);
1955+
}
1956+
}
19271957
}

0 commit comments

Comments
 (0)