Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls-tokio/src/task/waker/contract.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use core::{
5 sync::atomic::{AtomicBool, Ordering},
6 task::{Context, Poll, Waker},
7 };
8 use std::{sync::Arc, task::Wake};
9
10 /// Checks that if a function returns [`Poll::Pending`], then the function called [`Waker::clone`],
11 /// [`Waker::wake`], or [`Waker::wake_by_ref`] on the [`Context`]'s [`Waker`].
12 pub struct Contract {
13 state: Arc<State>,
14 waker: Waker,
15 }
16
17 struct State {
18 inner: Waker,
19 wake_called: AtomicBool,
20 }
21
22 impl Wake for State {
23 #[inline]
24 fn wake(self: Arc<Self>) {
25 Wake::wake_by_ref(&self)
26 }
27
28 #[inline]
29 fn wake_by_ref(self: &Arc<Self>) {
30 self.wake_called.store(true, Ordering::Release);
31 self.inner.wake_by_ref();
32 }
33 }
34
35 impl Contract {
36 /// Wraps a [`Context`] in the contract checker
37 #[inline]
38 pub fn new(cx: &mut Context) -> Self {
39 let state = State {
40 inner: cx.waker().clone(),
41 wake_called: AtomicBool::new(false),
42 };
43 let state = Arc::new(state);
44 let waker = Waker::from(state.clone());
45 Self { state, waker }
46 }
47
48 /// Returns a new [`Context`] to be checked
49 #[inline]
50 pub fn context(&self) -> Context<'_> {
51 Context::from_waker(&self.waker)
52 }
53
54 /// Checks the state of the waker based on the provided `outcome`
55 #[inline]
56 #[track_caller]
57 pub fn check_outcome<T>(self, outcome: &Poll<T>) {
58 if outcome.is_ready() {
59 return;
60 }
61
62 let strong_count = Arc::strong_count(&self.state);
63 let is_cloned = strong_count > 2; // 1 for `state`, one for our owned `waker`
64 let wake_called = self.state.wake_called.load(Ordering::Acquire);
65
66 let is_ok = is_cloned || wake_called;
67
68 assert!(
69 is_ok,
70 "strong_count = {strong_count}; is_cloned = {is_cloned}; wake_called = {wake_called}"
71 );
72 }
73 }
74
75 /// Checks that if a function returns [`Poll::Pending`], then the function called [`Waker::clone`],
76 /// [`Waker::wake`], or [`Waker::wake_by_ref`] on the [`Context`]'s [`Waker`].
77 #[inline(always)]
78 #[track_caller]
79 pub fn assert_contract<F: FnOnce(&mut Context) -> Poll<R>, R>(cx: &mut Context, f: F) -> Poll<R> {
80 let contract = Contract::new(cx);
81 let mut cx = contract.context();
82 let outcome = f(&mut cx);
83 contract.check_outcome(&outcome);
84 outcome
85 }
86
87 /// Checks that if a function returns [`Poll::Pending`], then the function called [`Waker::clone`],
88 /// [`Waker::wake`], or [`Waker::wake_by_ref`] on the [`Context`]'s [`Waker`].
89 ///
90 /// This is only enabled with `debug_assertions`.
91 #[inline(always)]
92 #[track_caller]
93 pub fn debug_assert_contract<F: FnOnce(&mut Context) -> Poll<R>, R>(
94 cx: &mut Context,
95 f: F,
96 ) -> Poll<R> {
97 #[cfg(debug_assertions)]
98 return assert_contract(cx, f);
99
100 #[cfg(not(debug_assertions))]
101 return f(cx);
102 }
103
104 #[cfg(test)]
105 mod tests {
106 use super::*;
107
108 #[inline]
109 pub fn noop() -> Waker {
110 use core::{
111 ptr,
112 task::{RawWaker, RawWakerVTable},
113 };
114
115 const VTABLE: RawWakerVTable = RawWakerVTable::new(
116 // Cloning just returns a new no-op raw waker
117 |_| RAW,
118 // `wake` does nothing
119 |_| {},
120 // `wake_by_ref` does nothing
121 |_| {},
122 // Dropping does nothing as we don't allocate anything
123 |_| {},
124 );
125 const RAW: RawWaker = RawWaker::new(ptr::null(), &VTABLE);
126
127 unsafe { Waker::from_raw(RAW) }
128 }
129
130 #[test]
131 fn correct_test() {
132 let waker = noop();
133 let mut cx = Context::from_waker(&waker);
134
135 // the contract isn't violated when returning Ready
136 let _ = assert_contract(&mut cx, |_cx| Poll::Ready(()));
137
138 // the contract isn't violated if the waker is immediately woken
139 let _ = assert_contract(&mut cx, |cx| {
140 cx.waker().wake_by_ref();
141 Poll::<()>::Pending
142 });
143
144 // the contract isn't violated if the waker is cloned then immediately woken
145 let _ = assert_contract(&mut cx, |cx| {
146 let waker = cx.waker().clone();
147 waker.wake();
148 Poll::<()>::Pending
149 });
150
151 // the contract isn't violated if the waker is cloned and stored for later
152 let mut stored = None;
153 let _ = assert_contract(&mut cx, |cx| {
154 stored = Some(cx.waker().clone());
155 Poll::<()>::Pending
156 });
157 }
158
159 #[test]
160 #[should_panic]
161 fn incorrect_test() {
162 let waker = noop();
163 let mut cx = Context::from_waker(&waker);
164
165 // the contract is violated if we return Pending without doing anything
166 let _ = assert_contract(&mut cx, |_cx| Poll::<()>::Pending);
167 }
168 }