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