Skip to main content

fxfs/
drop_event.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use event_listener::Event;
6use std::ops::Deref;
7
8/// Same as Event but notifies when dropped.
9pub struct DropEvent(Event);
10
11impl Drop for DropEvent {
12    fn drop(&mut self) {
13        // `Event` doesn't allocate its internal state until a listener is registered or a
14        // notification is sent. Since we're in the Drop impl, no new listeners can be
15        // registered. If there are no listeners, then we can skip sending the notification,
16        // avoiding unnecessary heap allocation and mutex locking in `Event`.
17        if self.0.total_listeners() > 0 {
18            self.0.notify(usize::MAX);
19        }
20    }
21}
22
23impl Deref for DropEvent {
24    type Target = Event;
25
26    fn deref(&self) -> &Self::Target {
27        &self.0
28    }
29}
30
31impl DropEvent {
32    pub fn new() -> Self {
33        Self(Event::new())
34    }
35}