Skip to content

Commit 13f97f9

Browse files
committed
Introduce with_loaned_item.
1 parent a398d56 commit 13f97f9

File tree

1 file changed

+39
-26
lines changed

1 file changed

+39
-26
lines changed

src/ir/context.rs

Lines changed: 39 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -965,6 +965,29 @@ impl BindgenContext {
965965
}
966966
}
967967

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+
968991
/// Compute the bitfield allocation units for all `TypeKind::Comp` items we
969992
/// parsed.
970993
fn compute_bitfield_units(&mut self) {
@@ -973,22 +996,14 @@ impl BindgenContext {
973996
let need_bitfield_allocation =
974997
mem::replace(&mut self.need_bitfield_allocation, vec![]);
975998
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+
});
9921007
}
9931008
}
9941009

@@ -1010,16 +1025,14 @@ impl BindgenContext {
10101025
.collect();
10111026

10121027
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+
});
10231036
}
10241037
}
10251038

0 commit comments

Comments
 (0)