Skip to main content

ic_canister_kit/common/
once.rs

1use std::{borrow::BorrowMut, cell::RefCell};
2
3thread_local! {
4    static CALL_ONCE: RefCell<bool> = const { RefCell::new(false) };
5}
6
7/// 拦截对象
8pub struct CallOnceGuard;
9
10impl Drop for CallOnceGuard {
11    fn drop(&mut self) {
12        CALL_ONCE.with_borrow_mut(|o| *o.borrow_mut() = false)
13    }
14}
15
16/// 调用一次
17#[inline]
18pub fn call_once_guard() -> CallOnceGuard {
19    if CALL_ONCE.with(|o| *o.borrow()) {
20        ic_cdk::trap("Too many request."); // ! 中止执行
21    }
22
23    CALL_ONCE.with_borrow_mut(|o| *o.borrow_mut() = true);
24
25    CallOnceGuard
26}