async_utils/async_once/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Exposes the OnceCell crate for use in async code.

use async_lock::Mutex;
use once_cell::sync::OnceCell;
use std::future::Future;

/// Wrapper presenting an async interface to a OnceCell.
#[derive(Debug)]
pub struct Once<T> {
    mutex: Mutex<()>,
    value: OnceCell<T>,
}

impl<T> Default for Once<T> {
    fn default() -> Self {
        Self { mutex: Mutex::new(()), value: OnceCell::new() }
    }
}

impl<T> Once<T> {
    /// Constructor.
    pub fn new() -> Self {
        Self { mutex: Mutex::new(()), value: OnceCell::new() }
    }

    /// Async wrapper around OnceCell's `get_or_init`.
    pub async fn get_or_init<'a, F>(&'a self, fut: F) -> &'a T
    where
        F: Future<Output = T>,
    {
        if let Some(t) = self.value.get() {
            t
        } else {
            let _mut = self.mutex.lock().await;
            // Someone raced us and just released the lock
            if let Some(t) = self.value.get() {
                t
            } else {
                let t = fut.await;
                self.value.set(t).unwrap_or_else(|_| panic!("race in async-cell!"));
                self.value.get().unwrap()
            }
        }
    }

    /// Async wrapper around OnceCell's `get_or_try_init`.
    pub async fn get_or_try_init<'a, F, E>(&'a self, fut: F) -> Result<&'a T, E>
    where
        F: Future<Output = Result<T, E>>,
    {
        if let Some(t) = self.value.get() {
            Ok(t)
        } else {
            let _mut = self.mutex.lock().await;
            // Someone raced us and just released the lock
            if let Some(t) = self.value.get() {
                Ok(t)
            } else {
                let r = fut.await;
                match r {
                    Ok(t) => {
                        self.value.set(t).unwrap_or_else(|_| panic!("race in async-cell!"));
                        Ok(self.value.get().unwrap())
                    }
                    Err(e) => Err(e),
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use futures_lite::future::block_on;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn test_get_or_init() {
        lazy_static::lazy_static!(
            static ref ONCE: Once<bool> = Once::new();
        );

        static COUNTER: AtomicUsize = AtomicUsize::new(0);

        let val = block_on(ONCE.get_or_init(async {
            let _: usize = COUNTER.fetch_add(1, Ordering::SeqCst);
            true
        }));

        assert_eq!(*val, true);
        assert_eq!(COUNTER.load(Ordering::SeqCst), 1);

        let val = block_on(ONCE.get_or_init(async {
            let _: usize = COUNTER.fetch_add(1, Ordering::SeqCst);
            false
        }));

        assert_eq!(*val, true);
        assert_eq!(COUNTER.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_get_or_init_default_initializer() {
        lazy_static::lazy_static!(
            static ref ONCE: Once<bool> = Once::default();
        );

        static COUNTER: AtomicUsize = AtomicUsize::new(0);

        let val = block_on(ONCE.get_or_init(async {
            let _: usize = COUNTER.fetch_add(1, Ordering::SeqCst);
            true
        }));

        assert_eq!(*val, true);
        assert_eq!(COUNTER.load(Ordering::SeqCst), 1);

        let val = block_on(ONCE.get_or_init(async {
            let _: usize = COUNTER.fetch_add(1, Ordering::SeqCst);
            false
        }));

        assert_eq!(*val, true);
        assert_eq!(COUNTER.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_get_or_try_init() {
        lazy_static::lazy_static!(
            static ref ONCE: Once<bool> = Once::new();
        );

        static COUNTER: AtomicUsize = AtomicUsize::new(0);

        let initializer = || async {
            let val = COUNTER.fetch_add(1, Ordering::SeqCst);
            if val == 0 {
                Err(std::io::Error::new(std::io::ErrorKind::Other, "first attempt fails"))
            } else {
                Ok(true)
            }
        };

        let val = block_on(ONCE.get_or_try_init(initializer()));

        assert!(val.is_err());
        assert_eq!(COUNTER.load(Ordering::SeqCst), 1);

        // The initializer gets another chance to run because the first attempt failed.
        let val = block_on(ONCE.get_or_try_init(initializer()));
        assert_eq!(*val.unwrap(), true);
        assert_eq!(COUNTER.load(Ordering::SeqCst), 2);

        // The initializer never runs again...
        let val = block_on(ONCE.get_or_try_init(initializer()));
        assert_eq!(*val.unwrap(), true);
        assert_eq!(COUNTER.load(Ordering::SeqCst), 2);
    }
}