blob: 023cfb6b58247b88ed007ff9334cb945c69216e1 [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
Ryan Yin683a8672022-11-09 20:44:20 -0800373 pub fn realtime_now(&self) -> RealtimeInstant {
374 RealtimeInstant(self.0.realtime_now())
375 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700376 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
377 /// part of `self.configuration()`, which will always have this lifetime.
378 ///
379 /// # Panics
380 ///
381 /// Dropping `self` before the returned object is dropped will panic.
382 pub fn make_raw_watcher(&mut self, channel: &'event_loop Channel) -> RawWatcher {
383 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
384 // the usual autocxx heuristics.
385 RawWatcher(unsafe { self.0.as_mut().MakeWatcher(channel) }.within_box())
386 }
387
Brian Silverman90221f82022-08-22 23:46:09 -0700388 /// Provides type-safe async blocking access to messages on a channel. `T` should be a
389 /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static`
390 /// is easiest.
391 ///
392 /// # Panics
393 ///
394 /// Dropping `self` before the returned object is dropped will panic.
395 pub fn make_watcher<T>(&mut self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError>
396 where
397 for<'a> T: FollowWith<'a>,
398 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
399 T: FullyQualifiedName,
400 {
401 let channel = self.get_channel::<T>(channel_name)?;
402 Ok(Watcher(self.make_raw_watcher(channel), PhantomData))
403 }
404
Brian Silverman9809c5f2022-07-23 16:12:23 -0700405 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
406 /// part of `self.configuration()`, which will always have this lifetime.
407 ///
408 /// # Panics
409 ///
410 /// Dropping `self` before the returned object is dropped will panic.
411 pub fn make_raw_sender(&mut self, channel: &'event_loop Channel) -> RawSender {
412 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
413 // the usual autocxx heuristics.
414 RawSender(unsafe { self.0.as_mut().MakeSender(channel) }.within_box())
415 }
416
Brian Silverman90221f82022-08-22 23:46:09 -0700417 /// Allows sending messages on a channel with a type-safe API.
418 ///
419 /// # Panics
420 ///
421 /// Dropping `self` before the returned object is dropped will panic.
422 pub fn make_sender<T>(&mut self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError>
423 where
424 for<'a> T: FollowWith<'a>,
425 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
426 T: FullyQualifiedName,
427 {
428 let channel = self.get_channel::<T>(channel_name)?;
429 Ok(Sender(self.make_raw_sender(channel), PhantomData))
430 }
431
Brian Silverman9809c5f2022-07-23 16:12:23 -0700432 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
433 /// part of `self.configuration()`, which will always have this lifetime.
434 ///
435 /// # Panics
436 ///
437 /// Dropping `self` before the returned object is dropped will panic.
438 pub fn make_raw_fetcher(&mut self, channel: &'event_loop Channel) -> RawFetcher {
439 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
440 // the usual autocxx heuristics.
441 RawFetcher(unsafe { self.0.as_mut().MakeFetcher(channel) }.within_box())
442 }
443
Brian Silverman90221f82022-08-22 23:46:09 -0700444 /// Provides type-safe access to messages on a channel, without the ability to wait for a new
445 /// one. This provides APIs to get the latest message, and to follow along and retrieve each
446 /// message in order.
447 ///
448 /// # Panics
449 ///
450 /// Dropping `self` before the returned object is dropped will panic.
451 pub fn make_fetcher<T>(&mut self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError>
452 where
453 for<'a> T: FollowWith<'a>,
454 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
455 T: FullyQualifiedName,
456 {
457 let channel = self.get_channel::<T>(channel_name)?;
458 Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData))
459 }
460
Brian Silverman9809c5f2022-07-23 16:12:23 -0700461 // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those,
462 // instead of / in addition to mirroring C++ with separate setup and wait?
463
Brian Silverman76f48362022-08-24 21:09:08 -0700464 /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all
465 /// subsequent code will have any realtime scheduling applied. This means it can rely on
466 /// consistent timing, but it can no longer create any EventLoop child objects or do anything
467 /// else non-realtime.
468 pub fn on_run(&mut self) -> OnRun {
469 OnRun(self.0.as_mut().MakeOnRun().within_box())
470 }
471
472 pub fn is_running(&self) -> bool {
473 self.0.is_running()
474 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700475}
476
Brian Silverman9809c5f2022-07-23 16:12:23 -0700477/// Provides async blocking access to messages on a channel. This will return every message on the
478/// channel, in order.
479///
480/// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these.
481///
482/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
483/// for actually interpreting messages. You probably want a [`Watcher`] instead.
484///
485/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
486/// reasons.
487///
488/// # Design
489///
490/// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means
491/// it's different for each `self` lifetime so we can't write a single type alias for it. We could
492/// write an intermediate type with a generic lifetime that implements `Stream` and is returned
493/// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding
494/// another level doesn't help anything.
495///
496/// We also drop the extraneous `cx` argument that isn't used by this implementation anyways.
497///
498/// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's
499/// the same one mentioned here:
500/// 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
501/// We get around that one by moving the unbounded lifetime from the pointer dereference into the
502/// function with the if statement.
Brian Silverman90221f82022-08-22 23:46:09 -0700503// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
504#[repr(transparent)]
505pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>);
506
Brian Silverman9809c5f2022-07-23 16:12:23 -0700507impl RawWatcher {
508 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
509 /// without skipping any messages.
510 ///
511 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
512 /// will need to call this function again to get the succeeding message.
513 ///
514 /// # Examples
515 ///
516 /// The common use case is immediately awaiting the next message:
517 /// ```
518 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
519 /// println!("received: {:?}", watcher.next().await);
520 /// # }
521 /// ```
522 ///
523 /// You can also await the first message from any of a set of channels:
524 /// ```
525 /// # async fn select(
526 /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher,
527 /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher,
528 /// # ) {
529 /// futures::select! {
530 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
531 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
532 /// }
533 /// # }
534 /// ```
535 ///
536 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
537 /// enforce only having a single of these returned objects at a time. Drop the previous message
538 /// before asking for the next one. That means this will not compile:
539 /// ```compile_fail
540 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
541 /// let first = watcher.next();
542 /// let second = watcher.next();
543 /// first.await;
544 /// # }
545 /// ```
546 /// and nor will this:
547 /// ```compile_fail
548 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
549 /// let first = watcher.next().await;
550 /// watcher.next();
551 /// println!("still have: {:?}", first);
552 /// # }
553 /// ```
554 /// but this is fine:
555 /// ```
556 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
557 /// let first = watcher.next().await;
558 /// println!("have: {:?}", first);
559 /// watcher.next();
560 /// # }
561 /// ```
562 pub fn next(&mut self) -> RawWatcherNext {
563 RawWatcherNext(Some(self))
564 }
565}
566
567/// The type returned from [`RawWatcher::next`], see there for details.
568pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>);
569
570impl<'a> Future for RawWatcherNext<'a> {
571 type Output = Context<'a>;
572 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> {
573 let inner = self
574 .0
575 .take()
576 .expect("May not call poll after it returns Ready");
577 let maybe_context = inner.0.as_mut().PollNext();
578 if maybe_context.is_null() {
579 // We're not returning a reference into it, so we can safely replace the reference to
580 // use again in the future.
581 self.0.replace(inner);
582 Poll::Pending
583 } else {
584 // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will
585 // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`)
586 // because we're dropping `inner` (which is that reference), so it will need to be
587 // borrowed again which cannot happen before the end of `'a`.
588 Poll::Ready(Context(unsafe { &*maybe_context }))
589 }
590 }
591}
592
593impl FusedFuture for RawWatcherNext<'_> {
594 fn is_terminated(&self) -> bool {
595 self.0.is_none()
596 }
597}
598
Brian Silverman90221f82022-08-22 23:46:09 -0700599/// Provides async blocking access to messages on a channel. This will return every message on the
600/// channel, in order.
601///
602/// Use [`EventLoopRuntime::make_watcher`] to create one of these.
603///
604/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
605/// reasons. See [`RawWatcher`]'s documentation for details.
606pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>)
607where
608 for<'a> T: FollowWith<'a>,
609 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
610
611impl<T> Watcher<T>
612where
613 for<'a> T: FollowWith<'a>,
614 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
615{
616 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
617 /// without skipping any messages.
618 ///
619 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
620 /// will need to call this function again to get the succeeding message.
621 ///
622 /// # Examples
623 ///
624 /// The common use case is immediately awaiting the next message:
625 /// ```
626 /// # use pong_rust_fbs::aos::examples::Pong;
627 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
628 /// println!("received: {:?}", watcher.next().await);
629 /// # }
630 /// ```
631 ///
632 /// You can also await the first message from any of a set of channels:
633 /// ```
634 /// # use pong_rust_fbs::aos::examples::Pong;
635 /// # async fn select(
636 /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
637 /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
638 /// # ) {
639 /// futures::select! {
640 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
641 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
642 /// }
643 /// # }
644 /// ```
645 ///
646 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
647 /// enforce only having a single of these returned objects at a time. Drop the previous message
648 /// before asking for the next one. That means this will not compile:
649 /// ```compile_fail
650 /// # use pong_rust_fbs::aos::examples::Pong;
651 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
652 /// let first = watcher.next();
653 /// let second = watcher.next();
654 /// first.await;
655 /// # }
656 /// ```
657 /// and nor will this:
658 /// ```compile_fail
659 /// # use pong_rust_fbs::aos::examples::Pong;
660 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
661 /// let first = watcher.next().await;
662 /// watcher.next();
663 /// println!("still have: {:?}", first);
664 /// # }
665 /// ```
666 /// but this is fine:
667 /// ```
668 /// # use pong_rust_fbs::aos::examples::Pong;
669 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
670 /// let first = watcher.next().await;
671 /// println!("have: {:?}", first);
672 /// watcher.next();
673 /// # }
674 /// ```
675 pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> {
676 WatcherNext(self.0.next(), PhantomData)
677 }
678}
679
680/// The type returned from [`Watcher::next`], see there for details.
681pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>)
682where
683 T: Follow<'watcher> + 'watcher;
684
685impl<'watcher, T> Future for WatcherNext<'watcher, T>
686where
687 T: Follow<'watcher> + 'watcher,
688{
689 type Output = TypedContext<'watcher, T>;
690
691 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
692 Pin::new(&mut self.get_mut().0).poll(cx).map(|context|
693 // SAFETY: The Watcher this was created from verified that the channel is the
694 // right type, and the C++ guarantees that the buffer's type matches.
695 TypedContext(context, PhantomData))
696 }
697}
698
699impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T>
700where
701 T: Follow<'watcher> + 'watcher,
702{
703 fn is_terminated(&self) -> bool {
704 self.0.is_terminated()
705 }
706}
707
708/// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type.
709pub struct TypedContext<'a, T>(
710 // SAFETY: This must have a message, and it must be a valid `T` flatbuffer.
711 Context<'a>,
712 PhantomData<*mut T>,
713)
714where
715 T: Follow<'a> + 'a;
716
Brian Silverman90221f82022-08-22 23:46:09 -0700717impl<'a, T> TypedContext<'a, T>
718where
719 T: Follow<'a> + 'a,
720{
721 pub fn message(&self) -> Option<T::Inner> {
722 self.0.data().map(|data| {
723 // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right
724 // type based on invariants for our type.
725 unsafe { root_unchecked::<T>(data) }
726 })
727 }
728
729 pub fn monotonic_event_time(&self) -> MonotonicInstant {
730 self.0.monotonic_event_time()
731 }
732 pub fn monotonic_remote_time(&self) -> MonotonicInstant {
733 self.0.monotonic_remote_time()
734 }
Ryan Yin683a8672022-11-09 20:44:20 -0800735 pub fn realtime_event_time(&self) -> RealtimeInstant {
736 self.0.realtime_event_time()
737 }
738 pub fn realtime_remote_time(&self) -> RealtimeInstant {
739 self.0.realtime_remote_time()
740 }
Brian Silverman90221f82022-08-22 23:46:09 -0700741 pub fn queue_index(&self) -> u32 {
742 self.0.queue_index()
743 }
744 pub fn remote_queue_index(&self) -> u32 {
745 self.0.remote_queue_index()
746 }
747 pub fn buffer_index(&self) -> i32 {
748 self.0.buffer_index()
749 }
750 pub fn source_boot_uuid(&self) -> &Uuid {
751 self.0.source_boot_uuid()
752 }
753}
754
755impl<'a, T> fmt::Debug for TypedContext<'a, T>
756where
757 T: Follow<'a> + 'a,
758 T::Inner: fmt::Debug,
759{
760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman90221f82022-08-22 23:46:09 -0700761 f.debug_struct("TypedContext")
762 .field("monotonic_event_time", &self.monotonic_event_time())
763 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -0800764 .field("realtime_event_time", &self.realtime_event_time())
765 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman90221f82022-08-22 23:46:09 -0700766 .field("queue_index", &self.queue_index())
767 .field("remote_queue_index", &self.remote_queue_index())
768 .field("message", &self.message())
769 .field("buffer_index", &self.buffer_index())
770 .field("source_boot_uuid", &self.source_boot_uuid())
771 .finish()
772 }
773}
Brian Silverman9809c5f2022-07-23 16:12:23 -0700774
775/// Provides access to messages on a channel, without the ability to wait for a new one. This
Brian Silverman90221f82022-08-22 23:46:09 -0700776/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700777///
778/// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these.
779///
780/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
781/// for actually interpreting messages. You probably want a [`Fetcher`] instead.
Brian Silverman90221f82022-08-22 23:46:09 -0700782// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
783#[repr(transparent)]
784pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>);
785
Brian Silverman9809c5f2022-07-23 16:12:23 -0700786impl RawFetcher {
787 pub fn fetch_next(&mut self) -> bool {
788 self.0.as_mut().FetchNext()
789 }
790
791 pub fn fetch(&mut self) -> bool {
792 self.0.as_mut().Fetch()
793 }
794
795 pub fn context(&self) -> Context {
796 Context(self.0.context())
797 }
798}
799
Brian Silverman90221f82022-08-22 23:46:09 -0700800/// Provides access to messages on a channel, without the ability to wait for a new one. This
801/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
802///
803/// Use [`EventLoopRuntime::make_fetcher`] to create one of these.
804pub struct Fetcher<T>(
805 // SAFETY: This must produce messages of type `T`.
806 RawFetcher,
807 PhantomData<*mut T>,
808)
809where
810 for<'a> T: FollowWith<'a>,
811 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
812
813impl<T> Fetcher<T>
814where
815 for<'a> T: FollowWith<'a>,
816 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
817{
818 pub fn fetch_next(&mut self) -> bool {
819 self.0.fetch_next()
820 }
821 pub fn fetch(&mut self) -> bool {
822 self.0.fetch()
823 }
824
825 pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> {
826 // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's
827 // type matches.
828 TypedContext(self.0.context(), PhantomData)
829 }
830}
Brian Silverman9809c5f2022-07-23 16:12:23 -0700831
832/// Allows sending messages on a channel.
833///
834/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
835/// for actually creating messages to send. You probably want a [`Sender`] instead.
836///
837/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
Brian Silverman90221f82022-08-22 23:46:09 -0700838// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
839#[repr(transparent)]
840pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>);
841
Brian Silverman9809c5f2022-07-23 16:12:23 -0700842impl RawSender {
843 fn buffer(&mut self) -> &mut [u8] {
844 // SAFETY: This is a valid slice, and `u8` doesn't have any alignment requirements.
845 unsafe { slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) }
846 }
847
848 /// Returns an object which can be used to build a message.
849 ///
850 /// # Examples
851 ///
852 /// ```
853 /// # use pong_rust_fbs::aos::examples::PongBuilder;
854 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
855 /// # unsafe {
856 /// let mut builder = sender.make_builder();
857 /// let pong = PongBuilder::new(builder.fbb()).finish();
858 /// builder.send(pong);
859 /// # }
860 /// # }
861 /// ```
862 ///
863 /// You can bail out of building a message and build another one:
864 /// ```
865 /// # use pong_rust_fbs::aos::examples::PongBuilder;
866 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
867 /// # unsafe {
868 /// let mut builder1 = sender.make_builder();
869 /// builder1.fbb();
870 /// let mut builder2 = sender.make_builder();
871 /// let pong = PongBuilder::new(builder2.fbb()).finish();
872 /// builder2.send(pong);
873 /// # }
874 /// # }
875 /// ```
876 /// but you cannot build two messages at the same time with a single builder:
877 /// ```compile_fail
878 /// # use pong_rust_fbs::aos::examples::PongBuilder;
879 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
880 /// # unsafe {
881 /// let mut builder1 = sender.make_builder();
882 /// let mut builder2 = sender.make_builder();
883 /// PongBuilder::new(builder2.fbb()).finish();
884 /// PongBuilder::new(builder1.fbb()).finish();
885 /// # }
886 /// # }
887 /// ```
888 pub fn make_builder(&mut self) -> RawBuilder {
889 // TODO(Brian): Actually use the provided buffer instead of just using its
890 // size to allocate a separate one.
891 //
892 // See https://github.com/google/flatbuffers/issues/7385.
893 let fbb = flatbuffers::FlatBufferBuilder::with_capacity(self.buffer().len());
894 RawBuilder {
895 raw_sender: self,
896 fbb,
897 }
898 }
899}
900
Brian Silverman9809c5f2022-07-23 16:12:23 -0700901/// Used for building a message. See [`RawSender::make_builder`] for details.
902pub struct RawBuilder<'sender> {
903 raw_sender: &'sender mut RawSender,
904 fbb: flatbuffers::FlatBufferBuilder<'sender>,
905}
906
907impl<'sender> RawBuilder<'sender> {
908 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
909 &mut self.fbb
910 }
911
912 /// # Safety
913 ///
914 /// `T` must match the type of the channel of the sender this builder was created from.
915 pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> {
916 self.fbb.finish_minimal(root);
917 let data = self.fbb.finished_data();
918
919 use ffi::aos::RawSender_Error as FfiError;
920 // SAFETY: This is a valid buffer we're passing.
921 match unsafe {
922 self.raw_sender
923 .0
924 .as_mut()
925 .CopyAndSend(data.as_ptr(), data.len())
926 } {
927 FfiError::kOk => Ok(()),
928 FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast),
929 FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone),
930 }
931 }
932}
933
Brian Silverman90221f82022-08-22 23:46:09 -0700934/// Allows sending messages on a channel with a type-safe API.
935///
936/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
937pub struct Sender<T>(
938 // SAFETY: This must accept messages of type `T`.
939 RawSender,
940 PhantomData<*mut T>,
941)
942where
943 for<'a> T: FollowWith<'a>,
944 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
945
946impl<T> Sender<T>
947where
948 for<'a> T: FollowWith<'a>,
949 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
950{
951 /// Returns an object which can be used to build a message.
952 ///
953 /// # Examples
954 ///
955 /// ```
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 builder = sender.make_builder();
959 /// let pong = PongBuilder::new(builder.fbb()).finish();
960 /// builder.send(pong);
961 /// # }
962 /// ```
963 ///
964 /// You can bail out of building a message and build another one:
965 /// ```
966 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
967 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
968 /// let mut builder1 = sender.make_builder();
969 /// builder1.fbb();
970 /// let mut builder2 = sender.make_builder();
971 /// let pong = PongBuilder::new(builder2.fbb()).finish();
972 /// builder2.send(pong);
973 /// # }
974 /// ```
975 /// but you cannot build two messages at the same time with a single builder:
976 /// ```compile_fail
977 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
978 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
979 /// let mut builder1 = sender.make_builder();
980 /// let mut builder2 = sender.make_builder();
981 /// PongBuilder::new(builder2.fbb()).finish();
982 /// PongBuilder::new(builder1.fbb()).finish();
983 /// # }
984 /// ```
985 pub fn make_builder(&mut self) -> Builder<T> {
986 Builder(self.0.make_builder(), PhantomData)
987 }
988}
989
990/// Used for building a message. See [`Sender::make_builder`] for details.
991pub struct Builder<'sender, T>(
992 // SAFETY: This must accept messages of type `T`.
993 RawBuilder<'sender>,
994 PhantomData<*mut T>,
995)
996where
997 for<'a> T: FollowWith<'a>,
998 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
999
1000impl<'sender, T> Builder<'sender, T>
1001where
1002 for<'a> T: FollowWith<'a>,
1003 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1004{
1005 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
1006 self.0.fbb()
1007 }
1008
1009 pub fn send<'a>(
1010 self,
1011 root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>,
1012 ) -> Result<(), SendError> {
1013 // SAFETY: We guarantee this is the right type based on invariants for our type.
1014 unsafe { self.0.send(root) }
1015 }
1016}
1017
1018#[derive(Clone, Copy, Eq, PartialEq, Debug, Error)]
1019pub enum SendError {
1020 #[error("messages have been sent too fast on this channel")]
1021 MessagesSentTooFast,
1022 #[error("invalid redzone data, shared memory corruption detected")]
1023 InvalidRedzone,
1024}
1025
Brian Silverman9809c5f2022-07-23 16:12:23 -07001026#[repr(transparent)]
1027#[derive(Clone, Copy)]
1028pub struct Context<'context>(&'context ffi::aos::Context);
1029
1030impl fmt::Debug for Context<'_> {
1031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001032 f.debug_struct("Context")
1033 .field("monotonic_event_time", &self.monotonic_event_time())
1034 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -08001035 .field("realtime_event_time", &self.realtime_event_time())
1036 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman9809c5f2022-07-23 16:12:23 -07001037 .field("queue_index", &self.queue_index())
1038 .field("remote_queue_index", &self.remote_queue_index())
1039 .field("size", &self.data().map(|data| data.len()))
1040 .field("buffer_index", &self.buffer_index())
1041 .field("source_boot_uuid", &self.source_boot_uuid())
1042 .finish()
1043 }
1044}
1045
Brian Silverman9809c5f2022-07-23 16:12:23 -07001046impl<'context> Context<'context> {
1047 pub fn monotonic_event_time(self) -> MonotonicInstant {
1048 MonotonicInstant(self.0.monotonic_event_time)
1049 }
1050
1051 pub fn monotonic_remote_time(self) -> MonotonicInstant {
1052 MonotonicInstant(self.0.monotonic_remote_time)
1053 }
1054
Ryan Yin683a8672022-11-09 20:44:20 -08001055 pub fn realtime_event_time(self) -> RealtimeInstant {
1056 RealtimeInstant(self.0.realtime_event_time)
1057 }
1058
1059 pub fn realtime_remote_time(self) -> RealtimeInstant {
1060 RealtimeInstant(self.0.realtime_remote_time)
1061 }
1062
Brian Silverman9809c5f2022-07-23 16:12:23 -07001063 pub fn queue_index(self) -> u32 {
1064 self.0.queue_index
1065 }
1066 pub fn remote_queue_index(self) -> u32 {
1067 self.0.remote_queue_index
1068 }
1069
1070 pub fn data(self) -> Option<&'context [u8]> {
1071 if self.0.data.is_null() {
1072 None
1073 } else {
1074 // SAFETY:
1075 // * `u8` has no alignment requirements
1076 // * It must be a single initialized flatbuffers buffer
1077 // * The borrow in `self.0` guarantees it won't be modified for `'context`
1078 Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) })
1079 }
1080 }
1081
1082 pub fn buffer_index(self) -> i32 {
1083 self.0.buffer_index
1084 }
1085
1086 pub fn source_boot_uuid(self) -> &'context Uuid {
1087 // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be
1088 // valid until something changes the context, which is `'context`.
1089 Uuid::from_bytes_ref(&self.0.source_boot_uuid)
1090 }
1091}
1092
Brian Silverman76f48362022-08-24 21:09:08 -07001093/// The type returned from [`EventLoopRuntime::on_run`], see there for details.
1094// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1095#[repr(transparent)]
1096pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>);
1097
1098impl Future for OnRun {
1099 type Output = ();
1100
1101 fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
1102 if self.0.is_running() {
1103 Poll::Ready(())
1104 } else {
1105 Poll::Pending
1106 }
1107 }
1108}
1109
Brian Silverman9809c5f2022-07-23 16:12:23 -07001110/// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This
1111/// is intended to have the same API as [`std::time::Instant`], any missing
1112/// functionality can be added if useful.
Brian Silverman9809c5f2022-07-23 16:12:23 -07001113#[repr(transparent)]
1114#[derive(Clone, Copy, Eq, PartialEq)]
1115pub struct MonotonicInstant(i64);
1116
1117impl MonotonicInstant {
1118 /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value.
1119 pub const MIN_TIME: Self = Self(i64::MIN);
1120
1121 pub fn is_min_time(self) -> bool {
1122 self == Self::MIN_TIME
1123 }
1124
1125 pub fn duration_since_epoch(self) -> Option<Duration> {
1126 if self.is_min_time() {
1127 None
1128 } else {
1129 Some(Duration::from_nanos(self.0.try_into().expect(
1130 "monotonic_clock::time_point should always be after the epoch",
1131 )))
1132 }
1133 }
1134}
1135
1136impl fmt::Debug for MonotonicInstant {
1137 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1138 self.duration_since_epoch().fmt(f)
1139 }
1140}
1141
Ryan Yin683a8672022-11-09 20:44:20 -08001142#[repr(transparent)]
1143#[derive(Clone, Copy, Eq, PartialEq)]
1144pub struct RealtimeInstant(i64);
1145
1146impl RealtimeInstant {
1147 pub const MIN_TIME: Self = Self(i64::MIN);
1148
1149 pub fn is_min_time(self) -> bool {
1150 self == Self::MIN_TIME
1151 }
1152
1153 pub fn duration_since_epoch(self) -> Option<Duration> {
1154 if self.is_min_time() {
1155 None
1156 } else {
1157 Some(Duration::from_nanos(self.0.try_into().expect(
1158 "monotonic_clock::time_point should always be after the epoch",
1159 )))
1160 }
1161 }
1162}
1163
1164impl fmt::Debug for RealtimeInstant {
1165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1166 self.duration_since_epoch().fmt(f)
1167 }
1168}
1169
Brian Silverman9809c5f2022-07-23 16:12:23 -07001170mod panic_waker {
1171 use std::task::{RawWaker, RawWakerVTable, Waker};
1172
1173 unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker {
1174 raw_panic_waker()
1175 }
1176
1177 unsafe fn noop(_data: *const ()) {}
1178
1179 unsafe fn wake_panic(_data: *const ()) {
1180 panic!("Nothing should wake EventLoopRuntime's waker");
1181 }
1182
1183 const PANIC_WAKER_VTABLE: RawWakerVTable =
1184 RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop);
1185
1186 fn raw_panic_waker() -> RawWaker {
1187 RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE)
1188 }
1189
1190 pub fn panic_waker() -> Waker {
1191 // SAFETY: The implementations of the RawWakerVTable functions do what is required of them.
1192 unsafe { Waker::from_raw(raw_panic_waker()) }
1193 }
1194}
1195
1196use panic_waker::panic_waker;