Skip to content

Commit c9d1ed5

Browse files
committed
Add find_all_extract macro to lightning-invoice
Used for extracting more than one field of the same type.
1 parent a8038a8 commit c9d1ed5

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

lightning-invoice/src/lib.rs

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,7 @@ impl SignedRawInvoice {
747747
/// Finds the first element of an enum stream of a given variant and extracts one member of the
748748
/// variant. If no element was found `None` gets returned.
749749
///
750-
/// The following example would extract the first
750+
/// The following example would extract the first B.
751751
/// ```
752752
/// use Enum::*
753753
///
@@ -761,11 +761,35 @@ impl SignedRawInvoice {
761761
/// assert_eq!(find_extract!(elements.iter(), Enum::B(ref x), x), Some(3u16))
762762
/// ```
763763
macro_rules! find_extract {
764-
($iter:expr, $enm:pat, $enm_var:ident) => {
764+
($iter:expr, $enm:pat, $enm_var:ident) => {
765+
find_all_extract!($iter, $enm, $enm_var).next()
766+
};
767+
}
768+
769+
/// Finds the all elements of an enum stream of a given variant and extracts one member of the
770+
/// variant through an iterator.
771+
///
772+
/// The following example would extract all A.
773+
/// ```
774+
/// use Enum::*
775+
///
776+
/// enum Enum {
777+
/// A(u8),
778+
/// B(u16)
779+
/// }
780+
///
781+
/// let elements = vec![A(1), A(2), B(3), A(4)]
782+
///
783+
/// assert_eq!(
784+
/// find_all_extract!(elements.iter(), Enum::A(ref x), x).collect::<Vec<u8>>(),
785+
/// vec![1u8, 2u8, 4u8])
786+
/// ```
787+
macro_rules! find_all_extract {
788+
($iter:expr, $enm:pat, $enm_var:ident) => {
765789
$iter.filter_map(|tf| match *tf {
766790
$enm => Some($enm_var),
767791
_ => None,
768-
}).next()
792+
})
769793
};
770794
}
771795

@@ -886,17 +910,11 @@ impl RawInvoice {
886910

887911
/// (C-not exported) as we don't support Vec<&NonOpaqueType>
888912
pub fn fallbacks(&self) -> Vec<&Fallback> {
889-
self.known_tagged_fields().filter_map(|tf| match tf {
890-
&TaggedField::Fallback(ref f) => Some(f),
891-
_ => None,
892-
}).collect::<Vec<&Fallback>>()
913+
find_all_extract!(self.known_tagged_fields(), TaggedField::Fallback(ref x), x).collect()
893914
}
894915

895916
pub fn routes(&self) -> Vec<&RouteHint> {
896-
self.known_tagged_fields().filter_map(|tf| match tf {
897-
&TaggedField::Route(ref r) => Some(r),
898-
_ => None,
899-
}).collect::<Vec<&RouteHint>>()
917+
find_all_extract!(self.known_tagged_fields(), TaggedField::Route(ref x), x).collect()
900918
}
901919

902920
pub fn amount_pico_btc(&self) -> Option<u64> {

0 commit comments

Comments
 (0)