@@ -965,6 +965,29 @@ impl BindgenContext {
965
965
}
966
966
}
967
967
968
+ /// Temporarily loan `Item` with the given `ItemId`. This provides means to
969
+ /// mutably borrow `Item` while having a reference to `BindgenContext`.
970
+ ///
971
+ /// `Item` with the given `ItemId` is removed from the context, given
972
+ /// closure is executed and then `Item` is placed back.
973
+ ///
974
+ /// # Panics
975
+ ///
976
+ /// Panics if attempt to resolve given `ItemId` inside the given
977
+ /// closure is made.
978
+ fn with_loaned_item < F : FnOnce ( & BindgenContext , & mut Item ) > (
979
+ & mut self ,
980
+ item_id : ItemId ,
981
+ f : F ,
982
+ ) {
983
+ let mut item = self . items . remove ( & item_id) . unwrap ( ) ;
984
+
985
+ f ( self , & mut item) ;
986
+
987
+ let existing = self . items . insert ( item_id, item) ;
988
+ assert ! ( existing. is_none( ) ) ;
989
+ }
990
+
968
991
/// Compute the bitfield allocation units for all `TypeKind::Comp` items we
969
992
/// parsed.
970
993
fn compute_bitfield_units ( & mut self ) {
@@ -973,22 +996,14 @@ impl BindgenContext {
973
996
let need_bitfield_allocation =
974
997
mem:: replace ( & mut self . need_bitfield_allocation , vec ! [ ] ) ;
975
998
for id in need_bitfield_allocation {
976
- // To appease the borrow checker, we temporarily remove this item
977
- // from the context, and then replace it once we are done computing
978
- // its bitfield units. We will never try and resolve this
979
- // `TypeKind::Comp` item's id (which would now cause a panic) during
980
- // bitfield unit computation because it is a non-scalar by
981
- // definition, and non-scalar types may not be used as bitfields.
982
- let mut item = self . items . remove ( & id) . unwrap ( ) ;
983
-
984
- item. kind_mut ( )
985
- . as_type_mut ( )
986
- . unwrap ( )
987
- . as_comp_mut ( )
988
- . unwrap ( )
989
- . compute_bitfield_units ( & * self ) ;
990
-
991
- self . items . insert ( id, item) ;
999
+ self . with_loaned_item ( id, |ctx, item| {
1000
+ item. kind_mut ( )
1001
+ . as_type_mut ( )
1002
+ . unwrap ( )
1003
+ . as_comp_mut ( )
1004
+ . unwrap ( )
1005
+ . compute_bitfield_units ( ctx) ;
1006
+ } ) ;
992
1007
}
993
1008
}
994
1009
@@ -1010,16 +1025,14 @@ impl BindgenContext {
1010
1025
. collect ( ) ;
1011
1026
1012
1027
for id in comp_item_ids {
1013
- let mut item = self . items . remove ( & id) . unwrap ( ) ;
1014
-
1015
- item. kind_mut ( )
1016
- . as_type_mut ( )
1017
- . unwrap ( )
1018
- . as_comp_mut ( )
1019
- . unwrap ( )
1020
- . deanonymize_fields ( self ) ;
1021
-
1022
- self . items . insert ( id, item) ;
1028
+ self . with_loaned_item ( id, |ctx, item| {
1029
+ item. kind_mut ( )
1030
+ . as_type_mut ( )
1031
+ . unwrap ( )
1032
+ . as_comp_mut ( )
1033
+ . unwrap ( )
1034
+ . deanonymize_fields ( ctx) ;
1035
+ } ) ;
1023
1036
}
1024
1037
}
1025
1038
0 commit comments