@@ -22,6 +22,8 @@ use core::cmp;
22
22
use core:: convert:: TryFrom ;
23
23
use core:: ops:: Deref ;
24
24
25
+ use alloc:: collections:: BTreeMap ;
26
+
25
27
use bitcoin:: secp256k1:: { PublicKey , SecretKey } ;
26
28
use bitcoin:: secp256k1:: constants:: { PUBLIC_KEY_SIZE , SECRET_KEY_SIZE , COMPACT_SIGNATURE_SIZE , SCHNORR_SIGNATURE_SIZE } ;
27
29
use bitcoin:: secp256k1:: ecdsa;
@@ -588,43 +590,47 @@ impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
588
590
fn from ( v : & ' a Vec < T > ) -> Self { Self ( v) }
589
591
}
590
592
591
- // HashMap
592
- impl < K , V > Writeable for HashMap < K , V >
593
- where K : Writeable + Eq + Hash ,
594
- V : Writeable
595
- {
596
- #[ inline]
597
- fn write < W : Writer > ( & self , w : & mut W ) -> Result < ( ) , io:: Error > {
598
- ( self . len ( ) as u16 ) . write ( w) ?;
599
- for ( key, value) in self . iter ( ) {
600
- key. write ( w) ?;
601
- value. write ( w) ?;
593
+ macro_rules! impl_for_map {
594
+ ( $ty: ident, $keybound: ident, $constr: expr) => {
595
+ impl <K , V > Writeable for $ty<K , V >
596
+ where K : Writeable + Eq + $keybound, V : Writeable
597
+ {
598
+ #[ inline]
599
+ fn write<W : Writer >( & self , w: & mut W ) -> Result <( ) , io:: Error > {
600
+ ( self . len( ) as u16 ) . write( w) ?;
601
+ for ( key, value) in self . iter( ) {
602
+ key. write( w) ?;
603
+ value. write( w) ?;
604
+ }
605
+ Ok ( ( ) )
606
+ }
602
607
}
603
- Ok ( ( ) )
604
- }
605
- }
606
608
607
- impl < K , V > Readable for HashMap < K , V >
608
- where K : Readable + Eq + Hash ,
609
- V : MaybeReadable
610
- {
611
- #[ inline]
612
- fn read < R : Read > ( r : & mut R ) -> Result < Self , DecodeError > {
613
- let len: u16 = Readable :: read ( r) ?;
614
- let mut ret = HashMap :: with_capacity ( len as usize ) ;
615
- for _ in 0 ..len {
616
- let k = K :: read ( r) ?;
617
- let v_opt = V :: read ( r) ?;
618
- if let Some ( v) = v_opt {
619
- if ret. insert ( k, v) . is_some ( ) {
620
- return Err ( DecodeError :: InvalidValue ) ;
609
+ impl <K , V > Readable for $ty<K , V >
610
+ where K : Readable + Eq + $keybound, V : MaybeReadable
611
+ {
612
+ #[ inline]
613
+ fn read<R : Read >( r: & mut R ) -> Result <Self , DecodeError > {
614
+ let len: u16 = Readable :: read( r) ?;
615
+ let mut ret = $constr( len as usize ) ;
616
+ for _ in 0 ..len {
617
+ let k = K :: read( r) ?;
618
+ let v_opt = V :: read( r) ?;
619
+ if let Some ( v) = v_opt {
620
+ if ret. insert( k, v) . is_some( ) {
621
+ return Err ( DecodeError :: InvalidValue ) ;
622
+ }
623
+ }
621
624
}
625
+ Ok ( ret)
622
626
}
623
627
}
624
- Ok ( ret)
625
628
}
626
629
}
627
630
631
+ impl_for_map ! ( BTreeMap , Ord , |_| BTreeMap :: new( ) ) ;
632
+ impl_for_map ! ( HashMap , Hash , |len| HashMap :: with_capacity( len) ) ;
633
+
628
634
// HashSet
629
635
impl < T > Writeable for HashSet < T >
630
636
where T : Writeable + Eq + Hash
0 commit comments