blob: 76c1e2e00cf8bd209e194a2e68e82fa305ac4107 [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.
Brian Silverman2ee175e2023-07-11 16:32:08 -070037//! * Rust's lifetimes are only flexible enough to track everything with a single big lifetime.
38//! All the callbacks can store references to things tied to the event loop's lifetime, but no
39//! other lifetimes.
Brian Silverman9809c5f2022-07-23 16:12:23 -070040//! * We can't use [`futures::stream::Stream`] and all of its nice [`futures::stream::StreamExt`]
41//! helpers for watchers because we need lifetime-generic `Item` types. Effectively we're making
42//! a lending stream. This is very close to lending iterators, which is one of the motivating
43//! examples for generic associated types (https://github.com/rust-lang/rust/issues/44265).
44
Brian Silverman1431a772022-08-31 20:44:36 -070045use std::{
46 fmt,
47 future::Future,
48 marker::PhantomData,
Brian Silverman2ee175e2023-07-11 16:32:08 -070049 mem::ManuallyDrop,
Brian Silverman1431a772022-08-31 20:44:36 -070050 panic::{catch_unwind, AssertUnwindSafe},
51 pin::Pin,
52 slice,
53 task::Poll,
54 time::Duration,
55};
Brian Silverman9809c5f2022-07-23 16:12:23 -070056
57use autocxx::{
Austin Schuhdad7a812023-07-26 21:11:22 -070058 subclass::{subclass, CppSubclass},
Brian Silverman9809c5f2022-07-23 16:12:23 -070059 WithinBox,
60};
61use cxx::UniquePtr;
Brian Silverman90221f82022-08-22 23:46:09 -070062use flatbuffers::{root_unchecked, Follow, FollowWith, FullyQualifiedName};
Adam Snaider163800b2023-07-12 00:21:17 -040063use futures::{future::pending, future::FusedFuture, never::Never};
Brian Silverman9809c5f2022-07-23 16:12:23 -070064use thiserror::Error;
65use uuid::Uuid;
66
Brian Silverman90221f82022-08-22 23:46:09 -070067pub use aos_configuration::{Channel, Configuration, Node};
68use aos_configuration::{ChannelLookupError, ConfigurationExt};
69
Brian Silverman9809c5f2022-07-23 16:12:23 -070070pub use aos_uuid::UUID;
Brian Silverman2ee175e2023-07-11 16:32:08 -070071pub use ffi::aos::EventLoopRuntime as CppEventLoopRuntime;
Adam Snaider163800b2023-07-12 00:21:17 -040072pub use ffi::aos::ExitHandle as CppExitHandle;
Brian Silverman9809c5f2022-07-23 16:12:23 -070073
74autocxx::include_cpp! (
75#include "aos/events/event_loop_runtime.h"
76
77safety!(unsafe)
78
79generate_pod!("aos::Context")
80generate!("aos::WatcherForRust")
81generate!("aos::RawSender_Error")
82generate!("aos::SenderForRust")
83generate!("aos::FetcherForRust")
Brian Silverman76f48362022-08-24 21:09:08 -070084generate!("aos::OnRunForRust")
Brian Silverman9809c5f2022-07-23 16:12:23 -070085generate!("aos::EventLoopRuntime")
Adam Snaider163800b2023-07-12 00:21:17 -040086generate!("aos::ExitHandle")
Brian Silverman9809c5f2022-07-23 16:12:23 -070087
88subclass!("aos::ApplicationFuture", RustApplicationFuture)
89
90extern_cpp_type!("aos::Configuration", crate::Configuration)
91extern_cpp_type!("aos::Channel", crate::Channel)
92extern_cpp_type!("aos::Node", crate::Node)
93extern_cpp_type!("aos::UUID", crate::UUID)
94);
95
96pub type EventLoop = ffi::aos::EventLoop;
97
Brian Silverman2ee175e2023-07-11 16:32:08 -070098/// A marker type which is invariant with respect to the given lifetime.
99///
100/// When interacting with functions that take and return things with a given lifetime, the lifetime
101/// becomes invariant. Because we don't store these functions as Rust types, we need a type like
102/// this to tell the Rust compiler that it can't substitute a shorter _or_ longer lifetime.
103pub type InvariantLifetime<'a> = PhantomData<fn(&'a ()) -> &'a ()>;
104
Brian Silverman9809c5f2022-07-23 16:12:23 -0700105/// # Safety
106///
107/// This should have a `'event_loop` lifetime and `future` should include that in its type, but
108/// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is
109/// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which
110/// must be outlived by the EventLoop.
111#[doc(hidden)]
Austin Schuhdad7a812023-07-26 21:11:22 -0700112#[subclass]
Brian Silverman9809c5f2022-07-23 16:12:23 -0700113pub struct RustApplicationFuture {
114 /// This logically has a `'event_loop` bound, see the class comment for details.
115 future: Pin<Box<dyn Future<Output = Never>>>,
116}
117
118impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture {
Brian Silverman1431a772022-08-31 20:44:36 -0700119 fn Poll(&mut self) -> bool {
120 catch_unwind(AssertUnwindSafe(|| {
121 // This is always allowed because it can never create a value of type `Ready<Never>` to
122 // return, so it must always return `Pending`. That also means the value it returns doesn't
123 // mean anything, so we ignore it.
124 let _ = Pin::new(&mut self.future)
125 .poll(&mut std::task::Context::from_waker(&panic_waker()));
126 }))
127 .is_ok()
Brian Silverman9809c5f2022-07-23 16:12:23 -0700128 }
129}
130
131impl RustApplicationFuture {
132 pub fn new<'event_loop>(
133 future: impl Future<Output = Never> + 'event_loop,
134 ) -> UniquePtr<ffi::aos::ApplicationFuture> {
135 /// # Safety
136 ///
137 /// This completely removes the `'event_loop` lifetime, the caller must ensure that is
138 /// sound.
139 unsafe fn remove_lifetime<'event_loop>(
140 future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>,
141 ) -> Pin<Box<dyn Future<Output = Never>>> {
142 // SAFETY: Caller is responsible.
143 unsafe { std::mem::transmute(future) }
144 }
145
146 Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self {
147 // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for
148 // details.
149 future: unsafe { remove_lifetime(Box::pin(future)) },
150 cpp_peer: Default::default(),
151 }))
152 }
153}
154
Brian Silverman2ee175e2023-07-11 16:32:08 -0700155/// An abstraction for objects which hold an `aos::EventLoop` from Rust code.
156///
157/// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call
158/// [`EventLoopRuntime.new`] directly.
159///
160/// # Safety
161///
162/// Objects implementing this trait *must* have mostly-exclusive (except for running it) ownership
163/// of the `aos::EventLoop` *for its entire lifetime*, which *must* be dropped when this object is.
164/// See [`EventLoopRuntime.new`]'s safety requirements for why this can be important and details of
165/// mostly-exclusive. In other words, nothing else may mutate it in any way except processing events
166/// (including dropping, because this object has to be the one to drop it).
167///
168/// This also implies semantics similar to `Pin<&mut ffi::aos::EventLoop>` for the underlying object.
169/// Implementations of this trait must have exclusive ownership of it, and the underlying object
170/// must not be moved.
171pub unsafe trait EventLoopHolder {
172 /// Converts this holder into a raw C++ pointer. This may be fed through other Rust and C++
173 /// code, and eventually passed back to [`from_raw`].
174 fn into_raw(self) -> *mut ffi::aos::EventLoop;
175
176 /// Converts a raw C++ pointer back to a holder object.
177 ///
178 /// # Safety
179 ///
180 /// `raw` must be the result of [`into_raw`] on an instance of this same type. These raw
181 /// pointers *are not* interchangeable between implementations of this trait.
182 unsafe fn from_raw(raw: *mut ffi::aos::EventLoop) -> Self;
183}
184
185/// Owns an [`EventLoopRuntime`] and its underlying `aos::EventLoop`, with safe management of the
186/// associated Rust lifetimes.
187pub struct EventLoopRuntimeHolder<T: EventLoopHolder>(
188 ManuallyDrop<Pin<Box<CppEventLoopRuntime>>>,
189 PhantomData<T>,
190);
191
192impl<T: EventLoopHolder> EventLoopRuntimeHolder<T> {
193 /// Creates a new [`EventLoopRuntime`] and runs an initialization function on it. This is a
194 /// safe wrapper around [`EventLoopRuntime.new`] (although see [`EventLoopHolder`]'s safety
195 /// requirements, part of them are just delegated there).
196 ///
197 /// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call
198 /// [`EventLoopRuntime.new`] directly.
199 ///
200 /// All setup of the runtime must be performed with `fun`, which is called before this function
201 /// returns. `fun` may create further objects to use in async functions via [`EventLoop.spawn`]
202 /// etc, but it is the only place to set things up before the EventLoop is run.
203 ///
204 /// `fun` cannot capture things outside of the event loop, because the event loop might outlive
205 /// them:
206 /// ```compile_fail
207 /// # use aos_events_event_loop_runtime::*;
208 /// # fn bad(event_loop: impl EventLoopHolder) {
209 /// let mut x = 0;
210 /// EventLoopRuntimeHolder::new(event_loop, |runtime| {
211 /// runtime.spawn(async {
212 /// x = 1;
213 /// loop {}
214 /// });
215 /// });
216 /// # }
217 /// ```
218 ///
219 /// But it can capture `'event_loop` references:
220 /// ```
221 /// # use aos_events_event_loop_runtime::*;
222 /// # use aos_configuration::ChannelExt;
223 /// # fn good(event_loop: impl EventLoopHolder) {
224 /// EventLoopRuntimeHolder::new(event_loop, |runtime| {
225 /// let channel = runtime.get_raw_channel("/test", "aos.examples.Ping").unwrap();
226 /// runtime.spawn(async {
227 /// loop {
228 /// eprintln!("{:?}", channel.type_());
229 /// }
230 /// });
231 /// });
232 /// # }
233 /// ```
234 pub fn new<F>(event_loop: T, fun: F) -> Self
235 where
236 F: for<'event_loop> FnOnce(&mut EventLoopRuntime<'event_loop>),
237 {
238 // SAFETY: The EventLoopRuntime never escapes this function, which means the only code that
239 // observes its lifetime is `fun`. `fun` must be generic across any value of its
240 // `'event_loop` lifetime parameter, which means we can choose any lifetime here, which
241 // satisfies the safety requirements.
242 //
243 // This is a similar pattern as `std::thread::scope`, `ghost-cell`, etc. Note that unlike
244 // `std::thread::scope`, our inner functions (the async ones) are definitely not allowed to
245 // capture things from the calling scope of this function, so there's no `'env` equivalent.
246 // `ghost-cell` ends up looking very similar despite doing different things with the
247 // pattern, while `std::thread::scope` has a lot of additional complexity to achieve a
248 // similar result.
249 //
250 // `EventLoopHolder`s safety requirements prevent anybody else from touching the underlying
251 // `aos::EventLoop`.
252 let mut runtime = unsafe { EventLoopRuntime::new(event_loop.into_raw()) };
253 fun(&mut runtime);
254 Self(ManuallyDrop::new(runtime.into_cpp()), PhantomData)
255 }
256}
257
258impl<T: EventLoopHolder> Drop for EventLoopRuntimeHolder<T> {
259 fn drop(&mut self) {
260 let event_loop = self.0.as_mut().event_loop();
261 // SAFETY: We're not going to touch this field again. The underlying EventLoop will not be
262 // run again because we're going to drop it next.
263 unsafe { ManuallyDrop::drop(&mut self.0) };
264 // SAFETY: We took this from `into_raw`, and we just dropped the runtime which may contain
265 // Rust references to it.
266 unsafe { drop(T::from_raw(event_loop)) };
267 }
268}
269
Brian Silverman9809c5f2022-07-23 16:12:23 -0700270pub struct EventLoopRuntime<'event_loop>(
271 Pin<Box<ffi::aos::EventLoopRuntime>>,
Brian Silverman2ee175e2023-07-11 16:32:08 -0700272 // See documentation of [`new`] for details.
273 InvariantLifetime<'event_loop>,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700274);
275
276/// Manages the Rust interface to a *single* `aos::EventLoop`. This is intended to be used by a
277/// single application.
278impl<'event_loop> EventLoopRuntime<'event_loop> {
Brian Silverman2ee175e2023-07-11 16:32:08 -0700279 /// Creates a new runtime. This must be the only user of the underlying `aos::EventLoop`.
280 ///
281 /// Consider using [`EventLoopRuntimeHolder.new`] instead, if you're working with an
282 /// `aos::EventLoop` owned (indirectly) by Rust code.
283 ///
284 /// One common pattern is calling this in the constructor of an object whose lifetime is managed
285 /// by C++; C++ doesn't inherit the Rust lifetime but we do have a lot of C++ code that obeys
286 /// these rules implicitly.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700287 ///
288 /// Call [`spawn`] to respond to events. The non-event-driven APIs may be used without calling
289 /// this.
290 ///
291 /// This is an async runtime, but it's a somewhat unusual one. See the module-level
292 /// documentation for details.
293 ///
294 /// # Safety
295 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700296 /// This function is where all the tricky lifetime guarantees to ensure soundness come
297 /// together. It all boils down to choosing `'event_loop` correctly, which is very complicated.
298 /// Here are the rules:
Brian Silverman9809c5f2022-07-23 16:12:23 -0700299 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700300 /// 1. The `aos::EventLoop` APIs, and any other consumer-facing APIs, of the underlying
301 /// `aos::EventLoop` *must* be exclusively used by this object, and things it calls, for
302 /// `'event_loop`.
303 /// 2. `'event_loop` extends until after the last time the underlying `aos::EventLoop` is run.
304 /// This is often beyond the lifetime of this Rust `EventLoopRuntime` object.
305 /// 3. `'event_loop` must outlive this object, because this object stores references to the
306 /// underlying `aos::EventLoop`.
307 /// 4. Any other references stored in the underlying `aos::EventLoop` must be valid for
308 /// `'event_loop`. The easiest way to ensure this is by not using the `aos::EventLoop` before
309 /// passing it to this object.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700310 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700311 /// Here are some corollaries:
312 ///
313 /// 1. The underlying `aos::EventLoop` must be dropped after this object.
314 /// 2. This object will store various references valid for `'event_loop` with a duration of
315 /// `'event_loop`, which is safe as long as they're both the same `'event_loop`. Note that
316 /// this requires this type to be invariant with respect to `'event_loop`.
317 /// 3. `event_loop` (the pointer being passed in) is effectively `Pin`, which is also implied
318 /// by the underlying `aos::EventLoop` C++ type.
319 /// 4. You cannot create multiple `EventLoopRuntime`s from the same underlying `aos::EventLoop`
320 /// or otherwise use it from a different application. The first one may create
321 /// mutable Rust references while the second one expects exclusive ownership, for example.
322 ///
323 /// `aos::EventLoop`'s public API is exclusively for consumers of the event loop. Some
324 /// subclasses extend this API. Additionally, all useful implementations of `aos::EventLoop`
325 /// must have some way to process events. Sometimes this is additional API surface (such as
326 /// `aos::ShmEventLoop`), in other cases comes via other objects holding references to the
327 /// `aos::EventLoop` (such as `aos::SimulatedEventLoopFactory`). This access to run the event
328 /// loop functions independently of the consuming functions in every way except lifetime of the
329 /// `aos::EventLoop`, and may be used independently of `'event_loop`.
330 ///
331 /// ## Discussion of the rules
332 ///
333 /// Rule 1 is similar to rule 3 (they're both similar to mutable borrowing), but rule 1 extends
334 /// for the entire lifetime of the object instead of being limited to the lifetime of an
335 /// individual borrow by an instance of this type. This is similar to the way [`Pin`]'s
336 /// estrictions extend for the entire lifetime of the object, until it is dropped.
337 ///
338 /// Rule 2 and corollaries 2 and 3 go together, and are essential for making [`spawn`]ed tasks
339 /// useful. The `aos::EventLoop` is full of indirect circular references, both within itself
340 /// and via all of the callbacks. This is sound if all of these references have the *exact
341 /// same* Rust lifetime, which is `'event_loop`.
342 ///
343 /// ## Alternatives and why they don't work
344 ///
345 /// Making the argument `Pin<&'event_loop mut EventLoop>` would express some (but not all) of
346 /// these restrictions within the Rust type system. However, having an actual Rust mutable
347 /// reference like that prevents anything else from creating one via other pointers to the
348 /// same object from C++, which is a common operation. See the module-level documentation for
349 /// details.
350 ///
351 /// [`spawn`]ed tasks need to hold `&'event_loop` references to things like channels. Using a
352 /// separate `'config` lifetime wouldn't change much; the tasks still need to do things which
353 /// require them to not outlive something they don't control. This is fundamental to
354 /// self-referential objects, which `aos::EventLoop` is based around, but Rust requires unsafe
355 /// code to manage manually.
356 ///
357 /// ## Final cautions
358 ///
359 /// Following these rules is very tricky. Be very cautious calling this function. It exposes an
360 /// unbound lifetime, which means you should wrap it directly in a function that attaches a
361 /// correct lifetime.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700362 pub unsafe fn new(event_loop: *mut ffi::aos::EventLoop) -> Self {
363 Self(
364 // SAFETY: We push all the validity requirements for this up to our caller.
365 unsafe { ffi::aos::EventLoopRuntime::new(event_loop) }.within_box(),
Brian Silverman2ee175e2023-07-11 16:32:08 -0700366 InvariantLifetime::default(),
Brian Silverman9809c5f2022-07-23 16:12:23 -0700367 )
368 }
369
Brian Silverman2ee175e2023-07-11 16:32:08 -0700370 /// Creates a Rust wrapper from the underlying C++ object, with an unbound lifetime.
371 ///
372 /// This may never be useful, but it's here for this big scary comment to explain why it's not
373 /// useful.
374 ///
375 /// # Safety
376 ///
377 /// See [`new`] for safety restrictions on `'event_loop` when calling this. In particular, see
378 /// the note about how tricky doing this correctly is, and remember that for this function the
379 /// event loop in question isn't even an argument to this function so it's even trickier. Also
380 /// note that you cannot call this on the result of [`into_cpp`] without violating those
381 /// restrictions.
382 pub unsafe fn from_cpp(cpp: Pin<Box<ffi::aos::EventLoopRuntime>>) -> Self {
383 Self(cpp, InvariantLifetime::default())
384 }
385
386 /// Extracts the underlying C++ object, without the corresponding Rust lifetime. This is useful
387 /// to stop the propagation of Rust lifetimes without destroying the underlying object which
388 /// contains all the state.
389 ///
390 /// Note that you *cannot* call [`from_cpp`] on the result of this, because that will violate
391 /// [`from_cpp`]'s safety requirements.
392 pub fn into_cpp(self) -> Pin<Box<ffi::aos::EventLoopRuntime>> {
393 self.0
394 }
395
Brian Silverman9809c5f2022-07-23 16:12:23 -0700396 /// Returns the pointer passed into the constructor.
397 ///
398 /// The returned value should only be used for destroying it (_after_ `self` is dropped) or
399 /// calling other C++ APIs.
400 pub fn raw_event_loop(&mut self) -> *mut ffi::aos::EventLoop {
401 self.0.as_mut().event_loop()
402 }
403
Brian Silverman90221f82022-08-22 23:46:09 -0700404 /// Returns a reference to the name of this EventLoop.
405 ///
406 /// TODO(Brian): Come up with a nice way to expose this safely, without memory allocations, for
407 /// logging etc.
408 ///
409 /// # Safety
410 ///
411 /// The result must not be used after C++ could change it. Unfortunately C++ can change this
412 /// name from most places, so you should be really careful what you do with the result.
413 pub unsafe fn raw_name(&self) -> &str {
414 self.0.name()
415 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700416
417 pub fn get_raw_channel(
418 &self,
419 name: &str,
420 typename: &str,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700421 ) -> Result<&'event_loop Channel, ChannelLookupError> {
Brian Silverman90221f82022-08-22 23:46:09 -0700422 self.configuration().get_channel(
423 name,
424 typename,
425 // SAFETY: We're not calling any EventLoop methods while C++ is using this for the
426 // channel lookup.
427 unsafe { self.raw_name() },
428 self.node(),
429 )
Brian Silverman9809c5f2022-07-23 16:12:23 -0700430 }
431
Brian Silverman90221f82022-08-22 23:46:09 -0700432 pub fn get_channel<T: FullyQualifiedName>(
433 &self,
434 name: &str,
435 ) -> Result<&'event_loop Channel, ChannelLookupError> {
436 self.get_raw_channel(name, T::get_fully_qualified_name())
437 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700438
439 /// Starts running the given `task`, which may not return (as specified by its type). If you
440 /// want your task to stop, return the result of awaiting [`futures::future::pending`], which
441 /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits.
442 ///
Brian Silverman76f48362022-08-24 21:09:08 -0700443 /// Note that task will be polled immediately, to give it a chance to initialize. If you want to
444 /// defer work until the event loop starts running, await [`on_run`] in the task.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700445 ///
446 /// # Panics
447 ///
448 /// Panics if called more than once. See the module-level documentation for alternatives if you
449 /// want to do this.
450 ///
451 /// # Examples with interesting return types
452 ///
453 /// These are all valid futures which never return:
454 /// ```
455 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
456 /// # use futures::{never::Never, future::pending};
457 /// async fn pending_wrapper() -> Never {
458 /// pending().await
459 /// }
460 /// async fn loop_forever() -> Never {
461 /// loop {}
462 /// }
463 ///
464 /// runtime.spawn(pending());
465 /// runtime.spawn(async { pending().await });
466 /// runtime.spawn(pending_wrapper());
467 /// runtime.spawn(async { loop {} });
468 /// runtime.spawn(loop_forever());
469 /// runtime.spawn(async { println!("all done"); pending().await });
470 /// # }
471 /// ```
472 /// but this is not:
473 /// ```compile_fail
474 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
475 /// # use futures::ready;
476 /// runtime.spawn(ready());
477 /// # }
478 /// ```
479 /// and neither is this:
480 /// ```compile_fail
481 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
482 /// # use futures::ready;
483 /// runtime.spawn(async { println!("all done") });
484 /// # }
485 /// ```
486 ///
487 /// # Examples with capturing
488 ///
489 /// The future can capture things. This is important to access other objects created from the
490 /// runtime, either before calling this function:
491 /// ```
492 /// # fn compile_check<'event_loop>(
493 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
494 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
495 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
496 /// # ) {
497 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
498 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
499 /// runtime.spawn(async move { loop {
500 /// watcher1.next().await;
501 /// watcher2.next().await;
502 /// }});
503 /// # }
504 /// ```
505 /// or after:
506 /// ```
507 /// # fn compile_check<'event_loop>(
508 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
509 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
510 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
511 /// # ) {
512 /// # use std::{cell::RefCell, rc::Rc};
513 /// let runtime = Rc::new(RefCell::new(runtime));
514 /// runtime.borrow_mut().spawn({
515 /// let mut runtime = runtime.clone();
516 /// async move {
517 /// let mut runtime = runtime.borrow_mut();
518 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
519 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
520 /// loop {
521 /// watcher1.next().await;
522 /// watcher2.next().await;
523 /// }
524 /// }
525 /// });
526 /// # }
527 /// ```
528 /// or both:
529 /// ```
530 /// # fn compile_check<'event_loop>(
531 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
532 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
533 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
534 /// # ) {
535 /// # use std::{cell::RefCell, rc::Rc};
536 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
537 /// let runtime = Rc::new(RefCell::new(runtime));
538 /// runtime.borrow_mut().spawn({
539 /// let mut runtime = runtime.clone();
540 /// async move {
541 /// let mut runtime = runtime.borrow_mut();
542 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
543 /// loop {
544 /// watcher1.next().await;
545 /// watcher2.next().await;
546 /// }
547 /// }
548 /// });
549 /// # }
550 /// ```
551 ///
552 /// But you cannot capture local variables:
553 /// ```compile_fail
554 /// # fn compile_check<'event_loop>(
555 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
556 /// # ) {
557 /// let mut local: i32 = 971;
558 /// let local = &mut local;
559 /// runtime.spawn(async move { loop {
560 /// println!("have: {}", local);
561 /// }});
562 /// # }
563 /// ```
564 pub fn spawn(&mut self, task: impl Future<Output = Never> + 'event_loop) {
Brian Silverman1431a772022-08-31 20:44:36 -0700565 self.0.as_mut().Spawn(RustApplicationFuture::new(task));
Brian Silverman9809c5f2022-07-23 16:12:23 -0700566 }
567
568 pub fn configuration(&self) -> &'event_loop Configuration {
569 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop.
570 unsafe { &*self.0.configuration() }
571 }
572
573 pub fn node(&self) -> Option<&'event_loop Node> {
574 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null.
575 unsafe { self.0.node().as_ref() }
576 }
577
578 pub fn monotonic_now(&self) -> MonotonicInstant {
579 MonotonicInstant(self.0.monotonic_now())
580 }
581
Ryan Yin683a8672022-11-09 20:44:20 -0800582 pub fn realtime_now(&self) -> RealtimeInstant {
583 RealtimeInstant(self.0.realtime_now())
584 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700585 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
586 /// part of `self.configuration()`, which will always have this lifetime.
587 ///
588 /// # Panics
589 ///
590 /// Dropping `self` before the returned object is dropped will panic.
591 pub fn make_raw_watcher(&mut self, channel: &'event_loop Channel) -> RawWatcher {
592 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
593 // the usual autocxx heuristics.
594 RawWatcher(unsafe { self.0.as_mut().MakeWatcher(channel) }.within_box())
595 }
596
Brian Silverman90221f82022-08-22 23:46:09 -0700597 /// Provides type-safe async blocking access to messages on a channel. `T` should be a
598 /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static`
599 /// is easiest.
600 ///
601 /// # Panics
602 ///
603 /// Dropping `self` before the returned object is dropped will panic.
604 pub fn make_watcher<T>(&mut self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError>
605 where
606 for<'a> T: FollowWith<'a>,
607 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
608 T: FullyQualifiedName,
609 {
610 let channel = self.get_channel::<T>(channel_name)?;
611 Ok(Watcher(self.make_raw_watcher(channel), PhantomData))
612 }
613
Brian Silverman9809c5f2022-07-23 16:12:23 -0700614 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
615 /// part of `self.configuration()`, which will always have this lifetime.
616 ///
617 /// # Panics
618 ///
619 /// Dropping `self` before the returned object is dropped will panic.
620 pub fn make_raw_sender(&mut self, channel: &'event_loop Channel) -> RawSender {
621 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
622 // the usual autocxx heuristics.
623 RawSender(unsafe { self.0.as_mut().MakeSender(channel) }.within_box())
624 }
625
Brian Silverman90221f82022-08-22 23:46:09 -0700626 /// Allows sending messages on a channel with a type-safe API.
627 ///
628 /// # Panics
629 ///
630 /// Dropping `self` before the returned object is dropped will panic.
631 pub fn make_sender<T>(&mut self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError>
632 where
633 for<'a> T: FollowWith<'a>,
634 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
635 T: FullyQualifiedName,
636 {
637 let channel = self.get_channel::<T>(channel_name)?;
638 Ok(Sender(self.make_raw_sender(channel), PhantomData))
639 }
640
Brian Silverman9809c5f2022-07-23 16:12:23 -0700641 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
642 /// part of `self.configuration()`, which will always have this lifetime.
643 ///
644 /// # Panics
645 ///
646 /// Dropping `self` before the returned object is dropped will panic.
647 pub fn make_raw_fetcher(&mut self, channel: &'event_loop Channel) -> RawFetcher {
648 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
649 // the usual autocxx heuristics.
650 RawFetcher(unsafe { self.0.as_mut().MakeFetcher(channel) }.within_box())
651 }
652
Brian Silverman90221f82022-08-22 23:46:09 -0700653 /// Provides type-safe access to messages on a channel, without the ability to wait for a new
654 /// one. This provides APIs to get the latest message, and to follow along and retrieve each
655 /// message in order.
656 ///
657 /// # Panics
658 ///
659 /// Dropping `self` before the returned object is dropped will panic.
660 pub fn make_fetcher<T>(&mut self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError>
661 where
662 for<'a> T: FollowWith<'a>,
663 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
664 T: FullyQualifiedName,
665 {
666 let channel = self.get_channel::<T>(channel_name)?;
667 Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData))
668 }
669
Brian Silverman9809c5f2022-07-23 16:12:23 -0700670 // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those,
671 // instead of / in addition to mirroring C++ with separate setup and wait?
672
Brian Silverman76f48362022-08-24 21:09:08 -0700673 /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all
674 /// subsequent code will have any realtime scheduling applied. This means it can rely on
675 /// consistent timing, but it can no longer create any EventLoop child objects or do anything
676 /// else non-realtime.
677 pub fn on_run(&mut self) -> OnRun {
678 OnRun(self.0.as_mut().MakeOnRun().within_box())
679 }
680
681 pub fn is_running(&self) -> bool {
682 self.0.is_running()
683 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700684}
685
Brian Silverman9809c5f2022-07-23 16:12:23 -0700686/// Provides async blocking access to messages on a channel. This will return every message on the
687/// channel, in order.
688///
689/// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these.
690///
691/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
692/// for actually interpreting messages. You probably want a [`Watcher`] instead.
693///
694/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
695/// reasons.
696///
697/// # Design
698///
699/// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means
700/// it's different for each `self` lifetime so we can't write a single type alias for it. We could
701/// write an intermediate type with a generic lifetime that implements `Stream` and is returned
702/// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding
703/// another level doesn't help anything.
704///
705/// We also drop the extraneous `cx` argument that isn't used by this implementation anyways.
706///
707/// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's
708/// the same one mentioned here:
709/// 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
710/// We get around that one by moving the unbounded lifetime from the pointer dereference into the
711/// function with the if statement.
Brian Silverman90221f82022-08-22 23:46:09 -0700712// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
713#[repr(transparent)]
714pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>);
715
Brian Silverman9809c5f2022-07-23 16:12:23 -0700716impl RawWatcher {
717 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
718 /// without skipping any messages.
719 ///
720 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
721 /// will need to call this function again to get the succeeding message.
722 ///
723 /// # Examples
724 ///
725 /// The common use case is immediately awaiting the next message:
726 /// ```
727 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
728 /// println!("received: {:?}", watcher.next().await);
729 /// # }
730 /// ```
731 ///
732 /// You can also await the first message from any of a set of channels:
733 /// ```
734 /// # async fn select(
735 /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher,
736 /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher,
737 /// # ) {
738 /// futures::select! {
739 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
740 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
741 /// }
742 /// # }
743 /// ```
744 ///
745 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
746 /// enforce only having a single of these returned objects at a time. Drop the previous message
747 /// before asking for the next one. That means this will not compile:
748 /// ```compile_fail
749 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
750 /// let first = watcher.next();
751 /// let second = watcher.next();
752 /// first.await;
753 /// # }
754 /// ```
755 /// and nor will this:
756 /// ```compile_fail
757 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
758 /// let first = watcher.next().await;
759 /// watcher.next();
760 /// println!("still have: {:?}", first);
761 /// # }
762 /// ```
763 /// but this is fine:
764 /// ```
765 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
766 /// let first = watcher.next().await;
767 /// println!("have: {:?}", first);
768 /// watcher.next();
769 /// # }
770 /// ```
771 pub fn next(&mut self) -> RawWatcherNext {
772 RawWatcherNext(Some(self))
773 }
774}
775
776/// The type returned from [`RawWatcher::next`], see there for details.
777pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>);
778
779impl<'a> Future for RawWatcherNext<'a> {
780 type Output = Context<'a>;
781 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> {
782 let inner = self
783 .0
784 .take()
785 .expect("May not call poll after it returns Ready");
786 let maybe_context = inner.0.as_mut().PollNext();
787 if maybe_context.is_null() {
788 // We're not returning a reference into it, so we can safely replace the reference to
789 // use again in the future.
790 self.0.replace(inner);
791 Poll::Pending
792 } else {
793 // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will
794 // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`)
795 // because we're dropping `inner` (which is that reference), so it will need to be
796 // borrowed again which cannot happen before the end of `'a`.
797 Poll::Ready(Context(unsafe { &*maybe_context }))
798 }
799 }
800}
801
802impl FusedFuture for RawWatcherNext<'_> {
803 fn is_terminated(&self) -> bool {
804 self.0.is_none()
805 }
806}
807
Brian Silverman90221f82022-08-22 23:46:09 -0700808/// Provides async blocking access to messages on a channel. This will return every message on the
809/// channel, in order.
810///
811/// Use [`EventLoopRuntime::make_watcher`] to create one of these.
812///
813/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
814/// reasons. See [`RawWatcher`]'s documentation for details.
815pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>)
816where
817 for<'a> T: FollowWith<'a>,
818 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
819
820impl<T> Watcher<T>
821where
822 for<'a> T: FollowWith<'a>,
823 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
824{
825 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
826 /// without skipping any messages.
827 ///
828 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
829 /// will need to call this function again to get the succeeding message.
830 ///
831 /// # Examples
832 ///
833 /// The common use case is immediately awaiting the next message:
834 /// ```
835 /// # use pong_rust_fbs::aos::examples::Pong;
836 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
837 /// println!("received: {:?}", watcher.next().await);
838 /// # }
839 /// ```
840 ///
841 /// You can also await the first message from any of a set of channels:
842 /// ```
843 /// # use pong_rust_fbs::aos::examples::Pong;
844 /// # async fn select(
845 /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
846 /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
847 /// # ) {
848 /// futures::select! {
849 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
850 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
851 /// }
852 /// # }
853 /// ```
854 ///
855 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
856 /// enforce only having a single of these returned objects at a time. Drop the previous message
857 /// before asking for the next one. That means this will not compile:
858 /// ```compile_fail
859 /// # use pong_rust_fbs::aos::examples::Pong;
860 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
861 /// let first = watcher.next();
862 /// let second = watcher.next();
863 /// first.await;
864 /// # }
865 /// ```
866 /// and nor will this:
867 /// ```compile_fail
868 /// # use pong_rust_fbs::aos::examples::Pong;
869 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
870 /// let first = watcher.next().await;
871 /// watcher.next();
872 /// println!("still have: {:?}", first);
873 /// # }
874 /// ```
875 /// but this is fine:
876 /// ```
877 /// # use pong_rust_fbs::aos::examples::Pong;
878 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
879 /// let first = watcher.next().await;
880 /// println!("have: {:?}", first);
881 /// watcher.next();
882 /// # }
883 /// ```
884 pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> {
885 WatcherNext(self.0.next(), PhantomData)
886 }
887}
888
889/// The type returned from [`Watcher::next`], see there for details.
890pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>)
891where
892 T: Follow<'watcher> + 'watcher;
893
894impl<'watcher, T> Future for WatcherNext<'watcher, T>
895where
896 T: Follow<'watcher> + 'watcher,
897{
898 type Output = TypedContext<'watcher, T>;
899
900 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
901 Pin::new(&mut self.get_mut().0).poll(cx).map(|context|
902 // SAFETY: The Watcher this was created from verified that the channel is the
903 // right type, and the C++ guarantees that the buffer's type matches.
904 TypedContext(context, PhantomData))
905 }
906}
907
908impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T>
909where
910 T: Follow<'watcher> + 'watcher,
911{
912 fn is_terminated(&self) -> bool {
913 self.0.is_terminated()
914 }
915}
916
917/// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type.
918pub struct TypedContext<'a, T>(
919 // SAFETY: This must have a message, and it must be a valid `T` flatbuffer.
920 Context<'a>,
921 PhantomData<*mut T>,
922)
923where
924 T: Follow<'a> + 'a;
925
Brian Silverman90221f82022-08-22 23:46:09 -0700926impl<'a, T> TypedContext<'a, T>
927where
928 T: Follow<'a> + 'a,
929{
930 pub fn message(&self) -> Option<T::Inner> {
931 self.0.data().map(|data| {
932 // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right
933 // type based on invariants for our type.
934 unsafe { root_unchecked::<T>(data) }
935 })
936 }
937
938 pub fn monotonic_event_time(&self) -> MonotonicInstant {
939 self.0.monotonic_event_time()
940 }
941 pub fn monotonic_remote_time(&self) -> MonotonicInstant {
942 self.0.monotonic_remote_time()
943 }
Ryan Yin683a8672022-11-09 20:44:20 -0800944 pub fn realtime_event_time(&self) -> RealtimeInstant {
945 self.0.realtime_event_time()
946 }
947 pub fn realtime_remote_time(&self) -> RealtimeInstant {
948 self.0.realtime_remote_time()
949 }
Brian Silverman90221f82022-08-22 23:46:09 -0700950 pub fn queue_index(&self) -> u32 {
951 self.0.queue_index()
952 }
953 pub fn remote_queue_index(&self) -> u32 {
954 self.0.remote_queue_index()
955 }
956 pub fn buffer_index(&self) -> i32 {
957 self.0.buffer_index()
958 }
959 pub fn source_boot_uuid(&self) -> &Uuid {
960 self.0.source_boot_uuid()
961 }
962}
963
964impl<'a, T> fmt::Debug for TypedContext<'a, T>
965where
966 T: Follow<'a> + 'a,
967 T::Inner: fmt::Debug,
968{
969 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman90221f82022-08-22 23:46:09 -0700970 f.debug_struct("TypedContext")
971 .field("monotonic_event_time", &self.monotonic_event_time())
972 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -0800973 .field("realtime_event_time", &self.realtime_event_time())
974 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman90221f82022-08-22 23:46:09 -0700975 .field("queue_index", &self.queue_index())
976 .field("remote_queue_index", &self.remote_queue_index())
977 .field("message", &self.message())
978 .field("buffer_index", &self.buffer_index())
979 .field("source_boot_uuid", &self.source_boot_uuid())
980 .finish()
981 }
982}
Brian Silverman9809c5f2022-07-23 16:12:23 -0700983
984/// Provides access to messages on a channel, without the ability to wait for a new one. This
Brian Silverman90221f82022-08-22 23:46:09 -0700985/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700986///
987/// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these.
988///
989/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
990/// for actually interpreting messages. You probably want a [`Fetcher`] instead.
Brian Silverman90221f82022-08-22 23:46:09 -0700991// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
992#[repr(transparent)]
993pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>);
994
Brian Silverman9809c5f2022-07-23 16:12:23 -0700995impl RawFetcher {
996 pub fn fetch_next(&mut self) -> bool {
997 self.0.as_mut().FetchNext()
998 }
999
1000 pub fn fetch(&mut self) -> bool {
1001 self.0.as_mut().Fetch()
1002 }
1003
1004 pub fn context(&self) -> Context {
1005 Context(self.0.context())
1006 }
1007}
1008
Brian Silverman90221f82022-08-22 23:46:09 -07001009/// Provides access to messages on a channel, without the ability to wait for a new one. This
1010/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
1011///
1012/// Use [`EventLoopRuntime::make_fetcher`] to create one of these.
1013pub struct Fetcher<T>(
1014 // SAFETY: This must produce messages of type `T`.
1015 RawFetcher,
1016 PhantomData<*mut T>,
1017)
1018where
1019 for<'a> T: FollowWith<'a>,
1020 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1021
1022impl<T> Fetcher<T>
1023where
1024 for<'a> T: FollowWith<'a>,
1025 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1026{
1027 pub fn fetch_next(&mut self) -> bool {
1028 self.0.fetch_next()
1029 }
1030 pub fn fetch(&mut self) -> bool {
1031 self.0.fetch()
1032 }
1033
1034 pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> {
1035 // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's
1036 // type matches.
1037 TypedContext(self.0.context(), PhantomData)
1038 }
1039}
Brian Silverman9809c5f2022-07-23 16:12:23 -07001040
1041/// Allows sending messages on a channel.
1042///
1043/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
1044/// for actually creating messages to send. You probably want a [`Sender`] instead.
1045///
1046/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
Brian Silverman90221f82022-08-22 23:46:09 -07001047// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1048#[repr(transparent)]
1049pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>);
1050
Brian Silverman9809c5f2022-07-23 16:12:23 -07001051impl RawSender {
1052 fn buffer(&mut self) -> &mut [u8] {
1053 // SAFETY: This is a valid slice, and `u8` doesn't have any alignment requirements.
1054 unsafe { slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) }
1055 }
1056
1057 /// Returns an object which can be used to build a message.
1058 ///
1059 /// # Examples
1060 ///
1061 /// ```
1062 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1063 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1064 /// # unsafe {
1065 /// let mut builder = sender.make_builder();
1066 /// let pong = PongBuilder::new(builder.fbb()).finish();
1067 /// builder.send(pong);
1068 /// # }
1069 /// # }
1070 /// ```
1071 ///
1072 /// You can bail out of building a message and build another one:
1073 /// ```
1074 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1075 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1076 /// # unsafe {
1077 /// let mut builder1 = sender.make_builder();
1078 /// builder1.fbb();
1079 /// let mut builder2 = sender.make_builder();
1080 /// let pong = PongBuilder::new(builder2.fbb()).finish();
1081 /// builder2.send(pong);
1082 /// # }
1083 /// # }
1084 /// ```
1085 /// but you cannot build two messages at the same time with a single builder:
1086 /// ```compile_fail
1087 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1088 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1089 /// # unsafe {
1090 /// let mut builder1 = sender.make_builder();
1091 /// let mut builder2 = sender.make_builder();
1092 /// PongBuilder::new(builder2.fbb()).finish();
1093 /// PongBuilder::new(builder1.fbb()).finish();
1094 /// # }
1095 /// # }
1096 /// ```
1097 pub fn make_builder(&mut self) -> RawBuilder {
1098 // TODO(Brian): Actually use the provided buffer instead of just using its
1099 // size to allocate a separate one.
1100 //
1101 // See https://github.com/google/flatbuffers/issues/7385.
1102 let fbb = flatbuffers::FlatBufferBuilder::with_capacity(self.buffer().len());
1103 RawBuilder {
1104 raw_sender: self,
1105 fbb,
1106 }
1107 }
1108}
1109
Brian Silverman9809c5f2022-07-23 16:12:23 -07001110/// Used for building a message. See [`RawSender::make_builder`] for details.
1111pub struct RawBuilder<'sender> {
1112 raw_sender: &'sender mut RawSender,
1113 fbb: flatbuffers::FlatBufferBuilder<'sender>,
1114}
1115
1116impl<'sender> RawBuilder<'sender> {
1117 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
1118 &mut self.fbb
1119 }
1120
1121 /// # Safety
1122 ///
1123 /// `T` must match the type of the channel of the sender this builder was created from.
1124 pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> {
1125 self.fbb.finish_minimal(root);
1126 let data = self.fbb.finished_data();
1127
1128 use ffi::aos::RawSender_Error as FfiError;
1129 // SAFETY: This is a valid buffer we're passing.
1130 match unsafe {
1131 self.raw_sender
1132 .0
1133 .as_mut()
1134 .CopyAndSend(data.as_ptr(), data.len())
1135 } {
1136 FfiError::kOk => Ok(()),
1137 FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast),
1138 FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone),
1139 }
1140 }
1141}
1142
Brian Silverman90221f82022-08-22 23:46:09 -07001143/// Allows sending messages on a channel with a type-safe API.
1144///
1145/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
1146pub struct Sender<T>(
1147 // SAFETY: This must accept messages of type `T`.
1148 RawSender,
1149 PhantomData<*mut T>,
1150)
1151where
1152 for<'a> T: FollowWith<'a>,
1153 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1154
1155impl<T> Sender<T>
1156where
1157 for<'a> T: FollowWith<'a>,
1158 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1159{
1160 /// Returns an object which can be used to build a message.
1161 ///
1162 /// # Examples
1163 ///
1164 /// ```
1165 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1166 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1167 /// let mut builder = sender.make_builder();
1168 /// let pong = PongBuilder::new(builder.fbb()).finish();
1169 /// builder.send(pong);
1170 /// # }
1171 /// ```
1172 ///
1173 /// You can bail out of building a message and build another one:
1174 /// ```
1175 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1176 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1177 /// let mut builder1 = sender.make_builder();
1178 /// builder1.fbb();
1179 /// let mut builder2 = sender.make_builder();
1180 /// let pong = PongBuilder::new(builder2.fbb()).finish();
1181 /// builder2.send(pong);
1182 /// # }
1183 /// ```
1184 /// but you cannot build two messages at the same time with a single builder:
1185 /// ```compile_fail
1186 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1187 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1188 /// let mut builder1 = sender.make_builder();
1189 /// let mut builder2 = sender.make_builder();
1190 /// PongBuilder::new(builder2.fbb()).finish();
1191 /// PongBuilder::new(builder1.fbb()).finish();
1192 /// # }
1193 /// ```
1194 pub fn make_builder(&mut self) -> Builder<T> {
1195 Builder(self.0.make_builder(), PhantomData)
1196 }
1197}
1198
1199/// Used for building a message. See [`Sender::make_builder`] for details.
1200pub struct Builder<'sender, T>(
1201 // SAFETY: This must accept messages of type `T`.
1202 RawBuilder<'sender>,
1203 PhantomData<*mut T>,
1204)
1205where
1206 for<'a> T: FollowWith<'a>,
1207 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1208
1209impl<'sender, T> Builder<'sender, T>
1210where
1211 for<'a> T: FollowWith<'a>,
1212 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1213{
1214 pub fn fbb(&mut self) -> &mut flatbuffers::FlatBufferBuilder<'sender> {
1215 self.0.fbb()
1216 }
1217
1218 pub fn send<'a>(
1219 self,
1220 root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>,
1221 ) -> Result<(), SendError> {
1222 // SAFETY: We guarantee this is the right type based on invariants for our type.
1223 unsafe { self.0.send(root) }
1224 }
1225}
1226
1227#[derive(Clone, Copy, Eq, PartialEq, Debug, Error)]
1228pub enum SendError {
1229 #[error("messages have been sent too fast on this channel")]
1230 MessagesSentTooFast,
1231 #[error("invalid redzone data, shared memory corruption detected")]
1232 InvalidRedzone,
1233}
1234
Brian Silverman9809c5f2022-07-23 16:12:23 -07001235#[repr(transparent)]
1236#[derive(Clone, Copy)]
1237pub struct Context<'context>(&'context ffi::aos::Context);
1238
1239impl fmt::Debug for Context<'_> {
1240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001241 f.debug_struct("Context")
1242 .field("monotonic_event_time", &self.monotonic_event_time())
1243 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -08001244 .field("realtime_event_time", &self.realtime_event_time())
1245 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman9809c5f2022-07-23 16:12:23 -07001246 .field("queue_index", &self.queue_index())
1247 .field("remote_queue_index", &self.remote_queue_index())
1248 .field("size", &self.data().map(|data| data.len()))
1249 .field("buffer_index", &self.buffer_index())
1250 .field("source_boot_uuid", &self.source_boot_uuid())
1251 .finish()
1252 }
1253}
1254
Brian Silverman9809c5f2022-07-23 16:12:23 -07001255impl<'context> Context<'context> {
1256 pub fn monotonic_event_time(self) -> MonotonicInstant {
1257 MonotonicInstant(self.0.monotonic_event_time)
1258 }
1259
1260 pub fn monotonic_remote_time(self) -> MonotonicInstant {
1261 MonotonicInstant(self.0.monotonic_remote_time)
1262 }
1263
Ryan Yin683a8672022-11-09 20:44:20 -08001264 pub fn realtime_event_time(self) -> RealtimeInstant {
1265 RealtimeInstant(self.0.realtime_event_time)
1266 }
1267
1268 pub fn realtime_remote_time(self) -> RealtimeInstant {
1269 RealtimeInstant(self.0.realtime_remote_time)
1270 }
1271
Brian Silverman9809c5f2022-07-23 16:12:23 -07001272 pub fn queue_index(self) -> u32 {
1273 self.0.queue_index
1274 }
1275 pub fn remote_queue_index(self) -> u32 {
1276 self.0.remote_queue_index
1277 }
1278
1279 pub fn data(self) -> Option<&'context [u8]> {
1280 if self.0.data.is_null() {
1281 None
1282 } else {
1283 // SAFETY:
1284 // * `u8` has no alignment requirements
1285 // * It must be a single initialized flatbuffers buffer
1286 // * The borrow in `self.0` guarantees it won't be modified for `'context`
1287 Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) })
1288 }
1289 }
1290
1291 pub fn buffer_index(self) -> i32 {
1292 self.0.buffer_index
1293 }
1294
1295 pub fn source_boot_uuid(self) -> &'context Uuid {
1296 // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be
1297 // valid until something changes the context, which is `'context`.
1298 Uuid::from_bytes_ref(&self.0.source_boot_uuid)
1299 }
1300}
1301
Brian Silverman76f48362022-08-24 21:09:08 -07001302/// The type returned from [`EventLoopRuntime::on_run`], see there for details.
1303// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1304#[repr(transparent)]
1305pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>);
1306
1307impl Future for OnRun {
1308 type Output = ();
1309
1310 fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
1311 if self.0.is_running() {
1312 Poll::Ready(())
1313 } else {
1314 Poll::Pending
1315 }
1316 }
1317}
1318
Brian Silverman9809c5f2022-07-23 16:12:23 -07001319/// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This
1320/// is intended to have the same API as [`std::time::Instant`], any missing
1321/// functionality can be added if useful.
Brian Silverman9809c5f2022-07-23 16:12:23 -07001322#[repr(transparent)]
1323#[derive(Clone, Copy, Eq, PartialEq)]
1324pub struct MonotonicInstant(i64);
1325
1326impl MonotonicInstant {
1327 /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value.
1328 pub const MIN_TIME: Self = Self(i64::MIN);
1329
1330 pub fn is_min_time(self) -> bool {
1331 self == Self::MIN_TIME
1332 }
1333
1334 pub fn duration_since_epoch(self) -> Option<Duration> {
1335 if self.is_min_time() {
1336 None
1337 } else {
1338 Some(Duration::from_nanos(self.0.try_into().expect(
1339 "monotonic_clock::time_point should always be after the epoch",
1340 )))
1341 }
1342 }
1343}
1344
1345impl fmt::Debug for MonotonicInstant {
1346 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1347 self.duration_since_epoch().fmt(f)
1348 }
1349}
1350
Ryan Yin683a8672022-11-09 20:44:20 -08001351#[repr(transparent)]
1352#[derive(Clone, Copy, Eq, PartialEq)]
1353pub struct RealtimeInstant(i64);
1354
1355impl RealtimeInstant {
1356 pub const MIN_TIME: Self = Self(i64::MIN);
1357
1358 pub fn is_min_time(self) -> bool {
1359 self == Self::MIN_TIME
1360 }
1361
1362 pub fn duration_since_epoch(self) -> Option<Duration> {
1363 if self.is_min_time() {
1364 None
1365 } else {
1366 Some(Duration::from_nanos(self.0.try_into().expect(
1367 "monotonic_clock::time_point should always be after the epoch",
1368 )))
1369 }
1370 }
1371}
1372
1373impl fmt::Debug for RealtimeInstant {
1374 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1375 self.duration_since_epoch().fmt(f)
1376 }
1377}
1378
Brian Silverman9809c5f2022-07-23 16:12:23 -07001379mod panic_waker {
1380 use std::task::{RawWaker, RawWakerVTable, Waker};
1381
1382 unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker {
1383 raw_panic_waker()
1384 }
1385
1386 unsafe fn noop(_data: *const ()) {}
1387
1388 unsafe fn wake_panic(_data: *const ()) {
1389 panic!("Nothing should wake EventLoopRuntime's waker");
1390 }
1391
1392 const PANIC_WAKER_VTABLE: RawWakerVTable =
1393 RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop);
1394
1395 fn raw_panic_waker() -> RawWaker {
1396 RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE)
1397 }
1398
1399 pub fn panic_waker() -> Waker {
1400 // SAFETY: The implementations of the RawWakerVTable functions do what is required of them.
1401 unsafe { Waker::from_raw(raw_panic_waker()) }
1402 }
1403}
1404
1405use panic_waker::panic_waker;
Adam Snaider163800b2023-07-12 00:21:17 -04001406
1407pub struct ExitHandle(UniquePtr<CppExitHandle>);
1408
1409impl ExitHandle {
1410 /// Exits the EventLoops represented by this handle. You probably want to immediately return
1411 /// from the context this is called in. Awaiting [`exit`] instead of using this function is an
1412 /// easy way to do that.
1413 pub fn exit_sync(mut self) {
1414 self.0.as_mut().unwrap().Exit();
1415 }
1416
1417 /// Exits the EventLoops represented by this handle, and never returns. Immediately awaiting
1418 /// this from a [`EventLoopRuntime::spawn`]ed task is usually what you want, it will ensure
1419 /// that no more code from that task runs.
1420 pub async fn exit(self) -> Never {
1421 self.exit_sync();
1422 pending().await
1423 }
1424}
1425
1426impl From<UniquePtr<CppExitHandle>> for ExitHandle {
1427 fn from(inner: UniquePtr<ffi::aos::ExitHandle>) -> Self {
1428 Self(inner)
1429 }
1430}