former_runtime/
hash_map.rs

1
2///
3/// Trait HashMapLike adopter for HashMap-like containers.
4///
5
6pub trait HashMapLike< K, E >
7where
8  K : std::cmp::Eq + std::hash::Hash,
9{
10  /// Inserts a key-value pair into the map.
11  fn insert( &mut self, k : K, e : E ) -> Option< E >;
12}
13
14impl< K, E > HashMapLike< K, E > for std::collections::HashMap< K, E >
15where
16  K : std::cmp::Eq + std::hash::Hash,
17{
18  fn insert( &mut self, k : K, e : E ) -> Option< E >
19  {
20    std::collections::HashMap::insert( self, k, e )
21  }
22}
23
24///
25/// Class for forming hashmap-like fields.
26///
27
28#[derive( Debug, Default )]
29pub struct HashMapFormer< K, E, HashMap, Former, ContainerEnd >
30where
31  K : std::cmp::Eq + std::hash::Hash,
32  HashMap : HashMapLike< K, E > + std::default::Default,
33  ContainerEnd : Fn( &mut Former, core::option::Option< HashMap > ),
34{
35  container : Option< HashMap >,
36  former : Former,
37  on_end : ContainerEnd,
38  _e_phantom : core::marker::PhantomData< E >,
39  _k_phantom : core::marker::PhantomData< K >,
40}
41
42impl< K, E, HashMap, Former, ContainerEnd >
43HashMapFormer< K, E, HashMap, Former, ContainerEnd >
44where
45  K : std::cmp::Eq + std::hash::Hash,
46  HashMap : HashMapLike< K, E > + std::default::Default,
47  ContainerEnd : Fn( &mut Former, core::option::Option< HashMap > ),
48{
49
50  /// Make a new HashMapFormer. It should be called by a former generated for your structure.
51  pub fn new( former : Former, container : core::option::Option< HashMap >, on_end : ContainerEnd ) -> Self
52  {
53    Self
54    {
55      former,
56      container,
57      on_end,
58      _e_phantom : core::marker::PhantomData,
59      _k_phantom : core::marker::PhantomData,
60    }
61  }
62
63  /// Set the whole container instead of setting each element individually.
64  pub fn replace( mut self, container : HashMap ) -> Self
65  {
66    debug_assert!( self.container.is_none() );
67    self.container = Some( container );
68    self
69  }
70
71  /// Return former of your struct moving container there. Should be called after configuring the container.
72  pub fn end( mut self ) -> Former
73  {
74    let container = self.container.take();
75    ( self.on_end )( &mut self.former, container );
76    self.former
77  }
78
79  /// Inserts a key-value pair into the map. Make a new container if it was not made so far.
80  pub fn insert< K2, E2 >( mut self, k : K2, e : E2 ) -> Self
81  where
82    K2 : core::convert::Into< K >,
83    E2 : core::convert::Into< E >,
84  {
85    if self.container.is_none()
86    {
87      self.container = core::option::Option::Some( Default::default() );
88    }
89    if let core::option::Option::Some( ref mut container ) = self.container
90    {
91      container.insert( k.into(), e.into() );
92    }
93    self
94  }
95
96}
97
98//