blob: dc1da079989f7d754ff6ff4b2179e89cd4d0a056 [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,
Adam Snaider34072e12023-10-03 10:04:25 -070050 ops::{Add, Deref, DerefMut},
Brian Silverman1431a772022-08-31 20:44:36 -070051 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::{
Austin Schuhdad7a812023-07-26 21:11:22 -070059 subclass::{subclass, CppSubclass},
Brian Silverman9809c5f2022-07-23 16:12:23 -070060 WithinBox,
61};
62use cxx::UniquePtr;
Adam Snaider34072e12023-10-03 10:04:25 -070063use flatbuffers::{
64 root_unchecked, Allocator, FlatBufferBuilder, Follow, FollowWith, FullyQualifiedName,
65};
Adam Snaider163800b2023-07-12 00:21:17 -040066use futures::{future::pending, future::FusedFuture, never::Never};
Brian Silverman9809c5f2022-07-23 16:12:23 -070067use thiserror::Error;
68use uuid::Uuid;
69
Brian Silverman90221f82022-08-22 23:46:09 -070070pub use aos_configuration::{Channel, Configuration, Node};
71use aos_configuration::{ChannelLookupError, ConfigurationExt};
72
Brian Silverman9809c5f2022-07-23 16:12:23 -070073pub use aos_uuid::UUID;
Adam Snaider88097232023-10-17 18:43:14 -070074pub use ffi::aos::EventLoop as CppEventLoop;
Brian Silverman2ee175e2023-07-11 16:32:08 -070075pub use ffi::aos::EventLoopRuntime as CppEventLoopRuntime;
Adam Snaider163800b2023-07-12 00:21:17 -040076pub use ffi::aos::ExitHandle as CppExitHandle;
Brian Silverman9809c5f2022-07-23 16:12:23 -070077
78autocxx::include_cpp! (
79#include "aos/events/event_loop_runtime.h"
80
81safety!(unsafe)
82
83generate_pod!("aos::Context")
84generate!("aos::WatcherForRust")
85generate!("aos::RawSender_Error")
86generate!("aos::SenderForRust")
87generate!("aos::FetcherForRust")
Brian Silverman76f48362022-08-24 21:09:08 -070088generate!("aos::OnRunForRust")
Brian Silverman9809c5f2022-07-23 16:12:23 -070089generate!("aos::EventLoopRuntime")
Adam Snaider163800b2023-07-12 00:21:17 -040090generate!("aos::ExitHandle")
Adam Snaidercc8c2f72023-06-25 20:56:13 -070091generate!("aos::TimerForRust")
Brian Silverman9809c5f2022-07-23 16:12:23 -070092
93subclass!("aos::ApplicationFuture", RustApplicationFuture)
94
95extern_cpp_type!("aos::Configuration", crate::Configuration)
96extern_cpp_type!("aos::Channel", crate::Channel)
97extern_cpp_type!("aos::Node", crate::Node)
98extern_cpp_type!("aos::UUID", crate::UUID)
99);
100
Brian Silverman2ee175e2023-07-11 16:32:08 -0700101/// A marker type which is invariant with respect to the given lifetime.
102///
103/// When interacting with functions that take and return things with a given lifetime, the lifetime
104/// becomes invariant. Because we don't store these functions as Rust types, we need a type like
105/// this to tell the Rust compiler that it can't substitute a shorter _or_ longer lifetime.
106pub type InvariantLifetime<'a> = PhantomData<fn(&'a ()) -> &'a ()>;
107
Brian Silverman9809c5f2022-07-23 16:12:23 -0700108/// # Safety
109///
110/// This should have a `'event_loop` lifetime and `future` should include that in its type, but
111/// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is
112/// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which
113/// must be outlived by the EventLoop.
114#[doc(hidden)]
Austin Schuhdad7a812023-07-26 21:11:22 -0700115#[subclass]
Brian Silverman9809c5f2022-07-23 16:12:23 -0700116pub struct RustApplicationFuture {
117 /// This logically has a `'event_loop` bound, see the class comment for details.
118 future: Pin<Box<dyn Future<Output = Never>>>,
119}
120
121impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture {
Brian Silverman1431a772022-08-31 20:44:36 -0700122 fn Poll(&mut self) -> bool {
123 catch_unwind(AssertUnwindSafe(|| {
124 // This is always allowed because it can never create a value of type `Ready<Never>` to
125 // return, so it must always return `Pending`. That also means the value it returns doesn't
126 // mean anything, so we ignore it.
127 let _ = Pin::new(&mut self.future)
128 .poll(&mut std::task::Context::from_waker(&panic_waker()));
129 }))
130 .is_ok()
Brian Silverman9809c5f2022-07-23 16:12:23 -0700131 }
132}
133
134impl RustApplicationFuture {
135 pub fn new<'event_loop>(
136 future: impl Future<Output = Never> + 'event_loop,
137 ) -> UniquePtr<ffi::aos::ApplicationFuture> {
138 /// # Safety
139 ///
140 /// This completely removes the `'event_loop` lifetime, the caller must ensure that is
141 /// sound.
142 unsafe fn remove_lifetime<'event_loop>(
143 future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>,
144 ) -> Pin<Box<dyn Future<Output = Never>>> {
145 // SAFETY: Caller is responsible.
146 unsafe { std::mem::transmute(future) }
147 }
148
149 Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self {
150 // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for
151 // details.
152 future: unsafe { remove_lifetime(Box::pin(future)) },
153 cpp_peer: Default::default(),
154 }))
155 }
156}
157
Brian Silverman2ee175e2023-07-11 16:32:08 -0700158/// An abstraction for objects which hold an `aos::EventLoop` from Rust code.
159///
160/// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call
161/// [`EventLoopRuntime.new`] directly.
162///
163/// # Safety
164///
165/// Objects implementing this trait *must* have mostly-exclusive (except for running it) ownership
166/// of the `aos::EventLoop` *for its entire lifetime*, which *must* be dropped when this object is.
167/// See [`EventLoopRuntime.new`]'s safety requirements for why this can be important and details of
168/// mostly-exclusive. In other words, nothing else may mutate it in any way except processing events
169/// (including dropping, because this object has to be the one to drop it).
170///
Adam Snaider88097232023-10-17 18:43:14 -0700171/// This also implies semantics similar to `Pin<&mut CppEventLoop>` for the underlying object.
Brian Silverman2ee175e2023-07-11 16:32:08 -0700172/// Implementations of this trait must have exclusive ownership of it, and the underlying object
173/// must not be moved.
174pub unsafe trait EventLoopHolder {
175 /// Converts this holder into a raw C++ pointer. This may be fed through other Rust and C++
176 /// code, and eventually passed back to [`from_raw`].
Adam Snaider88097232023-10-17 18:43:14 -0700177 fn into_raw(self) -> *mut CppEventLoop;
Brian Silverman2ee175e2023-07-11 16:32:08 -0700178
179 /// Converts a raw C++ pointer back to a holder object.
180 ///
181 /// # Safety
182 ///
183 /// `raw` must be the result of [`into_raw`] on an instance of this same type. These raw
184 /// pointers *are not* interchangeable between implementations of this trait.
Adam Snaider88097232023-10-17 18:43:14 -0700185 unsafe fn from_raw(raw: *mut CppEventLoop) -> Self;
Brian Silverman2ee175e2023-07-11 16:32:08 -0700186}
187
188/// Owns an [`EventLoopRuntime`] and its underlying `aos::EventLoop`, with safe management of the
189/// associated Rust lifetimes.
190pub struct EventLoopRuntimeHolder<T: EventLoopHolder>(
191 ManuallyDrop<Pin<Box<CppEventLoopRuntime>>>,
192 PhantomData<T>,
193);
194
195impl<T: EventLoopHolder> EventLoopRuntimeHolder<T> {
196 /// Creates a new [`EventLoopRuntime`] and runs an initialization function on it. This is a
197 /// safe wrapper around [`EventLoopRuntime.new`] (although see [`EventLoopHolder`]'s safety
198 /// requirements, part of them are just delegated there).
199 ///
200 /// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call
201 /// [`EventLoopRuntime.new`] directly.
202 ///
203 /// All setup of the runtime must be performed with `fun`, which is called before this function
204 /// returns. `fun` may create further objects to use in async functions via [`EventLoop.spawn`]
205 /// etc, but it is the only place to set things up before the EventLoop is run.
206 ///
207 /// `fun` cannot capture things outside of the event loop, because the event loop might outlive
208 /// them:
209 /// ```compile_fail
210 /// # use aos_events_event_loop_runtime::*;
211 /// # fn bad(event_loop: impl EventLoopHolder) {
212 /// let mut x = 0;
213 /// EventLoopRuntimeHolder::new(event_loop, |runtime| {
214 /// runtime.spawn(async {
215 /// x = 1;
216 /// loop {}
217 /// });
218 /// });
219 /// # }
220 /// ```
221 ///
222 /// But it can capture `'event_loop` references:
223 /// ```
224 /// # use aos_events_event_loop_runtime::*;
225 /// # use aos_configuration::ChannelExt;
226 /// # fn good(event_loop: impl EventLoopHolder) {
227 /// EventLoopRuntimeHolder::new(event_loop, |runtime| {
228 /// let channel = runtime.get_raw_channel("/test", "aos.examples.Ping").unwrap();
229 /// runtime.spawn(async {
230 /// loop {
231 /// eprintln!("{:?}", channel.type_());
232 /// }
233 /// });
234 /// });
235 /// # }
236 /// ```
237 pub fn new<F>(event_loop: T, fun: F) -> Self
238 where
239 F: for<'event_loop> FnOnce(&mut EventLoopRuntime<'event_loop>),
240 {
241 // SAFETY: The EventLoopRuntime never escapes this function, which means the only code that
242 // observes its lifetime is `fun`. `fun` must be generic across any value of its
243 // `'event_loop` lifetime parameter, which means we can choose any lifetime here, which
244 // satisfies the safety requirements.
245 //
246 // This is a similar pattern as `std::thread::scope`, `ghost-cell`, etc. Note that unlike
247 // `std::thread::scope`, our inner functions (the async ones) are definitely not allowed to
248 // capture things from the calling scope of this function, so there's no `'env` equivalent.
249 // `ghost-cell` ends up looking very similar despite doing different things with the
250 // pattern, while `std::thread::scope` has a lot of additional complexity to achieve a
251 // similar result.
252 //
253 // `EventLoopHolder`s safety requirements prevent anybody else from touching the underlying
254 // `aos::EventLoop`.
255 let mut runtime = unsafe { EventLoopRuntime::new(event_loop.into_raw()) };
256 fun(&mut runtime);
257 Self(ManuallyDrop::new(runtime.into_cpp()), PhantomData)
258 }
259}
260
261impl<T: EventLoopHolder> Drop for EventLoopRuntimeHolder<T> {
262 fn drop(&mut self) {
Adam Snaider48a54682023-09-28 21:50:42 -0700263 let event_loop = self.0.event_loop();
Brian Silverman2ee175e2023-07-11 16:32:08 -0700264 // SAFETY: We're not going to touch this field again. The underlying EventLoop will not be
265 // run again because we're going to drop it next.
266 unsafe { ManuallyDrop::drop(&mut self.0) };
267 // SAFETY: We took this from `into_raw`, and we just dropped the runtime which may contain
268 // Rust references to it.
269 unsafe { drop(T::from_raw(event_loop)) };
270 }
271}
272
Brian Silverman9809c5f2022-07-23 16:12:23 -0700273pub struct EventLoopRuntime<'event_loop>(
Adam Snaider88097232023-10-17 18:43:14 -0700274 Pin<Box<CppEventLoopRuntime>>,
Brian Silverman2ee175e2023-07-11 16:32:08 -0700275 // See documentation of [`new`] for details.
276 InvariantLifetime<'event_loop>,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700277);
278
279/// Manages the Rust interface to a *single* `aos::EventLoop`. This is intended to be used by a
280/// single application.
281impl<'event_loop> EventLoopRuntime<'event_loop> {
Brian Silverman2ee175e2023-07-11 16:32:08 -0700282 /// Creates a new runtime. This must be the only user of the underlying `aos::EventLoop`.
283 ///
284 /// Consider using [`EventLoopRuntimeHolder.new`] instead, if you're working with an
285 /// `aos::EventLoop` owned (indirectly) by Rust code.
286 ///
287 /// One common pattern is calling this in the constructor of an object whose lifetime is managed
288 /// by C++; C++ doesn't inherit the Rust lifetime but we do have a lot of C++ code that obeys
289 /// these rules implicitly.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700290 ///
291 /// Call [`spawn`] to respond to events. The non-event-driven APIs may be used without calling
292 /// this.
293 ///
294 /// This is an async runtime, but it's a somewhat unusual one. See the module-level
295 /// documentation for details.
296 ///
297 /// # Safety
298 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700299 /// This function is where all the tricky lifetime guarantees to ensure soundness come
300 /// together. It all boils down to choosing `'event_loop` correctly, which is very complicated.
301 /// Here are the rules:
Brian Silverman9809c5f2022-07-23 16:12:23 -0700302 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700303 /// 1. The `aos::EventLoop` APIs, and any other consumer-facing APIs, of the underlying
304 /// `aos::EventLoop` *must* be exclusively used by this object, and things it calls, for
305 /// `'event_loop`.
306 /// 2. `'event_loop` extends until after the last time the underlying `aos::EventLoop` is run.
307 /// This is often beyond the lifetime of this Rust `EventLoopRuntime` object.
308 /// 3. `'event_loop` must outlive this object, because this object stores references to the
309 /// underlying `aos::EventLoop`.
310 /// 4. Any other references stored in the underlying `aos::EventLoop` must be valid for
311 /// `'event_loop`. The easiest way to ensure this is by not using the `aos::EventLoop` before
312 /// passing it to this object.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700313 ///
Brian Silverman2ee175e2023-07-11 16:32:08 -0700314 /// Here are some corollaries:
315 ///
316 /// 1. The underlying `aos::EventLoop` must be dropped after this object.
317 /// 2. This object will store various references valid for `'event_loop` with a duration of
318 /// `'event_loop`, which is safe as long as they're both the same `'event_loop`. Note that
319 /// this requires this type to be invariant with respect to `'event_loop`.
320 /// 3. `event_loop` (the pointer being passed in) is effectively `Pin`, which is also implied
321 /// by the underlying `aos::EventLoop` C++ type.
322 /// 4. You cannot create multiple `EventLoopRuntime`s from the same underlying `aos::EventLoop`
323 /// or otherwise use it from a different application. The first one may create
324 /// mutable Rust references while the second one expects exclusive ownership, for example.
325 ///
326 /// `aos::EventLoop`'s public API is exclusively for consumers of the event loop. Some
327 /// subclasses extend this API. Additionally, all useful implementations of `aos::EventLoop`
328 /// must have some way to process events. Sometimes this is additional API surface (such as
329 /// `aos::ShmEventLoop`), in other cases comes via other objects holding references to the
330 /// `aos::EventLoop` (such as `aos::SimulatedEventLoopFactory`). This access to run the event
331 /// loop functions independently of the consuming functions in every way except lifetime of the
332 /// `aos::EventLoop`, and may be used independently of `'event_loop`.
333 ///
334 /// ## Discussion of the rules
335 ///
336 /// Rule 1 is similar to rule 3 (they're both similar to mutable borrowing), but rule 1 extends
337 /// for the entire lifetime of the object instead of being limited to the lifetime of an
338 /// individual borrow by an instance of this type. This is similar to the way [`Pin`]'s
339 /// estrictions extend for the entire lifetime of the object, until it is dropped.
340 ///
341 /// Rule 2 and corollaries 2 and 3 go together, and are essential for making [`spawn`]ed tasks
342 /// useful. The `aos::EventLoop` is full of indirect circular references, both within itself
343 /// and via all of the callbacks. This is sound if all of these references have the *exact
344 /// same* Rust lifetime, which is `'event_loop`.
345 ///
346 /// ## Alternatives and why they don't work
347 ///
348 /// Making the argument `Pin<&'event_loop mut EventLoop>` would express some (but not all) of
349 /// these restrictions within the Rust type system. However, having an actual Rust mutable
350 /// reference like that prevents anything else from creating one via other pointers to the
351 /// same object from C++, which is a common operation. See the module-level documentation for
352 /// details.
353 ///
354 /// [`spawn`]ed tasks need to hold `&'event_loop` references to things like channels. Using a
355 /// separate `'config` lifetime wouldn't change much; the tasks still need to do things which
356 /// require them to not outlive something they don't control. This is fundamental to
357 /// self-referential objects, which `aos::EventLoop` is based around, but Rust requires unsafe
358 /// code to manage manually.
359 ///
360 /// ## Final cautions
361 ///
362 /// Following these rules is very tricky. Be very cautious calling this function. It exposes an
363 /// unbound lifetime, which means you should wrap it directly in a function that attaches a
364 /// correct lifetime.
Adam Snaider88097232023-10-17 18:43:14 -0700365 pub unsafe fn new(event_loop: *mut CppEventLoop) -> Self {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700366 Self(
367 // SAFETY: We push all the validity requirements for this up to our caller.
Adam Snaider88097232023-10-17 18:43:14 -0700368 unsafe { CppEventLoopRuntime::new(event_loop) }.within_box(),
Brian Silverman2ee175e2023-07-11 16:32:08 -0700369 InvariantLifetime::default(),
Brian Silverman9809c5f2022-07-23 16:12:23 -0700370 )
371 }
372
Brian Silverman2ee175e2023-07-11 16:32:08 -0700373 /// Creates a Rust wrapper from the underlying C++ object, with an unbound lifetime.
374 ///
375 /// This may never be useful, but it's here for this big scary comment to explain why it's not
376 /// useful.
377 ///
378 /// # Safety
379 ///
380 /// See [`new`] for safety restrictions on `'event_loop` when calling this. In particular, see
381 /// the note about how tricky doing this correctly is, and remember that for this function the
382 /// event loop in question isn't even an argument to this function so it's even trickier. Also
383 /// note that you cannot call this on the result of [`into_cpp`] without violating those
384 /// restrictions.
Adam Snaider88097232023-10-17 18:43:14 -0700385 pub unsafe fn from_cpp(cpp: Pin<Box<CppEventLoopRuntime>>) -> Self {
Brian Silverman2ee175e2023-07-11 16:32:08 -0700386 Self(cpp, InvariantLifetime::default())
387 }
388
389 /// Extracts the underlying C++ object, without the corresponding Rust lifetime. This is useful
390 /// to stop the propagation of Rust lifetimes without destroying the underlying object which
391 /// contains all the state.
392 ///
393 /// Note that you *cannot* call [`from_cpp`] on the result of this, because that will violate
394 /// [`from_cpp`]'s safety requirements.
Adam Snaider88097232023-10-17 18:43:14 -0700395 pub fn into_cpp(self) -> Pin<Box<CppEventLoopRuntime>> {
Brian Silverman2ee175e2023-07-11 16:32:08 -0700396 self.0
397 }
398
Brian Silverman9809c5f2022-07-23 16:12:23 -0700399 /// Returns the pointer passed into the constructor.
400 ///
401 /// The returned value should only be used for destroying it (_after_ `self` is dropped) or
402 /// calling other C++ APIs.
Adam Snaider88097232023-10-17 18:43:14 -0700403 pub fn raw_event_loop(&self) -> *mut CppEventLoop {
Adam Snaider48a54682023-09-28 21:50:42 -0700404 self.0.event_loop()
Brian Silverman9809c5f2022-07-23 16:12:23 -0700405 }
406
Brian Silverman90221f82022-08-22 23:46:09 -0700407 /// Returns a reference to the name of this EventLoop.
408 ///
409 /// TODO(Brian): Come up with a nice way to expose this safely, without memory allocations, for
410 /// logging etc.
411 ///
412 /// # Safety
413 ///
414 /// The result must not be used after C++ could change it. Unfortunately C++ can change this
415 /// name from most places, so you should be really careful what you do with the result.
416 pub unsafe fn raw_name(&self) -> &str {
417 self.0.name()
418 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700419
420 pub fn get_raw_channel(
421 &self,
422 name: &str,
423 typename: &str,
Brian Silverman9809c5f2022-07-23 16:12:23 -0700424 ) -> Result<&'event_loop Channel, ChannelLookupError> {
Brian Silverman90221f82022-08-22 23:46:09 -0700425 self.configuration().get_channel(
426 name,
427 typename,
428 // SAFETY: We're not calling any EventLoop methods while C++ is using this for the
429 // channel lookup.
430 unsafe { self.raw_name() },
431 self.node(),
432 )
Brian Silverman9809c5f2022-07-23 16:12:23 -0700433 }
434
Brian Silverman90221f82022-08-22 23:46:09 -0700435 pub fn get_channel<T: FullyQualifiedName>(
436 &self,
437 name: &str,
438 ) -> Result<&'event_loop Channel, ChannelLookupError> {
439 self.get_raw_channel(name, T::get_fully_qualified_name())
440 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700441
442 /// Starts running the given `task`, which may not return (as specified by its type). If you
443 /// want your task to stop, return the result of awaiting [`futures::future::pending`], which
444 /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits.
445 ///
Brian Silverman76f48362022-08-24 21:09:08 -0700446 /// Note that task will be polled immediately, to give it a chance to initialize. If you want to
447 /// defer work until the event loop starts running, await [`on_run`] in the task.
Brian Silverman9809c5f2022-07-23 16:12:23 -0700448 ///
449 /// # Panics
450 ///
451 /// Panics if called more than once. See the module-level documentation for alternatives if you
452 /// want to do this.
453 ///
454 /// # Examples with interesting return types
455 ///
456 /// These are all valid futures which never return:
457 /// ```
458 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
459 /// # use futures::{never::Never, future::pending};
460 /// async fn pending_wrapper() -> Never {
461 /// pending().await
462 /// }
463 /// async fn loop_forever() -> Never {
464 /// loop {}
465 /// }
466 ///
467 /// runtime.spawn(pending());
468 /// runtime.spawn(async { pending().await });
469 /// runtime.spawn(pending_wrapper());
470 /// runtime.spawn(async { loop {} });
471 /// runtime.spawn(loop_forever());
472 /// runtime.spawn(async { println!("all done"); pending().await });
473 /// # }
474 /// ```
475 /// but this is not:
476 /// ```compile_fail
477 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
478 /// # use futures::ready;
479 /// runtime.spawn(ready());
480 /// # }
481 /// ```
482 /// and neither is this:
483 /// ```compile_fail
484 /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) {
485 /// # use futures::ready;
486 /// runtime.spawn(async { println!("all done") });
487 /// # }
488 /// ```
489 ///
490 /// # Examples with capturing
491 ///
492 /// The future can capture things. This is important to access other objects created from the
493 /// runtime, either before calling this function:
494 /// ```
495 /// # fn compile_check<'event_loop>(
496 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
497 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
498 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
499 /// # ) {
500 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
501 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
502 /// runtime.spawn(async move { loop {
503 /// watcher1.next().await;
504 /// watcher2.next().await;
505 /// }});
506 /// # }
507 /// ```
508 /// or after:
509 /// ```
510 /// # fn compile_check<'event_loop>(
511 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
512 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
513 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
514 /// # ) {
515 /// # use std::{cell::RefCell, rc::Rc};
516 /// let runtime = Rc::new(RefCell::new(runtime));
517 /// runtime.borrow_mut().spawn({
518 /// let mut runtime = runtime.clone();
519 /// async move {
520 /// let mut runtime = runtime.borrow_mut();
521 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
522 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
523 /// loop {
524 /// watcher1.next().await;
525 /// watcher2.next().await;
526 /// }
527 /// }
528 /// });
529 /// # }
530 /// ```
531 /// or both:
532 /// ```
533 /// # fn compile_check<'event_loop>(
534 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
535 /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel,
536 /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel,
537 /// # ) {
538 /// # use std::{cell::RefCell, rc::Rc};
539 /// let mut watcher1 = runtime.make_raw_watcher(channel1);
540 /// let runtime = Rc::new(RefCell::new(runtime));
541 /// runtime.borrow_mut().spawn({
542 /// let mut runtime = runtime.clone();
543 /// async move {
544 /// let mut runtime = runtime.borrow_mut();
545 /// let mut watcher2 = runtime.make_raw_watcher(channel2);
546 /// loop {
547 /// watcher1.next().await;
548 /// watcher2.next().await;
549 /// }
550 /// }
551 /// });
552 /// # }
553 /// ```
554 ///
555 /// But you cannot capture local variables:
556 /// ```compile_fail
557 /// # fn compile_check<'event_loop>(
558 /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>,
559 /// # ) {
560 /// let mut local: i32 = 971;
561 /// let local = &mut local;
562 /// runtime.spawn(async move { loop {
563 /// println!("have: {}", local);
564 /// }});
565 /// # }
566 /// ```
Adam Snaider48a54682023-09-28 21:50:42 -0700567 pub fn spawn(&self, task: impl Future<Output = Never> + 'event_loop) {
568 self.0.Spawn(RustApplicationFuture::new(task));
Brian Silverman9809c5f2022-07-23 16:12:23 -0700569 }
570
571 pub fn configuration(&self) -> &'event_loop Configuration {
572 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop.
573 unsafe { &*self.0.configuration() }
574 }
575
576 pub fn node(&self) -> Option<&'event_loop Node> {
577 // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null.
578 unsafe { self.0.node().as_ref() }
579 }
580
581 pub fn monotonic_now(&self) -> MonotonicInstant {
582 MonotonicInstant(self.0.monotonic_now())
583 }
584
Ryan Yin683a8672022-11-09 20:44:20 -0800585 pub fn realtime_now(&self) -> RealtimeInstant {
586 RealtimeInstant(self.0.realtime_now())
587 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700588 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
589 /// part of `self.configuration()`, which will always have this lifetime.
590 ///
591 /// # Panics
592 ///
593 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700594 pub fn make_raw_watcher(&self, channel: &'event_loop Channel) -> RawWatcher {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700595 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
596 // the usual autocxx heuristics.
Adam Snaider48a54682023-09-28 21:50:42 -0700597 RawWatcher(unsafe { self.0.MakeWatcher(channel) }.within_box())
Brian Silverman9809c5f2022-07-23 16:12:23 -0700598 }
599
Brian Silverman90221f82022-08-22 23:46:09 -0700600 /// Provides type-safe async blocking access to messages on a channel. `T` should be a
601 /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static`
602 /// is easiest.
603 ///
604 /// # Panics
605 ///
606 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700607 pub fn make_watcher<T>(&self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError>
Brian Silverman90221f82022-08-22 23:46:09 -0700608 where
609 for<'a> T: FollowWith<'a>,
610 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
611 T: FullyQualifiedName,
612 {
613 let channel = self.get_channel::<T>(channel_name)?;
614 Ok(Watcher(self.make_raw_watcher(channel), PhantomData))
615 }
616
Brian Silverman9809c5f2022-07-23 16:12:23 -0700617 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
618 /// part of `self.configuration()`, which will always have this lifetime.
619 ///
620 /// # Panics
621 ///
622 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700623 pub fn make_raw_sender(&self, channel: &'event_loop Channel) -> RawSender {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700624 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
625 // the usual autocxx heuristics.
Adam Snaider48a54682023-09-28 21:50:42 -0700626 RawSender(unsafe { self.0.MakeSender(channel) }.within_box())
Brian Silverman9809c5f2022-07-23 16:12:23 -0700627 }
628
Brian Silverman90221f82022-08-22 23:46:09 -0700629 /// Allows sending messages on a channel with a type-safe API.
630 ///
631 /// # Panics
632 ///
633 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700634 pub fn make_sender<T>(&self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError>
Brian Silverman90221f82022-08-22 23:46:09 -0700635 where
636 for<'a> T: FollowWith<'a>,
637 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
638 T: FullyQualifiedName,
639 {
640 let channel = self.get_channel::<T>(channel_name)?;
641 Ok(Sender(self.make_raw_sender(channel), PhantomData))
642 }
643
Brian Silverman9809c5f2022-07-23 16:12:23 -0700644 /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is
645 /// part of `self.configuration()`, which will always have this lifetime.
646 ///
647 /// # Panics
648 ///
649 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700650 pub fn make_raw_fetcher(&self, channel: &'event_loop Channel) -> RawFetcher {
Brian Silverman9809c5f2022-07-23 16:12:23 -0700651 // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under
652 // the usual autocxx heuristics.
Adam Snaider48a54682023-09-28 21:50:42 -0700653 RawFetcher(unsafe { self.0.MakeFetcher(channel) }.within_box())
Brian Silverman9809c5f2022-07-23 16:12:23 -0700654 }
655
Brian Silverman90221f82022-08-22 23:46:09 -0700656 /// Provides type-safe access to messages on a channel, without the ability to wait for a new
657 /// one. This provides APIs to get the latest message, and to follow along and retrieve each
658 /// message in order.
659 ///
660 /// # Panics
661 ///
662 /// Dropping `self` before the returned object is dropped will panic.
Adam Snaider48a54682023-09-28 21:50:42 -0700663 pub fn make_fetcher<T>(&self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError>
Brian Silverman90221f82022-08-22 23:46:09 -0700664 where
665 for<'a> T: FollowWith<'a>,
666 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
667 T: FullyQualifiedName,
668 {
669 let channel = self.get_channel::<T>(channel_name)?;
670 Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData))
671 }
672
Brian Silverman9809c5f2022-07-23 16:12:23 -0700673 // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those,
674 // instead of / in addition to mirroring C++ with separate setup and wait?
675
Brian Silverman76f48362022-08-24 21:09:08 -0700676 /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all
677 /// subsequent code will have any realtime scheduling applied. This means it can rely on
678 /// consistent timing, but it can no longer create any EventLoop child objects or do anything
679 /// else non-realtime.
Adam Snaider48a54682023-09-28 21:50:42 -0700680 pub fn on_run(&self) -> OnRun {
681 OnRun(self.0.MakeOnRun().within_box())
Brian Silverman76f48362022-08-24 21:09:08 -0700682 }
683
684 pub fn is_running(&self) -> bool {
685 self.0.is_running()
686 }
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700687
688 /// Returns an unarmed timer.
Adam Snaider48a54682023-09-28 21:50:42 -0700689 pub fn add_timer(&self) -> Timer {
690 Timer(self.0.AddTimer())
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700691 }
692
693 /// Returns a timer that goes off every `duration`-long ticks.
Adam Snaider48a54682023-09-28 21:50:42 -0700694 pub fn add_interval(&self, duration: Duration) -> Timer {
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700695 let mut timer = self.add_timer();
696 timer.setup(self.monotonic_now(), Some(duration));
697 timer
698 }
Adam Snaidercf0dac72023-10-02 14:41:58 -0700699
700 /// Sets the scheduler priority to run the event loop at.
701 pub fn set_realtime_priority(&self, priority: i32) {
702 self.0.SetRuntimeRealtimePriority(priority.into());
703 }
Adam Snaidercc8c2f72023-06-25 20:56:13 -0700704}
705
706/// An event loop primitive that allows sleeping asynchronously.
707///
708/// # Examples
709///
710/// ```no_run
711/// # use aos_events_event_loop_runtime::EventLoopRuntime;
712/// # use std::time::Duration;
713/// # fn compile_check(runtime: &mut EventLoopRuntime<'_>) {
714/// # let mut timer = runtime.add_timer();
715/// // Goes as soon as awaited.
716/// timer.setup(runtime.monotonic_now(), None);
717/// // Goes off once in 2 seconds.
718/// timer.setup(runtime.monotonic_now() + Duration::from_secs(2), None);
719/// // Goes off as soon as awaited and every 2 seconds afterwards.
720/// timer.setup(runtime.monotonic_now(), Some(Duration::from_secs(1)));
721/// async {
722/// for i in 0..10 {
723/// timer.tick().await;
724/// }
725/// // Timer won't off anymore. Next `tick` will never return.
726/// timer.disable();
727/// timer.tick().await;
728/// };
729/// # }
730/// ```
731pub struct Timer(UniquePtr<ffi::aos::TimerForRust>);
732
733/// A "tick" for a [`Timer`].
734///
735/// This is the raw future generated by the [`Timer::tick`] function.
736pub struct TimerTick<'a>(&'a mut Timer);
737
738impl Timer {
739 /// Arms the timer.
740 ///
741 /// The timer should sleep until `base`, `base + repeat`, `base + repeat * 2`, ...
742 /// If `repeat` is `None`, then the timer only expires once at `base`.
743 pub fn setup(&mut self, base: MonotonicInstant, repeat: Option<Duration>) {
744 self.0.pin_mut().Schedule(
745 base.0,
746 repeat
747 .unwrap_or(Duration::from_nanos(0))
748 .as_nanos()
749 .try_into()
750 .expect("Out of range: Internal clock uses 64 bits"),
751 );
752 }
753
754 /// Disarms the timer.
755 ///
756 /// Can be re-enabled by calling `setup` again.
757 pub fn disable(&mut self) {
758 self.0.pin_mut().Disable();
759 }
760
761 /// Returns `true` if the timer is enabled.
762 pub fn is_enabled(&self) -> bool {
763 !self.0.IsDisabled()
764 }
765
766 /// Sets the name of the timer.
767 ///
768 /// This can be useful to get a descriptive name in the timing reports.
769 pub fn set_name(&mut self, name: &str) {
770 self.0.pin_mut().set_name(name);
771 }
772
773 /// Gets the name of the timer.
774 pub fn name(&self) -> &str {
775 self.0.name()
776 }
777
778 /// Returns a tick which can be `.await`ed.
779 ///
780 /// This tick will resolve on the next timer expired.
781 pub fn tick(&mut self) -> TimerTick {
782 TimerTick(self)
783 }
784
785 /// Polls the timer, returning `[Poll::Ready]` only once the timer expired.
786 fn poll(&mut self) -> Poll<()> {
787 if self.0.pin_mut().Poll() {
788 Poll::Ready(())
789 } else {
790 Poll::Pending
791 }
792 }
793}
794
795impl Future for TimerTick<'_> {
796 type Output = ();
797
798 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
799 self.0.poll()
800 }
Brian Silverman9809c5f2022-07-23 16:12:23 -0700801}
802
Brian Silverman9809c5f2022-07-23 16:12:23 -0700803/// Provides async blocking access to messages on a channel. This will return every message on the
804/// channel, in order.
805///
806/// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these.
807///
808/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
809/// for actually interpreting messages. You probably want a [`Watcher`] instead.
810///
811/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
812/// reasons.
813///
814/// # Design
815///
816/// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means
817/// it's different for each `self` lifetime so we can't write a single type alias for it. We could
818/// write an intermediate type with a generic lifetime that implements `Stream` and is returned
819/// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding
820/// another level doesn't help anything.
821///
822/// We also drop the extraneous `cx` argument that isn't used by this implementation anyways.
823///
824/// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's
825/// the same one mentioned here:
826/// 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
827/// We get around that one by moving the unbounded lifetime from the pointer dereference into the
828/// function with the if statement.
Brian Silverman90221f82022-08-22 23:46:09 -0700829// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
830#[repr(transparent)]
831pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>);
832
Brian Silverman9809c5f2022-07-23 16:12:23 -0700833impl RawWatcher {
834 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
835 /// without skipping any messages.
836 ///
837 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
838 /// will need to call this function again to get the succeeding message.
839 ///
840 /// # Examples
841 ///
842 /// The common use case is immediately awaiting the next message:
843 /// ```
844 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
845 /// println!("received: {:?}", watcher.next().await);
846 /// # }
847 /// ```
848 ///
849 /// You can also await the first message from any of a set of channels:
850 /// ```
851 /// # async fn select(
852 /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher,
853 /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher,
854 /// # ) {
855 /// futures::select! {
856 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
857 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
858 /// }
859 /// # }
860 /// ```
861 ///
862 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
863 /// enforce only having a single of these returned objects at a time. Drop the previous message
864 /// before asking for the next one. That means this will not compile:
865 /// ```compile_fail
866 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
867 /// let first = watcher.next();
868 /// let second = watcher.next();
869 /// first.await;
870 /// # }
871 /// ```
872 /// and nor will this:
873 /// ```compile_fail
874 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
875 /// let first = watcher.next().await;
876 /// watcher.next();
877 /// println!("still have: {:?}", first);
878 /// # }
879 /// ```
880 /// but this is fine:
881 /// ```
882 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) {
883 /// let first = watcher.next().await;
884 /// println!("have: {:?}", first);
885 /// watcher.next();
886 /// # }
887 /// ```
888 pub fn next(&mut self) -> RawWatcherNext {
889 RawWatcherNext(Some(self))
890 }
891}
892
893/// The type returned from [`RawWatcher::next`], see there for details.
894pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>);
895
896impl<'a> Future for RawWatcherNext<'a> {
897 type Output = Context<'a>;
898 fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> {
899 let inner = self
900 .0
901 .take()
902 .expect("May not call poll after it returns Ready");
903 let maybe_context = inner.0.as_mut().PollNext();
904 if maybe_context.is_null() {
905 // We're not returning a reference into it, so we can safely replace the reference to
906 // use again in the future.
907 self.0.replace(inner);
908 Poll::Pending
909 } else {
910 // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will
911 // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`)
912 // because we're dropping `inner` (which is that reference), so it will need to be
913 // borrowed again which cannot happen before the end of `'a`.
914 Poll::Ready(Context(unsafe { &*maybe_context }))
915 }
916 }
917}
918
919impl FusedFuture for RawWatcherNext<'_> {
920 fn is_terminated(&self) -> bool {
921 self.0.is_none()
922 }
923}
924
Brian Silverman90221f82022-08-22 23:46:09 -0700925/// Provides async blocking access to messages on a channel. This will return every message on the
926/// channel, in order.
927///
928/// Use [`EventLoopRuntime::make_watcher`] to create one of these.
929///
930/// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical
931/// reasons. See [`RawWatcher`]'s documentation for details.
932pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>)
933where
934 for<'a> T: FollowWith<'a>,
935 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
936
937impl<T> Watcher<T>
938where
939 for<'a> T: FollowWith<'a>,
940 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
941{
942 /// Returns a Future to await the next value. This can be canceled (ie dropped) at will,
943 /// without skipping any messages.
944 ///
945 /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You
946 /// will need to call this function again to get the succeeding message.
947 ///
948 /// # Examples
949 ///
950 /// The common use case is immediately awaiting the next message:
951 /// ```
952 /// # use pong_rust_fbs::aos::examples::Pong;
953 /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
954 /// println!("received: {:?}", watcher.next().await);
955 /// # }
956 /// ```
957 ///
958 /// You can also await the first message from any of a set of channels:
959 /// ```
960 /// # use pong_rust_fbs::aos::examples::Pong;
961 /// # async fn select(
962 /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
963 /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>,
964 /// # ) {
965 /// futures::select! {
966 /// message1 = watcher1.next() => println!("channel 1: {:?}", message1),
967 /// message2 = watcher2.next() => println!("channel 2: {:?}", message2),
968 /// }
969 /// # }
970 /// ```
971 ///
972 /// Note that due to the returned object borrowing the `self` reference, the borrow checker will
973 /// enforce only having a single of these returned objects at a time. Drop the previous message
974 /// before asking for the next one. That means this will not compile:
975 /// ```compile_fail
976 /// # use pong_rust_fbs::aos::examples::Pong;
977 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
978 /// let first = watcher.next();
979 /// let second = watcher.next();
980 /// first.await;
981 /// # }
982 /// ```
983 /// and nor will this:
984 /// ```compile_fail
985 /// # use pong_rust_fbs::aos::examples::Pong;
986 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
987 /// let first = watcher.next().await;
988 /// watcher.next();
989 /// println!("still have: {:?}", first);
990 /// # }
991 /// ```
992 /// but this is fine:
993 /// ```
994 /// # use pong_rust_fbs::aos::examples::Pong;
995 /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) {
996 /// let first = watcher.next().await;
997 /// println!("have: {:?}", first);
998 /// watcher.next();
999 /// # }
1000 /// ```
1001 pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> {
1002 WatcherNext(self.0.next(), PhantomData)
1003 }
1004}
1005
1006/// The type returned from [`Watcher::next`], see there for details.
1007pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>)
1008where
1009 T: Follow<'watcher> + 'watcher;
1010
1011impl<'watcher, T> Future for WatcherNext<'watcher, T>
1012where
1013 T: Follow<'watcher> + 'watcher,
1014{
1015 type Output = TypedContext<'watcher, T>;
1016
1017 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
1018 Pin::new(&mut self.get_mut().0).poll(cx).map(|context|
1019 // SAFETY: The Watcher this was created from verified that the channel is the
1020 // right type, and the C++ guarantees that the buffer's type matches.
1021 TypedContext(context, PhantomData))
1022 }
1023}
1024
1025impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T>
1026where
1027 T: Follow<'watcher> + 'watcher,
1028{
1029 fn is_terminated(&self) -> bool {
1030 self.0.is_terminated()
1031 }
1032}
1033
1034/// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type.
1035pub struct TypedContext<'a, T>(
1036 // SAFETY: This must have a message, and it must be a valid `T` flatbuffer.
1037 Context<'a>,
1038 PhantomData<*mut T>,
1039)
1040where
1041 T: Follow<'a> + 'a;
1042
Brian Silverman90221f82022-08-22 23:46:09 -07001043impl<'a, T> TypedContext<'a, T>
1044where
1045 T: Follow<'a> + 'a,
1046{
1047 pub fn message(&self) -> Option<T::Inner> {
1048 self.0.data().map(|data| {
1049 // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right
1050 // type based on invariants for our type.
1051 unsafe { root_unchecked::<T>(data) }
1052 })
1053 }
1054
1055 pub fn monotonic_event_time(&self) -> MonotonicInstant {
1056 self.0.monotonic_event_time()
1057 }
1058 pub fn monotonic_remote_time(&self) -> MonotonicInstant {
1059 self.0.monotonic_remote_time()
1060 }
Ryan Yin683a8672022-11-09 20:44:20 -08001061 pub fn realtime_event_time(&self) -> RealtimeInstant {
1062 self.0.realtime_event_time()
1063 }
1064 pub fn realtime_remote_time(&self) -> RealtimeInstant {
1065 self.0.realtime_remote_time()
1066 }
Brian Silverman90221f82022-08-22 23:46:09 -07001067 pub fn queue_index(&self) -> u32 {
1068 self.0.queue_index()
1069 }
1070 pub fn remote_queue_index(&self) -> u32 {
1071 self.0.remote_queue_index()
1072 }
1073 pub fn buffer_index(&self) -> i32 {
1074 self.0.buffer_index()
1075 }
1076 pub fn source_boot_uuid(&self) -> &Uuid {
1077 self.0.source_boot_uuid()
1078 }
1079}
1080
1081impl<'a, T> fmt::Debug for TypedContext<'a, T>
1082where
1083 T: Follow<'a> + 'a,
1084 T::Inner: fmt::Debug,
1085{
1086 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman90221f82022-08-22 23:46:09 -07001087 f.debug_struct("TypedContext")
1088 .field("monotonic_event_time", &self.monotonic_event_time())
1089 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -08001090 .field("realtime_event_time", &self.realtime_event_time())
1091 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman90221f82022-08-22 23:46:09 -07001092 .field("queue_index", &self.queue_index())
1093 .field("remote_queue_index", &self.remote_queue_index())
1094 .field("message", &self.message())
1095 .field("buffer_index", &self.buffer_index())
1096 .field("source_boot_uuid", &self.source_boot_uuid())
1097 .finish()
1098 }
1099}
Brian Silverman9809c5f2022-07-23 16:12:23 -07001100
1101/// Provides access to messages on a channel, without the ability to wait for a new one. This
Brian Silverman90221f82022-08-22 23:46:09 -07001102/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
Brian Silverman9809c5f2022-07-23 16:12:23 -07001103///
1104/// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these.
1105///
1106/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
1107/// for actually interpreting messages. You probably want a [`Fetcher`] instead.
Brian Silverman90221f82022-08-22 23:46:09 -07001108// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1109#[repr(transparent)]
1110pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>);
1111
Brian Silverman9809c5f2022-07-23 16:12:23 -07001112impl RawFetcher {
1113 pub fn fetch_next(&mut self) -> bool {
1114 self.0.as_mut().FetchNext()
1115 }
1116
1117 pub fn fetch(&mut self) -> bool {
1118 self.0.as_mut().Fetch()
1119 }
1120
1121 pub fn context(&self) -> Context {
1122 Context(self.0.context())
1123 }
1124}
1125
Brian Silverman90221f82022-08-22 23:46:09 -07001126/// Provides access to messages on a channel, without the ability to wait for a new one. This
1127/// provides APIs to get the latest message, and to follow along and retrieve each message in order.
1128///
1129/// Use [`EventLoopRuntime::make_fetcher`] to create one of these.
1130pub struct Fetcher<T>(
1131 // SAFETY: This must produce messages of type `T`.
1132 RawFetcher,
1133 PhantomData<*mut T>,
1134)
1135where
1136 for<'a> T: FollowWith<'a>,
1137 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1138
1139impl<T> Fetcher<T>
1140where
1141 for<'a> T: FollowWith<'a>,
1142 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1143{
1144 pub fn fetch_next(&mut self) -> bool {
1145 self.0.fetch_next()
1146 }
1147 pub fn fetch(&mut self) -> bool {
1148 self.0.fetch()
1149 }
1150
1151 pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> {
1152 // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's
1153 // type matches.
1154 TypedContext(self.0.context(), PhantomData)
1155 }
1156}
Brian Silverman9809c5f2022-07-23 16:12:23 -07001157
1158/// Allows sending messages on a channel.
1159///
1160/// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs
1161/// for actually creating messages to send. You probably want a [`Sender`] instead.
1162///
1163/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
Brian Silverman90221f82022-08-22 23:46:09 -07001164// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1165#[repr(transparent)]
1166pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>);
1167
Brian Silverman9809c5f2022-07-23 16:12:23 -07001168impl RawSender {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001169 /// Returns an object which can be used to build a message.
1170 ///
1171 /// # Examples
1172 ///
1173 /// ```
1174 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1175 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1176 /// # unsafe {
1177 /// let mut builder = sender.make_builder();
1178 /// let pong = PongBuilder::new(builder.fbb()).finish();
1179 /// builder.send(pong);
1180 /// # }
1181 /// # }
1182 /// ```
1183 ///
1184 /// You can bail out of building a message and build another one:
1185 /// ```
1186 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1187 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1188 /// # unsafe {
1189 /// let mut builder1 = sender.make_builder();
1190 /// builder1.fbb();
Adam Snaider0126d832023-10-03 09:59:34 -07001191 /// drop(builder1);
Brian Silverman9809c5f2022-07-23 16:12:23 -07001192 /// let mut builder2 = sender.make_builder();
1193 /// let pong = PongBuilder::new(builder2.fbb()).finish();
1194 /// builder2.send(pong);
1195 /// # }
1196 /// # }
1197 /// ```
1198 /// but you cannot build two messages at the same time with a single builder:
1199 /// ```compile_fail
1200 /// # use pong_rust_fbs::aos::examples::PongBuilder;
1201 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) {
1202 /// # unsafe {
1203 /// let mut builder1 = sender.make_builder();
1204 /// let mut builder2 = sender.make_builder();
1205 /// PongBuilder::new(builder2.fbb()).finish();
1206 /// PongBuilder::new(builder1.fbb()).finish();
1207 /// # }
1208 /// # }
1209 /// ```
1210 pub fn make_builder(&mut self) -> RawBuilder {
Adam Snaider34072e12023-10-03 10:04:25 -07001211 // SAFETY: This is a valid slice, and `u8` doesn't have any alignment
1212 // requirements. Additionally, the lifetime of the builder is tied to
1213 // the lifetime of self so the buffer won't be accessible again until
1214 // the builder is destroyed.
1215 let allocator = ChannelPreallocatedAllocator::new(unsafe {
1216 slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size())
1217 });
1218 let fbb = FlatBufferBuilder::new_in(allocator);
Brian Silverman9809c5f2022-07-23 16:12:23 -07001219 RawBuilder {
1220 raw_sender: self,
1221 fbb,
1222 }
1223 }
1224}
1225
Brian Silverman9809c5f2022-07-23 16:12:23 -07001226/// Used for building a message. See [`RawSender::make_builder`] for details.
1227pub struct RawBuilder<'sender> {
1228 raw_sender: &'sender mut RawSender,
Adam Snaider34072e12023-10-03 10:04:25 -07001229 fbb: FlatBufferBuilder<'sender, ChannelPreallocatedAllocator<'sender>>,
Brian Silverman9809c5f2022-07-23 16:12:23 -07001230}
1231
1232impl<'sender> RawBuilder<'sender> {
Adam Snaider34072e12023-10-03 10:04:25 -07001233 pub fn fbb(
1234 &mut self,
1235 ) -> &mut FlatBufferBuilder<'sender, ChannelPreallocatedAllocator<'sender>> {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001236 &mut self.fbb
1237 }
1238
1239 /// # Safety
1240 ///
1241 /// `T` must match the type of the channel of the sender this builder was created from.
1242 pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> {
1243 self.fbb.finish_minimal(root);
1244 let data = self.fbb.finished_data();
1245
1246 use ffi::aos::RawSender_Error as FfiError;
1247 // SAFETY: This is a valid buffer we're passing.
Adam Snaider4769bb42023-11-22 11:01:46 -08001248 match unsafe { self.raw_sender.0.as_mut().SendBuffer(data.len()) } {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001249 FfiError::kOk => Ok(()),
1250 FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast),
1251 FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone),
1252 }
1253 }
1254}
1255
Brian Silverman90221f82022-08-22 23:46:09 -07001256/// Allows sending messages on a channel with a type-safe API.
1257///
1258/// Use [`EventLoopRuntime::make_raw_sender`] to create one of these.
1259pub struct Sender<T>(
1260 // SAFETY: This must accept messages of type `T`.
1261 RawSender,
1262 PhantomData<*mut T>,
1263)
1264where
1265 for<'a> T: FollowWith<'a>,
1266 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1267
1268impl<T> Sender<T>
1269where
1270 for<'a> T: FollowWith<'a>,
1271 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1272{
1273 /// Returns an object which can be used to build a message.
1274 ///
1275 /// # Examples
1276 ///
1277 /// ```
1278 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1279 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1280 /// let mut builder = sender.make_builder();
1281 /// let pong = PongBuilder::new(builder.fbb()).finish();
1282 /// builder.send(pong);
1283 /// # }
1284 /// ```
1285 ///
1286 /// You can bail out of building a message and build another one:
1287 /// ```
1288 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1289 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1290 /// let mut builder1 = sender.make_builder();
1291 /// builder1.fbb();
Adam Snaider0126d832023-10-03 09:59:34 -07001292 /// drop(builder1);
Brian Silverman90221f82022-08-22 23:46:09 -07001293 /// let mut builder2 = sender.make_builder();
1294 /// let pong = PongBuilder::new(builder2.fbb()).finish();
1295 /// builder2.send(pong);
1296 /// # }
1297 /// ```
1298 /// but you cannot build two messages at the same time with a single builder:
1299 /// ```compile_fail
1300 /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder};
1301 /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) {
1302 /// let mut builder1 = sender.make_builder();
1303 /// let mut builder2 = sender.make_builder();
1304 /// PongBuilder::new(builder2.fbb()).finish();
1305 /// PongBuilder::new(builder1.fbb()).finish();
1306 /// # }
1307 /// ```
1308 pub fn make_builder(&mut self) -> Builder<T> {
1309 Builder(self.0.make_builder(), PhantomData)
1310 }
1311}
1312
1313/// Used for building a message. See [`Sender::make_builder`] for details.
1314pub struct Builder<'sender, T>(
1315 // SAFETY: This must accept messages of type `T`.
1316 RawBuilder<'sender>,
1317 PhantomData<*mut T>,
1318)
1319where
1320 for<'a> T: FollowWith<'a>,
1321 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>;
1322
1323impl<'sender, T> Builder<'sender, T>
1324where
1325 for<'a> T: FollowWith<'a>,
1326 for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>,
1327{
Adam Snaider34072e12023-10-03 10:04:25 -07001328 pub fn fbb(
1329 &mut self,
1330 ) -> &mut FlatBufferBuilder<'sender, ChannelPreallocatedAllocator<'sender>> {
Brian Silverman90221f82022-08-22 23:46:09 -07001331 self.0.fbb()
1332 }
1333
1334 pub fn send<'a>(
1335 self,
1336 root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>,
1337 ) -> Result<(), SendError> {
1338 // SAFETY: We guarantee this is the right type based on invariants for our type.
1339 unsafe { self.0.send(root) }
1340 }
1341}
1342
1343#[derive(Clone, Copy, Eq, PartialEq, Debug, Error)]
1344pub enum SendError {
1345 #[error("messages have been sent too fast on this channel")]
1346 MessagesSentTooFast,
1347 #[error("invalid redzone data, shared memory corruption detected")]
1348 InvalidRedzone,
1349}
1350
Brian Silverman9809c5f2022-07-23 16:12:23 -07001351#[repr(transparent)]
1352#[derive(Clone, Copy)]
1353pub struct Context<'context>(&'context ffi::aos::Context);
1354
1355impl fmt::Debug for Context<'_> {
1356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Brian Silverman9809c5f2022-07-23 16:12:23 -07001357 f.debug_struct("Context")
1358 .field("monotonic_event_time", &self.monotonic_event_time())
1359 .field("monotonic_remote_time", &self.monotonic_remote_time())
Ryan Yin683a8672022-11-09 20:44:20 -08001360 .field("realtime_event_time", &self.realtime_event_time())
1361 .field("realtime_remote_time", &self.realtime_remote_time())
Brian Silverman9809c5f2022-07-23 16:12:23 -07001362 .field("queue_index", &self.queue_index())
1363 .field("remote_queue_index", &self.remote_queue_index())
1364 .field("size", &self.data().map(|data| data.len()))
1365 .field("buffer_index", &self.buffer_index())
1366 .field("source_boot_uuid", &self.source_boot_uuid())
1367 .finish()
1368 }
1369}
1370
Brian Silverman9809c5f2022-07-23 16:12:23 -07001371impl<'context> Context<'context> {
1372 pub fn monotonic_event_time(self) -> MonotonicInstant {
1373 MonotonicInstant(self.0.monotonic_event_time)
1374 }
1375
1376 pub fn monotonic_remote_time(self) -> MonotonicInstant {
1377 MonotonicInstant(self.0.monotonic_remote_time)
1378 }
1379
Ryan Yin683a8672022-11-09 20:44:20 -08001380 pub fn realtime_event_time(self) -> RealtimeInstant {
1381 RealtimeInstant(self.0.realtime_event_time)
1382 }
1383
1384 pub fn realtime_remote_time(self) -> RealtimeInstant {
1385 RealtimeInstant(self.0.realtime_remote_time)
1386 }
1387
Brian Silverman9809c5f2022-07-23 16:12:23 -07001388 pub fn queue_index(self) -> u32 {
1389 self.0.queue_index
1390 }
1391 pub fn remote_queue_index(self) -> u32 {
1392 self.0.remote_queue_index
1393 }
1394
1395 pub fn data(self) -> Option<&'context [u8]> {
1396 if self.0.data.is_null() {
1397 None
1398 } else {
1399 // SAFETY:
1400 // * `u8` has no alignment requirements
1401 // * It must be a single initialized flatbuffers buffer
1402 // * The borrow in `self.0` guarantees it won't be modified for `'context`
1403 Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) })
1404 }
1405 }
1406
1407 pub fn buffer_index(self) -> i32 {
1408 self.0.buffer_index
1409 }
1410
1411 pub fn source_boot_uuid(self) -> &'context Uuid {
1412 // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be
1413 // valid until something changes the context, which is `'context`.
1414 Uuid::from_bytes_ref(&self.0.source_boot_uuid)
1415 }
1416}
1417
Brian Silverman76f48362022-08-24 21:09:08 -07001418/// The type returned from [`EventLoopRuntime::on_run`], see there for details.
1419// SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL).
1420#[repr(transparent)]
1421pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>);
1422
Adam Snaidera3317c82023-10-02 16:02:36 -07001423impl Future for &'_ OnRun {
Brian Silverman76f48362022-08-24 21:09:08 -07001424 type Output = ();
1425
1426 fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> {
1427 if self.0.is_running() {
1428 Poll::Ready(())
1429 } else {
1430 Poll::Pending
1431 }
1432 }
1433}
1434
Brian Silverman9809c5f2022-07-23 16:12:23 -07001435/// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This
1436/// is intended to have the same API as [`std::time::Instant`], any missing
1437/// functionality can be added if useful.
Brian Silverman9809c5f2022-07-23 16:12:23 -07001438#[repr(transparent)]
1439#[derive(Clone, Copy, Eq, PartialEq)]
1440pub struct MonotonicInstant(i64);
1441
1442impl MonotonicInstant {
1443 /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value.
1444 pub const MIN_TIME: Self = Self(i64::MIN);
1445
1446 pub fn is_min_time(self) -> bool {
1447 self == Self::MIN_TIME
1448 }
1449
1450 pub fn duration_since_epoch(self) -> Option<Duration> {
1451 if self.is_min_time() {
1452 None
1453 } else {
1454 Some(Duration::from_nanos(self.0.try_into().expect(
1455 "monotonic_clock::time_point should always be after the epoch",
1456 )))
1457 }
1458 }
1459}
1460
Adam Snaidercc8c2f72023-06-25 20:56:13 -07001461impl Add<Duration> for MonotonicInstant {
1462 type Output = MonotonicInstant;
1463
1464 fn add(self, rhs: Duration) -> Self::Output {
1465 Self(self.0 + i64::try_from(rhs.as_nanos()).unwrap())
1466 }
1467}
1468
Adam Snaiderde51c672023-09-28 21:55:43 -07001469impl From<MonotonicInstant> for i64 {
1470 fn from(value: MonotonicInstant) -> Self {
1471 value.0
1472 }
1473}
1474
Brian Silverman9809c5f2022-07-23 16:12:23 -07001475impl fmt::Debug for MonotonicInstant {
1476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1477 self.duration_since_epoch().fmt(f)
1478 }
1479}
1480
Ryan Yin683a8672022-11-09 20:44:20 -08001481#[repr(transparent)]
1482#[derive(Clone, Copy, Eq, PartialEq)]
1483pub struct RealtimeInstant(i64);
1484
1485impl RealtimeInstant {
1486 pub const MIN_TIME: Self = Self(i64::MIN);
1487
1488 pub fn is_min_time(self) -> bool {
1489 self == Self::MIN_TIME
1490 }
1491
1492 pub fn duration_since_epoch(self) -> Option<Duration> {
1493 if self.is_min_time() {
1494 None
1495 } else {
1496 Some(Duration::from_nanos(self.0.try_into().expect(
1497 "monotonic_clock::time_point should always be after the epoch",
1498 )))
1499 }
1500 }
1501}
1502
Adam Snaiderde51c672023-09-28 21:55:43 -07001503impl From<RealtimeInstant> for i64 {
1504 fn from(value: RealtimeInstant) -> Self {
1505 value.0
1506 }
1507}
1508
Ryan Yin683a8672022-11-09 20:44:20 -08001509impl fmt::Debug for RealtimeInstant {
1510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511 self.duration_since_epoch().fmt(f)
1512 }
1513}
1514
Brian Silverman9809c5f2022-07-23 16:12:23 -07001515mod panic_waker {
1516 use std::task::{RawWaker, RawWakerVTable, Waker};
1517
1518 unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker {
1519 raw_panic_waker()
1520 }
1521
1522 unsafe fn noop(_data: *const ()) {}
1523
1524 unsafe fn wake_panic(_data: *const ()) {
1525 panic!("Nothing should wake EventLoopRuntime's waker");
1526 }
1527
1528 const PANIC_WAKER_VTABLE: RawWakerVTable =
1529 RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop);
1530
1531 fn raw_panic_waker() -> RawWaker {
1532 RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE)
1533 }
1534
1535 pub fn panic_waker() -> Waker {
1536 // SAFETY: The implementations of the RawWakerVTable functions do what is required of them.
1537 unsafe { Waker::from_raw(raw_panic_waker()) }
1538 }
1539}
1540
1541use panic_waker::panic_waker;
Adam Snaider163800b2023-07-12 00:21:17 -04001542
1543pub struct ExitHandle(UniquePtr<CppExitHandle>);
1544
1545impl ExitHandle {
1546 /// Exits the EventLoops represented by this handle. You probably want to immediately return
1547 /// from the context this is called in. Awaiting [`exit`] instead of using this function is an
1548 /// easy way to do that.
1549 pub fn exit_sync(mut self) {
1550 self.0.as_mut().unwrap().Exit();
1551 }
1552
1553 /// Exits the EventLoops represented by this handle, and never returns. Immediately awaiting
1554 /// this from a [`EventLoopRuntime::spawn`]ed task is usually what you want, it will ensure
1555 /// that no more code from that task runs.
1556 pub async fn exit(self) -> Never {
1557 self.exit_sync();
1558 pending().await
1559 }
1560}
1561
1562impl From<UniquePtr<CppExitHandle>> for ExitHandle {
1563 fn from(inner: UniquePtr<ffi::aos::ExitHandle>) -> Self {
1564 Self(inner)
1565 }
1566}
Adam Snaider34072e12023-10-03 10:04:25 -07001567
1568pub struct ChannelPreallocatedAllocator<'a> {
1569 buffer: &'a mut [u8],
1570}
1571
1572impl<'a> ChannelPreallocatedAllocator<'a> {
1573 pub fn new(buffer: &'a mut [u8]) -> Self {
1574 Self { buffer }
1575 }
1576}
1577
1578#[derive(Debug, Error)]
1579#[error("Can't allocate more memory with a fixed size allocator")]
1580pub struct OutOfMemory;
1581
1582// SAFETY: Allocator follows the required behavior.
1583unsafe impl Allocator for ChannelPreallocatedAllocator<'_> {
1584 type Error = OutOfMemory;
1585 fn grow_downwards(&mut self) -> Result<(), Self::Error> {
1586 // Fixed size allocator can't grow.
1587 Err(OutOfMemory)
1588 }
1589
1590 fn len(&self) -> usize {
1591 self.buffer.len()
1592 }
1593}
1594
1595impl Deref for ChannelPreallocatedAllocator<'_> {
1596 type Target = [u8];
1597
1598 fn deref(&self) -> &Self::Target {
1599 self.buffer
1600 }
1601}
1602
1603impl DerefMut for ChannelPreallocatedAllocator<'_> {
1604 fn deref_mut(&mut self) -> &mut Self::Target {
1605 self.buffer
1606 }
1607}