Skip to content

Commit

Permalink
Struggle with features serialization/deserialization with iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
optout21 committed Sep 6, 2024
1 parent 05dd6a1 commit babfa97
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lightning-invoice/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,27 @@ impl FromBase32 for Bolt11InvoiceFeatures {
/// and taking the resulting 8-bit values (right to left),
/// with the leading 0's skipped.
fn from_base32(field_data: &[Fe32]) -> Result<Self, Self::Err> {
// fes_to_bytes() trims, input needs to be padded, find padding size
let input_len = field_data.len();
let mut padding = 0;
while ((input_len + padding) * 5) % 8 != 0 {
padding += 1;
}
let mut output = field_data
.iter()
.map(|f| Fe32::try_from(f.to_u8().reverse_bits() >> 3).expect("<32"))
.rev()
.chain(core::iter::repeat(Fe32::Q).take(padding))
.fes_to_bytes()
.map(|b| b.reverse_bits())
.collect::<Vec<u8>>();
// Trim the highest feature bits -<-- COULD NOT DO WITH ITER
while !output.is_empty() && output[output.len() - 1] == 0 {
output.pop();
}
Ok(Bolt11InvoiceFeatures::from_le_bytes(output))

/*
// Fe32 conversion cannot be used, because this unpacks from right, right-to-left
// Carry bits, 0, 1, 2, 3, or 4 bits
let mut carry_bits = 0;
Expand Down Expand Up @@ -116,6 +137,7 @@ impl FromBase32 for Bolt11InvoiceFeatures {
output.pop();
}
Ok(Bolt11InvoiceFeatures::from_le_bytes(output))
*/
}
}

Expand Down
14 changes: 14 additions & 0 deletions lightning-invoice/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,19 @@ impl Base32Iterable for Bolt11InvoiceFeatures {
/// and taking the resulting 5-bit values in reverse (left-to-right),
/// with the leading 0's skipped.
fn fe_iter<'s>(&'s self) -> Box<dyn Iterator<Item = Fe32> + 's> {
Box::new(
self
.le_flags()
.iter()
.map(|b| b.reverse_bits())
.bytes_to_fes()
.collect::<Vec<Fe32>>().into_iter() // <-- COULD NOT DO WITHOUT COLLECT
.rev()
.map(|f| Fe32::try_from(f.to_u8().reverse_bits() >> 3).expect("<32"))
.skip_while(|e| *e == Fe32::Q)
)

/*
// Fe32 conversion cannot be used, because this packs from right, right-to-left
let mut input_iter = self.le_flags().iter();
// Carry bits, 0..7 bits
Expand Down Expand Up @@ -123,6 +136,7 @@ impl Base32Iterable for Bolt11InvoiceFeatures {
}
// Take result in reverse order, and skip leading 0s
Box::new(output.into_iter().rev().skip_while(|e| *e == Fe32::Q))
*/
}
}

Expand Down

0 comments on commit babfa97

Please sign in to comment.