diff options
| author | wanglei <[email protected]> | 2024-07-31 00:25:28 +0800 |
|---|---|---|
| committer | wanglei <[email protected]> | 2024-07-31 10:32:44 +0800 |
| commit | 05562b92af53c742c6531ec616afd518112687b8 (patch) | |
| tree | 4fd2ca0473a9fa6ab2456e6e8e415044c2f6169b /embassy-sync | |
| parent | 93696c912e7264e101308a3f205272dcdd44e6b2 (diff) | |
embassy-sync: more unit-test for LazyLock
Signed-off-by: wanglei <[email protected]>
Diffstat (limited to 'embassy-sync')
| -rw-r--r-- | embassy-sync/src/lazy_lock.rs | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/embassy-sync/src/lazy_lock.rs b/embassy-sync/src/lazy_lock.rs index cf88bfdf8..18e3c2019 100644 --- a/embassy-sync/src/lazy_lock.rs +++ b/embassy-sync/src/lazy_lock.rs | |||
| @@ -103,3 +103,50 @@ impl<T, F> Drop for LazyLock<T, F> { | |||
| 103 | } | 103 | } |
| 104 | } | 104 | } |
| 105 | } | 105 | } |
| 106 | |||
| 107 | #[cfg(test)] | ||
| 108 | mod tests { | ||
| 109 | use core::sync::atomic::{AtomicU32, Ordering}; | ||
| 110 | |||
| 111 | use super::*; | ||
| 112 | |||
| 113 | #[test] | ||
| 114 | fn test_lazy_lock() { | ||
| 115 | static VALUE: LazyLock<u32> = LazyLock::new(|| 20); | ||
| 116 | let reference = VALUE.get(); | ||
| 117 | assert_eq!(reference, &20); | ||
| 118 | } | ||
| 119 | #[test] | ||
| 120 | fn test_lazy_lock_into_inner() { | ||
| 121 | let lazy: LazyLock<u32> = LazyLock::new(|| 20); | ||
| 122 | let value = lazy.into_inner(); | ||
| 123 | assert_eq!(value, 20); | ||
| 124 | } | ||
| 125 | |||
| 126 | static DROP_CHECKER: AtomicU32 = AtomicU32::new(0); | ||
| 127 | struct DropCheck; | ||
| 128 | |||
| 129 | impl Drop for DropCheck { | ||
| 130 | fn drop(&mut self) { | ||
| 131 | DROP_CHECKER.fetch_add(1, Ordering::Acquire); | ||
| 132 | } | ||
| 133 | } | ||
| 134 | |||
| 135 | #[test] | ||
| 136 | fn test_lazy_drop() { | ||
| 137 | let lazy: LazyLock<DropCheck> = LazyLock::new(|| DropCheck); | ||
| 138 | assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 0); | ||
| 139 | lazy.get(); | ||
| 140 | drop(lazy); | ||
| 141 | assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 1); | ||
| 142 | |||
| 143 | let dropper = DropCheck; | ||
| 144 | let lazy_fn: LazyLock<u32, _> = LazyLock::new(move || { | ||
| 145 | let _a = dropper; | ||
| 146 | 20 | ||
| 147 | }); | ||
| 148 | assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 1); | ||
| 149 | drop(lazy_fn); | ||
| 150 | assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 2); | ||
| 151 | } | ||
| 152 | } | ||
