Skip to content

Commit 4607c70

Browse files
committed
chore: simplify *Metrics::alloc and avoid .unwrap()
Reduce number of unwraps/lock operations needed by using the `.entry()` API for more idiomatic code. Signed-off-by: Patrick Roy <roypat@amazon.co.uk>
1 parent c036a6d commit 4607c70

File tree

3 files changed

+16
-33
lines changed

3 files changed

+16
-33
lines changed

src/vmm/src/devices/virtio/block/virtio/metrics.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -100,20 +100,14 @@ impl BlockMetricsPerDevice {
100100
/// lock is always initialized so it is safe the unwrap
101101
/// the lock without a check.
102102
pub fn alloc(drive_id: String) -> Arc<BlockDeviceMetrics> {
103-
if METRICS.read().unwrap().metrics.get(&drive_id).is_none() {
103+
Arc::clone(
104104
METRICS
105105
.write()
106106
.unwrap()
107107
.metrics
108-
.insert(drive_id.clone(), Arc::new(BlockDeviceMetrics::new()));
109-
}
110-
METRICS
111-
.read()
112-
.unwrap()
113-
.metrics
114-
.get(&drive_id)
115-
.unwrap()
116-
.clone()
108+
.entry(drive_id)
109+
.or_insert_with(|| Arc::new(BlockDeviceMetrics::default())),
110+
)
117111
}
118112
}
119113

src/vmm/src/devices/virtio/net/metrics.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -102,20 +102,14 @@ impl NetMetricsPerDevice {
102102
/// lock is always initialized so it is safe the unwrap
103103
/// the lock without a check.
104104
pub fn alloc(iface_id: String) -> Arc<NetDeviceMetrics> {
105-
if METRICS.read().unwrap().metrics.get(&iface_id).is_none() {
105+
Arc::clone(
106106
METRICS
107107
.write()
108108
.unwrap()
109109
.metrics
110-
.insert(iface_id.clone(), Arc::new(NetDeviceMetrics::new()));
111-
}
112-
METRICS
113-
.read()
114-
.unwrap()
115-
.metrics
116-
.get(&iface_id)
117-
.unwrap()
118-
.clone()
110+
.entry(iface_id)
111+
.or_insert_with(|| Arc::new(NetDeviceMetrics::default())),
112+
)
119113
}
120114
}
121115

src/vmm/src/devices/virtio/vhost_user_metrics.rs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,19 +95,14 @@ impl VhostUserMetricsPerDevice {
9595
/// lock is always initialized so it is safe the unwrap
9696
/// the lock without a check.
9797
pub fn alloc(drive_id: String) -> Arc<VhostUserDeviceMetrics> {
98-
if METRICS.read().unwrap().metrics.get(&drive_id).is_none() {
99-
METRICS.write().unwrap().metrics.insert(
100-
drive_id.clone(),
101-
Arc::new(VhostUserDeviceMetrics::default()),
102-
);
103-
}
104-
METRICS
105-
.read()
106-
.unwrap()
107-
.metrics
108-
.get(&drive_id)
109-
.unwrap()
110-
.clone()
98+
Arc::clone(
99+
METRICS
100+
.write()
101+
.unwrap()
102+
.metrics
103+
.entry(drive_id)
104+
.or_insert_with(|| Arc::new(VhostUserDeviceMetrics::default())),
105+
)
111106
}
112107
}
113108

0 commit comments

Comments
 (0)