blob: c01d74f65479650c97fa9c229776d8265a5dd4a1 [file] [log] [blame]
Brian Silverman9809c5f2022-07-23 16:12:23 -07001#![warn(unsafe_op_in_unsafe_fn)]
2
3//! This module provides a Rust async runtime on top of the C++ `aos::EventLoop` interface.
4//!
5//! # Rust async with `aos::EventLoop`
6//!
7//! The async runtimes we create are not general-purpose. They may only await the objects provided
8//! by this module. Awaiting anything else will hang, until it is woken which will panic. Also,
9//! doing any long-running task (besides await) will block the C++ EventLoop thread, which is
10//! usually bad.
11//!
12//! ## Multiple tasks
13//!
14//! This runtime only supports a single task (aka a single [`Future`]) at a time. For many use
15//! cases, this is sufficient. If you want more than that, one of these may be appropriate:
16//!
17//! 1. If you have a small number of tasks determined at compile time, [`futures::join`] can await
18//! them all simultaneously.
19//! 2. [`futures::stream::FuturesUnordered`] can wait on a variable number of futures. It also
20//! supports adding them at runtime. Consider something like
21//! `FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>` if you want a generic "container of any
22//! future".
23//! 3. Multiple applications are better suited to multiple `EventLoopRuntime`s, on separate
24//! `aos::EventLoop`s. Otherwise they can't send messages to each other, among other
25//! restrictions. https://github.com/frc971/971-Robot-Code/issues/12 covers creating an adapter
26//! that provides multiple `EventLoop`s on top of a single underlying implementation.
27//!
28//! ## Design
29//!
30//! The design of this is tricky. This is a complicated API interface between C++ and Rust. The big
31//! considerations in arriving at this design include:
32//! * `EventLoop` implementations alias the objects they're returning from C++, which means
33//! creating Rust unique references to them is unsound. See
34//! https://github.com/google/autocxx/issues/1146 for details.
35//! * For various reasons autocxx can't directly wrap APIs using types ergonomic for C++. This and
36//! the previous point mean we wrap all of the C++ objects specifically for this class.
37//! * Keeping track of all the lifetimes and creating appropriate references for the callbacks is
38//! really hard in Rust. Even doing it for the library implementation turned out to be hard
39//! enough to look for alternatives. I think you'd have to make extensive use of pointers, but
40//! Rust makes that hard, and it's easy to create references in ways that violate Rust's
41//! aliasing rules.
42//! * We can't use [`futures::stream::Stream`] and all of its nice [`futures::stream::StreamExt`]
43//! helpers for watchers because we need lifetime-generic `Item` types. Effectively we're making
44//! a lending stream. This is very close to lending iterators, which is one of the motivating
45//! examples for generic associated types (https://github.com/rust-lang/rust/issues/44265).
46
47use std::{fmt, future::Future, marker::PhantomData, pin::Pin, slice, task::Poll, time::Duration};
48
49use autocxx::{
50 subclass::{is_subclass, CppSubclass},
51 WithinBox,
52};
53use cxx::UniquePtr;
Brian Silverman90221f82022-08-22 23:46:09 -070054use flatbuffers::{root_unchecked, Follow, FollowWith, FullyQualifiedName};
Brian Silverman9809c5f2022-07-23 16:12:23 -070055use futures::{future::FusedFuture, never::Never};
56use thiserror::Error;
57use uuid::Uuid;
58
Brian Silverman90221f82022-08-22 23:46:09 -070059pub use aos_configuration::{Channel, Configuration, Node};
60use aos_configuration::{ChannelLookupError, ConfigurationExt};
61
Brian Silverman9809c5f2022-07-23 16:12:23 -070062pub use aos_uuid::UUID;
63
64autocxx::include_cpp! (
65#include "aos/events/event_loop_runtime.h"
66
67safety!(unsafe)
68
69generate_pod!("aos::Context")
70generate!("aos::WatcherForRust")
71generate!("aos::RawSender_Error")
72generate!("aos::SenderForRust")
73generate!("aos::FetcherForRust")
Brian Silverman76f48362022-08-24 21:09:08 -070074generate!("aos::OnRunForRust")
Brian Silverman9809c5f2022-07-23 16:12:23 -070075generate!("aos::EventLoopRuntime")
76
77subclass!("aos::ApplicationFuture", RustApplicationFuture)
78
79extern_cpp_type!("aos::Configuration", crate::Configuration)
80extern_cpp_type!("aos::Channel", crate::Channel)
81extern_cpp_type!("aos::Node", crate::Node)
82extern_cpp_type!("aos::UUID", crate::UUID)
83);
84
85pub type EventLoop = ffi::aos::EventLoop;
86
87/// # Safety
88///
89/// This should have a `'event_loop` lifetime and `future` should include that in its type, but
90/// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is
91/// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which
92/// must be outlived by the EventLoop.
93#[doc(hidden)]
94#[is_subclass(superclass("aos::ApplicationFuture"))]
95pub struct RustApplicationFuture {
96 /// This logically has a `'event_loop` bound, see the class comment for details.
97 future: Pin<Box<dyn Future<Output = Never>>>,
98}
99
100impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture {
101 fn Poll(&mut self) {
102 // This is always allowed because it can never create a value of type `Ready<Never>` to
103 // return, so it must always return `Pending`. That also means the value it returns doesn't
104 // mean anything, so we ignore it.
105 let _ =
106 Pin::new(&mut self.future).poll(&mut std::task::Context::from_waker(&panic_waker()));
107 }
108}
109
110impl RustApplicationFuture {
111 pub fn new<'event_loop>(
112 future: impl Future<Output = Never> + 'event_loop,
113 ) -> UniquePtr<ffi::aos::ApplicationFuture> {
114 /// # Safety
115 ///
116 /// This completely removes the `'event_loop` lifetime, the caller must ensure that is
117 /// sound.
118 unsafe fn remove_lifetime<'event_loop>(
119 future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>,
120 ) -> Pin<Box<dyn Future<Output = Never>>> {
121 // SAFETY: Caller is responsible.
122 unsafe { std::mem::transmute(future) }
123 }
124
125 Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self {
126 // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for
127 // details.
128 future: unsafe { remove_lifetime(Box::pin(future)) },
129 cpp_peer: Default::default(),
130 }))
131 }
132}
133
134pub struct EventLoopRuntime<'event_loop>(
135 Pin<Box<ffi::aos::EventLoopRuntime>>,
136 // This is the lifetime of the underlying EventLoop, which is held in C++ via `.0`.
137 PhantomData<&'event_loop mut ()>,
138);
139
140/// Manages the Rust interface to a *single* `aos::EventLoop`. This is intended to be used by a
141/// single application.
142impl<'event_loop> EventLoopRuntime<'event_loop> {
143 /// Creates a new runtime. This must be the only user of the underlying `aos::EventLoop`, or
144 /// things may panic unexpectedly.
145 ///
146 /// Call [`spawn`] to respond to events. The non-event-driven APIs may be used without calling
147 /// this.
148 ///
149 /// This is an async runtime, but it's a somewhat unusual one. See the module-level
150 /// documentation for details.
151 ///
152 /// # Safety
153 ///
154 /// `event_loop` must be valid for `'event_loop`. Effectively we want the argument to be
155 /// `&'event_loop mut EventLoop`, but we can't do that (see the module-level documentation for
156 /// details).
157 ///
158 /// This is a tricky thing to guarantee, be very cautious calling this function. It's an unbound
159 /// lifetime so you should probably wrap it in a function that directly attaches a known
160 /// lifetime. One common pattern is calling this in the constructor of an object whose lifetime
161 /// is managed by C++; C++ doesn't inherit the Rust lifetime but we do have a lot of C++ code
162 /// that obeys the rule of destroying the object before the EventLoop, which is equivalent to
163 /// this restriction.
164 ///
165 /// In Rust terms, this is equivalent to storing `event_loop` in the returned object, which
166 /// will dereference it throughout its lifetime, and the caller must guarantee this is sound.
167 pub unsafe fn new(event_loop: *mut ffi::aos::EventLoop) -> Self {
168 Self(
169 // SAFETY: We push all the validity requirements for this up to our caller.
170 unsafe { ffi::aos::EventLoopRuntime::new(event_loop) }.within_box(),
171 PhantomData,
172 )
173 }
174
175 /// Returns the pointer passed into the constructor.
176 ///
177 /// The returned value should only be used for destroying it (_after_ `self` is dropped) or
178 /// calling other C++ APIs.
179 pub fn raw_event_loop(&mut self) -> *mut ffi::aos::EventLoop {
180 self.0.as_mut().event_loop()
181 }
182
Brian Silverman90221f82022-08-22 23:46:09 -0700183 /// Returns a reference to the name of this EventLoop.
184 ///
185 /// TODO(Brian): Come up with a nice way to expose this safely, without memory allocations, for
186 /// logging etc.
187 ///
188 /// # Safety
189 ///
190 /// The result must not be used after C++ could change it. Unfortunately C++ can change this
191 /// name from most places, so you should be really careful what you do with the result.
192 pub unsafe fn raw_name(&self) -> &str {
193 self.0.name()
194 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700195
196 pub fn get_raw_channel(
197 &self,
198 name: &str,
199 typename: &str,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700200 ) -> Result<&'event_loop Channel, ChannelLookupError> {
Brian Silverman90221f82022-08-22 23:46:09 -0700201 self.configuration().get_channel(
202 name,
203 typename,
204 // SAFETY: We're not calling any EventLoop methods while C++ is using this for the
205 // channel lookup.
206 unsafe { self.raw_name() },
207 self.node(),
208 )
Brian Silverman9809c5f2022-07-23 16:12:23 -0700209 }
210
Brian Silverman90221f82022-08-22 23:46:09 -0700211 pub fn get_channel<T: FullyQualifiedName>(
212 &self,
213 name: &str,
214 ) -> Result<&'event_loop Channel, ChannelLookupError> {
215 self.get_raw_channel(name, T::get_fully_qualified_name())
216 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700217
218 /// Starts running the given `task`, which may not return (as specified by its type). If you
219 /// want your task to stop, return the result of awaiting [`futures::future::pending`], which
220 /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits.
221 ///
Brian Silverman76f48362022-08-24 21:09:08 -0700222 /// Note that task will be polled immediately, to give it a chance to initialize. If you want to
223 /// defer work until the event loop starts running, await [`on_run`] in the task.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700224 ///
225 /// # Panics
226 ///
227 /// Panics if called more than once. See the module-level documentation for alternatives if you
228 /// want to do this.
229 ///
230 /// # Examples with interesting return types
231 ///
232 /// These are all valid futures which never return:
233 /// ```
234 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
235 /// # use futures::{never::Never, future::pending};
236 /// async fn pending_wrapper() -> Never {
237 /// pending().await
238 /// }
239 /// async fn loop_forever() -> Never {
240 /// loop {}
241 /// }
242 ///
243 /// runtime.spawn(pending());
244 /// runtime.spawn(async { pending().await });
245 /// runtime.spawn(pending_wrapper());
246 /// runtime.spawn(async { loop {} });
247 /// runtime.spawn(loop_forever());
248 /// runtime.spawn(async { println!("all done"); pending().await });
249 /// # }
250 /// ```
251 /// but this is not:
252 /// ```compile_fail
253 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
254 /// # use futures::ready;
255 /// runtime.spawn(ready());
256 /// # }
257 /// ```
258 /// and neither is this:
259 /// ```compile_fail
260 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
261 /// # use futures::ready;
262 /// runtime.spawn(async { println!("all done") });
263 /// # }
264 /// ```
265 ///
266 /// # Examples with capturing
267 ///
268 /// The future can capture things. This is important to access other objects created from the
269 /// runtime, either before calling this function:
270 /// ```
271 /// # fn compile_check<'event_loop>(
272 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
273 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
274 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
275 /// # ) {
276 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
277 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
278 /// runtime.spawn(async move { loop {
279 /// watcher1.next().await;
280 /// watcher2.next().await;
281 /// }});
282 /// # }
283 /// ```
284 /// or after:
285 /// ```
286 /// # fn compile_check<'event_loop>(
287 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
288 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
289 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
290 /// # ) {
291 /// # use std::{cell::RefCell, rc::Rc};
292 /// let runtime = Rc::new(RefCell::new(runtime));
293 /// runtime.borrow_mut().spawn({
294 /// let mut runtime = runtime.clone();
295 /// async move {
296 /// let mut runtime = runtime.borrow_mut();
297 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
298 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
299 /// loop {
300 /// watcher1.next().await;
301 /// watcher2.next().await;
302 /// }
303 /// }
304 /// });
305 /// # }
306 /// ```
307 /// or both:
308 /// ```
309 /// # fn compile_check<'event_loop>(
310 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
311 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
312 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
313 /// # ) {
314 /// # use std::{cell::RefCell, rc::Rc};
315 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
316 /// let runtime = Rc::new(RefCell::new(runtime));
317 /// runtime.borrow_mut().spawn({
318 /// let mut runtime = runtime.clone();
319 /// async move {
320 /// let mut runtime = runtime.borrow_mut();
321 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
322 /// loop {
323 /// watcher1.next().await;
324 /// watcher2.next().await;
325 /// }
326 /// }
327 /// });
328 /// # }
329 /// ```
330 ///
331 /// But you cannot capture local variables:
332 /// ```compile_fail
333 /// # fn compile_check<'event_loop>(
334 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
335 /// # ) {
336 /// let mut local: i32 = 971;
337 /// let local = &mut local;
338 /// runtime.spawn(async move { loop {
339 /// println!("have: {}", local);
340 /// }});
341 /// # }
342 /// ```
343 pub fn spawn(&mut self, task: impl Future<Output = Never> + 'event_loop) {
344 self.0.as_mut().spawn(RustApplicationFuture::new(task));
345 }
346
347 pub fn configuration(&self) -> &'event_loop Configuration {
348 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop.
349 unsafe { &*self.0.configuration() }
350 }
351
352 pub fn node(&self) -> Option<&'event_loop Node> {
353 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null.
354 unsafe { self.0.node().as_ref() }
355 }
356
357 pub fn monotonic_now(&self) -> MonotonicInstant {
358 MonotonicInstant(self.0.monotonic_now())
359 }
360
361 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
362 /// part of `self.configuration()`, which will always have this lifetime.
363 ///
364 /// # Panics
365 ///
366 /// Dropping `self` before the returned object is dropped will panic.
367 pub fn make_raw_watcher(&mut self, channel: &'event_loop Channel) -> RawWatcher {
368 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
369 // the usual autocxx heuristics.
370 RawWatcher(unsafe { self.0.as_mut().MakeWatcher(channel) }.within_box())
371 }
372
Brian Silverman90221f82022-08-22 23:46:09 -0700373 /// Provides type-safe async blocking access to messages on a channel. `T` should be a
374 /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static`
375 /// is easiest.
376 ///
377 /// # Panics
378 ///
379 /// Dropping `self` before the returned object is dropped will panic.
380 pub fn make_watcher<T>(&mut self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError>
381 where
382 for<'a> T: FollowWith<'a>,
383 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
384 T: FullyQualifiedName,
385 {
386 let channel = self.get_channel::<T>(channel_name)?;
387 Ok(Watcher(self.make_raw_watcher(channel), PhantomData))
388 }
389
Brian Silverman9809c5f2022-07-23 16:12:23 -0700390 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
391 /// part of `self.configuration()`, which will always have this lifetime.
392 ///
393 /// # Panics
394 ///
395 /// Dropping `self` before the returned object is dropped will panic.
396 pub fn make_raw_sender(&mut self, channel: &'event_loop Channel) -> RawSender {
397 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
398 // the usual autocxx heuristics.
399 RawSender(unsafe { self.0.as_mut().MakeSender(channel) }.within_box())
400 }
401
Brian Silverman90221f82022-08-22 23:46:09 -0700402 /// Allows sending messages on a channel with a type-safe API.
403 ///
404 /// # Panics
405 ///
406 /// Dropping `self` before the returned object is dropped will panic.
407 pub fn make_sender<T>(&mut self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError>
408 where
409 for<'a> T: FollowWith<'a>,
410 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
411 T: FullyQualifiedName,
412 {
413 let channel = self.get_channel::<T>(channel_name)?;
414 Ok(Sender(self.make_raw_sender(channel), PhantomData))
415 }
416
Brian Silverman9809c5f2022-07-23 16:12:23 -0700417 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
418 /// part of `self.configuration()`, which will always have this lifetime.
419 ///
420 /// # Panics
421 ///
422 /// Dropping `self` before the returned object is dropped will panic.
423 pub fn make_raw_fetcher(&mut self, channel: &'event_loop Channel) -> RawFetcher {
424 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
425 // the usual autocxx heuristics.
426 RawFetcher(unsafe { self.0.as_mut().MakeFetcher(channel) }.within_box())
427 }
428
Brian Silverman90221f82022-08-22 23:46:09 -0700429 /// Provides type-safe access to messages on a channel, without the ability to wait for a new
430 /// one. This provides APIs to get the latest message, and to follow along and retrieve each
431 /// message in order.
432 ///
433 /// # Panics
434 ///
435 /// Dropping `self` before the returned object is dropped will panic.
436 pub fn make_fetcher<T>(&mut self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError>
437 where
438 for<'a> T: FollowWith<'a>,
439 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
440 T: FullyQualifiedName,
441 {
442 let channel = self.get_channel::<T>(channel_name)?;
443 Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData))
444 }
445
Brian Silverman9809c5f2022-07-23 16:12:23 -0700446 // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those,
447 // instead of / in addition to mirroring C++ with separate setup and wait?
448
Brian Silverman76f48362022-08-24 21:09:08 -0700449 /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all
450 /// subsequent code will have any realtime scheduling applied. This means it can rely on
451 /// consistent timing, but it can no longer create any EventLoop child objects or do anything
452 /// else non-realtime.
453 pub fn on_run(&mut self) -> OnRun {
454 OnRun(self.0.as_mut().MakeOnRun().within_box())
455 }
456
457 pub fn is_running(&self) -> bool {
458 self.0.is_running()
459 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700460}
461
Brian Silverman9809c5f2022-07-23 16:12:23 -0700462/// Provides async blocking access to messages on a channel. This will return every message on the
463/// channel, in order.
464///
465/// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these.
466///
467/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
468/// for actually interpreting messages. You probably want a [`Watcher`] instead.
469///
470/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
471/// reasons.
472///
473/// # Design
474///
475/// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means
476/// it's different for each `self` lifetime so we can't write a single type alias for it. We could
477/// write an intermediate type with a generic lifetime that implements `Stream` and is returned
478/// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding
479/// another level doesn't help anything.
480///
481/// We also drop the extraneous `cx` argument that isn't used by this implementation anyways.
482///
483/// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's
484/// the same one mentioned here:
485/// https://blog.rust-lang.org/2022/08/05/nll-by-default.html#looking-forward-what-can-we-expect-for-the-borrow-checker-of-the-future
486/// We get around that one by moving the unbounded lifetime from the pointer dereference into the
487/// function with the if statement.
Brian Silverman90221f82022-08-22 23:46:09 -0700488// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
489#[repr(transparent)]
490pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>);
491
Brian Silverman9809c5f2022-07-23 16:12:23 -0700492impl RawWatcher {
493 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
494 /// without skipping any messages.
495 ///
496 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
497 /// will need to call this function again to get the succeeding message.
498 ///
499 /// # Examples
500 ///
501 /// The common use case is immediately awaiting the next message:
502 /// ```
503 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
504 /// println!("received: {:?}", watcher.next().await);
505 /// # }
506 /// ```
507 ///
508 /// You can also await the first message from any of a set of channels:
509 /// ```
510 /// # async fn select(
511 /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher,
512 /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher,
513 /// # ) {
514 /// futures::select! {
515 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
516 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
517 /// }
518 /// # }
519 /// ```
520 ///
521 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
522 /// enforce only having a single of these returned objects at a time. Drop the previous message
523 /// before asking for the next one. That means this will not compile:
524 /// ```compile_fail
525 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
526 /// let first = watcher.next();
527 /// let second = watcher.next();
528 /// first.await;
529 /// # }
530 /// ```
531 /// and nor will this:
532 /// ```compile_fail
533 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
534 /// let first = watcher.next().await;
535 /// watcher.next();
536 /// println!("still have: {:?}", first);
537 /// # }
538 /// ```
539 /// but this is fine:
540 /// ```
541 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
542 /// let first = watcher.next().await;
543 /// println!("have: {:?}", first);
544 /// watcher.next();
545 /// # }
546 /// ```
547 pub fn next(&mut self) -> RawWatcherNext {
548 RawWatcherNext(Some(self))
549 }
550}
551
552/// The type returned from [`RawWatcher::next`], see there for details.
553pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>);
554
555impl<'a> Future for RawWatcherNext<'a> {
556 type Output = Context<'a>;
557 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> {
558 let inner = self
559 .0
560 .take()
561 .expect("May not call poll after it returns Ready");
562 let maybe_context = inner.0.as_mut().PollNext();
563 if maybe_context.is_null() {
564 // We're not returning a reference into it, so we can safely replace the reference to
565 // use again in the future.
566 self.0.replace(inner);
567 Poll::Pending
568 } else {
569 // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will
570 // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`)
571 // because we're dropping `inner` (which is that reference), so it will need to be
572 // borrowed again which cannot happen before the end of `'a`.
573 Poll::Ready(Context(unsafe { &*maybe_context }))
574 }
575 }
576}
577
578impl FusedFuture for RawWatcherNext<'_> {
579 fn is_terminated(&self) -> bool {
580 self.0.is_none()
581 }
582}
583
Brian Silverman90221f82022-08-22 23:46:09 -0700584/// Provides async blocking access to messages on a channel. This will return every message on the
585/// channel, in order.
586///
587/// Use [`EventLoopRuntime::make_watcher`] to create one of these.
588///
589/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
590/// reasons. See [`RawWatcher`]'s documentation for details.
591pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>)
592where
593 for<'a> T: FollowWith<'a>,
594 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
595
596impl<T> Watcher<T>
597where
598 for<'a> T: FollowWith<'a>,
599 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
600{
601 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
602 /// without skipping any messages.
603 ///
604 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
605 /// will need to call this function again to get the succeeding message.
606 ///
607 /// # Examples
608 ///
609 /// The common use case is immediately awaiting the next message:
610 /// ```
611 /// # use pong_rust_fbs::aos::examples::Pong;
612 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
613 /// println!("received: {:?}", watcher.next().await);
614 /// # }
615 /// ```
616 ///
617 /// You can also await the first message from any of a set of channels:
618 /// ```
619 /// # use pong_rust_fbs::aos::examples::Pong;
620 /// # async fn select(
621 /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
622 /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
623 /// # ) {
624 /// futures::select! {
625 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
626 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
627 /// }
628 /// # }
629 /// ```
630 ///
631 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
632 /// enforce only having a single of these returned objects at a time. Drop the previous message
633 /// before asking for the next one. That means this will not compile:
634 /// ```compile_fail
635 /// # use pong_rust_fbs::aos::examples::Pong;
636 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
637 /// let first = watcher.next();
638 /// let second = watcher.next();
639 /// first.await;
640 /// # }
641 /// ```
642 /// and nor will this:
643 /// ```compile_fail
644 /// # use pong_rust_fbs::aos::examples::Pong;
645 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
646 /// let first = watcher.next().await;
647 /// watcher.next();
648 /// println!("still have: {:?}", first);
649 /// # }
650 /// ```
651 /// but this is fine:
652 /// ```
653 /// # use pong_rust_fbs::aos::examples::Pong;
654 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
655 /// let first = watcher.next().await;
656 /// println!("have: {:?}", first);
657 /// watcher.next();
658 /// # }
659 /// ```
660 pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> {
661 WatcherNext(self.0.next(), PhantomData)
662 }
663}
664
665/// The type returned from [`Watcher::next`], see there for details.
666pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>)
667where
668 T: Follow<'watcher> + 'watcher;
669
670impl<'watcher, T> Future for WatcherNext<'watcher, T>
671where
672 T: Follow<'watcher> + 'watcher,
673{
674 type Output = TypedContext<'watcher, T>;
675
676 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
677 Pin::new(&mut self.get_mut().0).poll(cx).map(|context|
678 // SAFETY: The Watcher this was created from verified that the channel is the
679 // right type, and the C++ guarantees that the buffer's type matches.
680 TypedContext(context, PhantomData))
681 }
682}
683
684impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T>
685where
686 T: Follow<'watcher> + 'watcher,
687{
688 fn is_terminated(&self) -> bool {
689 self.0.is_terminated()
690 }
691}
692
693/// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type.
694pub struct TypedContext<'a, T>(
695 // SAFETY: This must have a message, and it must be a valid `T` flatbuffer.
696 Context<'a>,
697 PhantomData<*mut T>,
698)
699where
700 T: Follow<'a> + 'a;
701
702// TODO(Brian): Add the realtime timestamps here.
703impl<'a, T> TypedContext<'a, T>
704where
705 T: Follow<'a> + 'a,
706{
707 pub fn message(&self) -> Option<T::Inner> {
708 self.0.data().map(|data| {
709 // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right
710 // type based on invariants for our type.
711 unsafe { root_unchecked::<T>(data) }
712 })
713 }
714
715 pub fn monotonic_event_time(&self) -> MonotonicInstant {
716 self.0.monotonic_event_time()
717 }
718 pub fn monotonic_remote_time(&self) -> MonotonicInstant {
719 self.0.monotonic_remote_time()
720 }
721 pub fn queue_index(&self) -> u32 {
722 self.0.queue_index()
723 }
724 pub fn remote_queue_index(&self) -> u32 {
725 self.0.remote_queue_index()
726 }
727 pub fn buffer_index(&self) -> i32 {
728 self.0.buffer_index()
729 }
730 pub fn source_boot_uuid(&self) -> &Uuid {
731 self.0.source_boot_uuid()
732 }
733}
734
735impl<'a, T> fmt::Debug for TypedContext<'a, T>
736where
737 T: Follow<'a> + 'a,
738 T::Inner: fmt::Debug,
739{
740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
741 // TODO(Brian): Add the realtime timestamps here.
742 f.debug_struct("TypedContext")
743 .field("monotonic_event_time", &self.monotonic_event_time())
744 .field("monotonic_remote_time", &self.monotonic_remote_time())
745 .field("queue_index", &self.queue_index())
746 .field("remote_queue_index", &self.remote_queue_index())
747 .field("message", &self.message())
748 .field("buffer_index", &self.buffer_index())
749 .field("source_boot_uuid", &self.source_boot_uuid())
750 .finish()
751 }
752}
Brian Silverman9809c5f2022-07-23 16:12:23 -0700753
754/// Provides access to messages on a channel, without the ability to wait for a new one. This
Brian Silverman90221f82022-08-22 23:46:09 -0700755/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700756///
757/// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these.
758///
759/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
760/// for actually interpreting messages. You probably want a [`Fetcher`] instead.
Brian Silverman90221f82022-08-22 23:46:09 -0700761// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
762#[repr(transparent)]
763pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>);
764
Brian Silverman9809c5f2022-07-23 16:12:23 -0700765impl RawFetcher {
766 pub fn fetch_next(&mut self) -> bool {
767 self.0.as_mut().FetchNext()
768 }
769
770 pub fn fetch(&mut self) -> bool {
771 self.0.as_mut().Fetch()
772 }
773
774 pub fn context(&self) -> Context {
775 Context(self.0.context())
776 }
777}
778
Brian Silverman90221f82022-08-22 23:46:09 -0700779/// Provides access to messages on a channel, without the ability to wait for a new one. This
780/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
781///
782/// Use [`EventLoopRuntime::make_fetcher`] to create one of these.
783pub struct Fetcher<T>(
784 // SAFETY: This must produce messages of type `T`.
785 RawFetcher,
786 PhantomData<*mut T>,
787)
788where
789 for<'a> T: FollowWith<'a>,
790 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
791
792impl<T> Fetcher<T>
793where
794 for<'a> T: FollowWith<'a>,
795 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
796{
797 pub fn fetch_next(&mut self) -> bool {
798 self.0.fetch_next()
799 }
800 pub fn fetch(&mut self) -> bool {
801 self.0.fetch()
802 }
803
804 pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> {
805 // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's
806 // type matches.
807 TypedContext(self.0.context(), PhantomData)
808 }
809}
Brian Silverman9809c5f2022-07-23 16:12:23 -0700810
811/// Allows sending messages on a channel.
812///
813/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
814/// for actually creating messages to send. You probably want a [`Sender`] instead.
815///
816/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
Brian Silverman90221f82022-08-22 23:46:09 -0700817// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
818#[repr(transparent)]
819pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>);
820
Brian Silverman9809c5f2022-07-23 16:12:23 -0700821impl RawSender {
822 fn buffer(&mut self) -> &mut [u8] {
823 // SAFETY: This is a valid slice, and `u8` doesn't have any alignment requirements.
824 unsafe { slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) }
825 }
826
827 /// Returns an object which can be used to build a message.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// # use pong_rust_fbs::aos::examples::PongBuilder;
833 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
834 /// # unsafe {
835 /// let mut builder = sender.make_builder();
836 /// let pong = PongBuilder::new(builder.fbb()).finish();
837 /// builder.send(pong);
838 /// # }
839 /// # }
840 /// ```
841 ///
842 /// You can bail out of building a message and build another one:
843 /// ```
844 /// # use pong_rust_fbs::aos::examples::PongBuilder;
845 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
846 /// # unsafe {
847 /// let mut builder1 = sender.make_builder();
848 /// builder1.fbb();
849 /// let mut builder2 = sender.make_builder();
850 /// let pong = PongBuilder::new(builder2.fbb()).finish();
851 /// builder2.send(pong);
852 /// # }
853 /// # }
854 /// ```
855 /// but you cannot build two messages at the same time with a single builder:
856 /// ```compile_fail
857 /// # use pong_rust_fbs::aos::examples::PongBuilder;
858 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
859 /// # unsafe {
860 /// let mut builder1 = sender.make_builder();
861 /// let mut builder2 = sender.make_builder();
862 /// PongBuilder::new(builder2.fbb()).finish();
863 /// PongBuilder::new(builder1.fbb()).finish();
864 /// # }
865 /// # }
866 /// ```
867 pub fn make_builder(&mut self) -> RawBuilder {
868 // TODO(Brian): Actually use the provided buffer instead of just using its
869 // size to allocate a separate one.
870 //
871 // See https://github.com/google/flatbuffers/issues/7385.
872 let fbb = flatbuffers::FlatBufferBuilder::with_capacity(self.buffer().len());
873 RawBuilder {
874 raw_sender: self,
875 fbb,
876 }
877 }
878}
879
Brian Silverman9809c5f2022-07-23 16:12:23 -0700880/// Used for building a message. See [`RawSender::make_builder`] for details.
881pub struct RawBuilder<'sender> {
882 raw_sender: &'sender mut RawSender,
883 fbb: flatbuffers::FlatBufferBuilder<'sender>,
884}
885
886impl<'sender> RawBuilder<'sender> {
887 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
888 &mut self.fbb
889 }
890
891 /// # Safety
892 ///
893 /// `T` must match the type of the channel of the sender this builder was created from.
894 pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> {
895 self.fbb.finish_minimal(root);
896 let data = self.fbb.finished_data();
897
898 use ffi::aos::RawSender_Error as FfiError;
899 // SAFETY: This is a valid buffer we're passing.
900 match unsafe {
901 self.raw_sender
902 .0
903 .as_mut()
904 .CopyAndSend(data.as_ptr(), data.len())
905 } {
906 FfiError::kOk => Ok(()),
907 FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast),
908 FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone),
909 }
910 }
911}
912
Brian Silverman90221f82022-08-22 23:46:09 -0700913/// Allows sending messages on a channel with a type-safe API.
914///
915/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
916pub struct Sender<T>(
917 // SAFETY: This must accept messages of type `T`.
918 RawSender,
919 PhantomData<*mut T>,
920)
921where
922 for<'a> T: FollowWith<'a>,
923 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
924
925impl<T> Sender<T>
926where
927 for<'a> T: FollowWith<'a>,
928 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
929{
930 /// Returns an object which can be used to build a message.
931 ///
932 /// # Examples
933 ///
934 /// ```
935 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
936 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
937 /// let mut builder = sender.make_builder();
938 /// let pong = PongBuilder::new(builder.fbb()).finish();
939 /// builder.send(pong);
940 /// # }
941 /// ```
942 ///
943 /// You can bail out of building a message and build another one:
944 /// ```
945 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
946 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
947 /// let mut builder1 = sender.make_builder();
948 /// builder1.fbb();
949 /// let mut builder2 = sender.make_builder();
950 /// let pong = PongBuilder::new(builder2.fbb()).finish();
951 /// builder2.send(pong);
952 /// # }
953 /// ```
954 /// but you cannot build two messages at the same time with a single builder:
955 /// ```compile_fail
956 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
957 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
958 /// let mut builder1 = sender.make_builder();
959 /// let mut builder2 = sender.make_builder();
960 /// PongBuilder::new(builder2.fbb()).finish();
961 /// PongBuilder::new(builder1.fbb()).finish();
962 /// # }
963 /// ```
964 pub fn make_builder(&mut self) -> Builder<T> {
965 Builder(self.0.make_builder(), PhantomData)
966 }
967}
968
969/// Used for building a message. See [`Sender::make_builder`] for details.
970pub struct Builder<'sender, T>(
971 // SAFETY: This must accept messages of type `T`.
972 RawBuilder<'sender>,
973 PhantomData<*mut T>,
974)
975where
976 for<'a> T: FollowWith<'a>,
977 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
978
979impl<'sender, T> Builder<'sender, T>
980where
981 for<'a> T: FollowWith<'a>,
982 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
983{
984 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
985 self.0.fbb()
986 }
987
988 pub fn send<'a>(
989 self,
990 root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>,
991 ) -> Result<(), SendError> {
992 // SAFETY: We guarantee this is the right type based on invariants for our type.
993 unsafe { self.0.send(root) }
994 }
995}
996
997#[derive(Clone, Copy, Eq, PartialEq, Debug, Error)]
998pub enum SendError {
999 #[error("messages have been sent too fast on this channel")]
1000 MessagesSentTooFast,
1001 #[error("invalid redzone data, shared memory corruption detected")]
1002 InvalidRedzone,
1003}
1004
Brian Silverman9809c5f2022-07-23 16:12:23 -07001005#[repr(transparent)]
1006#[derive(Clone, Copy)]
1007pub struct Context<'context>(&'context ffi::aos::Context);
1008
1009impl fmt::Debug for Context<'_> {
1010 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1011 // TODO(Brian): Add the realtime timestamps here.
1012 f.debug_struct("Context")
1013 .field("monotonic_event_time", &self.monotonic_event_time())
1014 .field("monotonic_remote_time", &self.monotonic_remote_time())
1015 .field("queue_index", &self.queue_index())
1016 .field("remote_queue_index", &self.remote_queue_index())
1017 .field("size", &self.data().map(|data| data.len()))
1018 .field("buffer_index", &self.buffer_index())
1019 .field("source_boot_uuid", &self.source_boot_uuid())
1020 .finish()
1021 }
1022}
1023
1024// TODO(Brian): Add the realtime timestamps here.
1025impl<'context> Context<'context> {
1026 pub fn monotonic_event_time(self) -> MonotonicInstant {
1027 MonotonicInstant(self.0.monotonic_event_time)
1028 }
1029
1030 pub fn monotonic_remote_time(self) -> MonotonicInstant {
1031 MonotonicInstant(self.0.monotonic_remote_time)
1032 }
1033
1034 pub fn queue_index(self) -> u32 {
1035 self.0.queue_index
1036 }
1037 pub fn remote_queue_index(self) -> u32 {
1038 self.0.remote_queue_index
1039 }
1040
1041 pub fn data(self) -> Option<&'context [u8]> {
1042 if self.0.data.is_null() {
1043 None
1044 } else {
1045 // SAFETY:
1046 // * `u8` has no alignment requirements
1047 // * It must be a single initialized flatbuffers buffer
1048 // * The borrow in `self.0` guarantees it won't be modified for `'context`
1049 Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) })
1050 }
1051 }
1052
1053 pub fn buffer_index(self) -> i32 {
1054 self.0.buffer_index
1055 }
1056
1057 pub fn source_boot_uuid(self) -> &'context Uuid {
1058 // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be
1059 // valid until something changes the context, which is `'context`.
1060 Uuid::from_bytes_ref(&self.0.source_boot_uuid)
1061 }
1062}
1063
Brian Silverman76f48362022-08-24 21:09:08 -07001064/// The type returned from [`EventLoopRuntime::on_run`], see there for details.
1065// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1066#[repr(transparent)]
1067pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>);
1068
1069impl Future for OnRun {
1070 type Output = ();
1071
1072 fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
1073 if self.0.is_running() {
1074 Poll::Ready(())
1075 } else {
1076 Poll::Pending
1077 }
1078 }
1079}
1080
Brian Silverman9809c5f2022-07-23 16:12:23 -07001081/// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This
1082/// is intended to have the same API as [`std::time::Instant`], any missing
1083/// functionality can be added if useful.
1084///
1085/// TODO(Brian): Do RealtimeInstant too. Use a macro? Integer as a generic
1086/// parameter to distinguish them? Or just copy/paste?
1087#[repr(transparent)]
1088#[derive(Clone, Copy, Eq, PartialEq)]
1089pub struct MonotonicInstant(i64);
1090
1091impl MonotonicInstant {
1092 /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value.
1093 pub const MIN_TIME: Self = Self(i64::MIN);
1094
1095 pub fn is_min_time(self) -> bool {
1096 self == Self::MIN_TIME
1097 }
1098
1099 pub fn duration_since_epoch(self) -> Option<Duration> {
1100 if self.is_min_time() {
1101 None
1102 } else {
1103 Some(Duration::from_nanos(self.0.try_into().expect(
1104 "monotonic_clock::time_point should always be after the epoch",
1105 )))
1106 }
1107 }
1108}
1109
1110impl fmt::Debug for MonotonicInstant {
1111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1112 self.duration_since_epoch().fmt(f)
1113 }
1114}
1115
1116mod panic_waker {
1117 use std::task::{RawWaker, RawWakerVTable, Waker};
1118
1119 unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker {
1120 raw_panic_waker()
1121 }
1122
1123 unsafe fn noop(_data: *const ()) {}
1124
1125 unsafe fn wake_panic(_data: *const ()) {
1126 panic!("Nothing should wake EventLoopRuntime's waker");
1127 }
1128
1129 const PANIC_WAKER_VTABLE: RawWakerVTable =
1130 RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop);
1131
1132 fn raw_panic_waker() -> RawWaker {
1133 RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE)
1134 }
1135
1136 pub fn panic_waker() -> Waker {
1137 // SAFETY: The implementations of the RawWakerVTable functions do what is required of them.
1138 unsafe { Waker::from_raw(raw_panic_waker()) }
1139 }
1140}
1141
1142use panic_waker::panic_waker;