Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1 | #![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 |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 25 | //! restrictions. <https://github.com/frc971/971-Robot-Code/issues/12> covers creating an adapter |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 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 |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 34 | //! <https://github.com/google/autocxx/issues/1146> for details. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 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 Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 37 | //! * 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 Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 40 | //! * 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 |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 43 | //! examples for generic associated types (<https://github.com/rust-lang/rust/issues/44265>). |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 44 | |
Brian Silverman | 1431a77 | 2022-08-31 20:44:36 -0700 | [diff] [blame] | 45 | use std::{ |
| 46 | fmt, |
| 47 | future::Future, |
| 48 | marker::PhantomData, |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 49 | ops::{Add, Deref, DerefMut}, |
Brian Silverman | 1431a77 | 2022-08-31 20:44:36 -0700 | [diff] [blame] | 50 | panic::{catch_unwind, AssertUnwindSafe}, |
| 51 | pin::Pin, |
| 52 | slice, |
| 53 | task::Poll, |
| 54 | time::Duration, |
| 55 | }; |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 56 | |
| 57 | use autocxx::{ |
Austin Schuh | dad7a81 | 2023-07-26 21:11:22 -0700 | [diff] [blame] | 58 | subclass::{subclass, CppSubclass}, |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 59 | WithinBox, |
| 60 | }; |
| 61 | use cxx::UniquePtr; |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 62 | use flatbuffers::{ |
| 63 | root_unchecked, Allocator, FlatBufferBuilder, Follow, FollowWith, FullyQualifiedName, |
| 64 | }; |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 65 | use futures::{future::pending, future::FusedFuture, never::Never}; |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 66 | use thiserror::Error; |
| 67 | use uuid::Uuid; |
| 68 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 69 | pub use aos_configuration::{Channel, Configuration, Node}; |
| 70 | use aos_configuration::{ChannelLookupError, ConfigurationExt}; |
| 71 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 72 | pub use aos_uuid::UUID; |
Adam Snaider | 8809723 | 2023-10-17 18:43:14 -0700 | [diff] [blame] | 73 | pub use ffi::aos::EventLoop as CppEventLoop; |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 74 | pub use ffi::aos::EventLoopRuntime as CppEventLoopRuntime; |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 75 | pub use ffi::aos::ExitHandle as CppExitHandle; |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 76 | |
| 77 | autocxx::include_cpp! ( |
| 78 | #include "aos/events/event_loop_runtime.h" |
| 79 | |
| 80 | safety!(unsafe) |
| 81 | |
| 82 | generate_pod!("aos::Context") |
| 83 | generate!("aos::WatcherForRust") |
| 84 | generate!("aos::RawSender_Error") |
| 85 | generate!("aos::SenderForRust") |
| 86 | generate!("aos::FetcherForRust") |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 87 | generate!("aos::OnRunForRust") |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 88 | generate!("aos::EventLoopRuntime") |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 89 | generate!("aos::ExitHandle") |
Adam Snaider | cc8c2f7 | 2023-06-25 20:56:13 -0700 | [diff] [blame] | 90 | generate!("aos::TimerForRust") |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 91 | |
| 92 | subclass!("aos::ApplicationFuture", RustApplicationFuture) |
| 93 | |
| 94 | extern_cpp_type!("aos::Configuration", crate::Configuration) |
| 95 | extern_cpp_type!("aos::Channel", crate::Channel) |
| 96 | extern_cpp_type!("aos::Node", crate::Node) |
| 97 | extern_cpp_type!("aos::UUID", crate::UUID) |
| 98 | ); |
| 99 | |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 100 | /// A marker type which is invariant with respect to the given lifetime. |
| 101 | /// |
| 102 | /// When interacting with functions that take and return things with a given lifetime, the lifetime |
| 103 | /// becomes invariant. Because we don't store these functions as Rust types, we need a type like |
| 104 | /// this to tell the Rust compiler that it can't substitute a shorter _or_ longer lifetime. |
| 105 | pub type InvariantLifetime<'a> = PhantomData<fn(&'a ()) -> &'a ()>; |
| 106 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 107 | /// # Safety |
| 108 | /// |
| 109 | /// This should have a `'event_loop` lifetime and `future` should include that in its type, but |
| 110 | /// autocxx's subclass doesn't support that. Even if it did, it wouldn't be enforced. C++ is |
| 111 | /// enforcing the lifetime: it destroys this object along with the C++ `EventLoopRuntime`, which |
| 112 | /// must be outlived by the EventLoop. |
| 113 | #[doc(hidden)] |
Austin Schuh | dad7a81 | 2023-07-26 21:11:22 -0700 | [diff] [blame] | 114 | #[subclass] |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 115 | pub struct RustApplicationFuture { |
| 116 | /// This logically has a `'event_loop` bound, see the class comment for details. |
| 117 | future: Pin<Box<dyn Future<Output = Never>>>, |
| 118 | } |
| 119 | |
| 120 | impl ffi::aos::ApplicationFuture_methods for RustApplicationFuture { |
Brian Silverman | 1431a77 | 2022-08-31 20:44:36 -0700 | [diff] [blame] | 121 | fn Poll(&mut self) -> bool { |
| 122 | catch_unwind(AssertUnwindSafe(|| { |
| 123 | // This is always allowed because it can never create a value of type `Ready<Never>` to |
| 124 | // return, so it must always return `Pending`. That also means the value it returns doesn't |
| 125 | // mean anything, so we ignore it. |
| 126 | let _ = Pin::new(&mut self.future) |
| 127 | .poll(&mut std::task::Context::from_waker(&panic_waker())); |
| 128 | })) |
| 129 | .is_ok() |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 130 | } |
| 131 | } |
| 132 | |
| 133 | impl RustApplicationFuture { |
| 134 | pub fn new<'event_loop>( |
| 135 | future: impl Future<Output = Never> + 'event_loop, |
| 136 | ) -> UniquePtr<ffi::aos::ApplicationFuture> { |
| 137 | /// # Safety |
| 138 | /// |
| 139 | /// This completely removes the `'event_loop` lifetime, the caller must ensure that is |
| 140 | /// sound. |
| 141 | unsafe fn remove_lifetime<'event_loop>( |
| 142 | future: Pin<Box<dyn Future<Output = Never> + 'event_loop>>, |
| 143 | ) -> Pin<Box<dyn Future<Output = Never>>> { |
| 144 | // SAFETY: Caller is responsible. |
| 145 | unsafe { std::mem::transmute(future) } |
| 146 | } |
| 147 | |
| 148 | Self::as_ApplicationFuture_unique_ptr(Self::new_cpp_owned(Self { |
| 149 | // SAFETY: C++ manages observing the lifetime, see [`RustApplicationFuture`] for |
| 150 | // details. |
| 151 | future: unsafe { remove_lifetime(Box::pin(future)) }, |
| 152 | cpp_peer: Default::default(), |
| 153 | })) |
| 154 | } |
| 155 | } |
| 156 | |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 157 | /// An abstraction for objects which hold an `aos::EventLoop` from Rust code. |
| 158 | /// |
| 159 | /// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call |
| 160 | /// [`EventLoopRuntime.new`] directly. |
| 161 | /// |
| 162 | /// # Safety |
| 163 | /// |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 164 | /// Objects implementing this trait must guarantee that the underlying event loop (as returned |
| 165 | /// from [`EventLoopHolder::as_raw`]), must be valid for as long as this object is. One way to do |
| 166 | /// this may be by managing ownership of the event loop with Rust's ownership semantics. However, |
| 167 | /// this is not strictly necessary. |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 168 | /// |
Adam Snaider | 8809723 | 2023-10-17 18:43:14 -0700 | [diff] [blame] | 169 | /// This also implies semantics similar to `Pin<&mut CppEventLoop>` for the underlying object. |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 170 | /// Implementations of this trait must guarantee that the underlying object must not be moved while |
| 171 | /// this object exists. |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 172 | pub unsafe trait EventLoopHolder { |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 173 | /// Returns the raw C++ pointer of the underlying event loop. |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 174 | /// |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 175 | /// Caller can only assume this pointer is valid while `self` is still alive. |
| 176 | fn as_raw(&self) -> *const CppEventLoop; |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 177 | } |
| 178 | |
| 179 | /// Owns an [`EventLoopRuntime`] and its underlying `aos::EventLoop`, with safe management of the |
| 180 | /// associated Rust lifetimes. |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 181 | pub struct EventLoopRuntimeHolder<T: EventLoopHolder> { |
| 182 | // NOTE: `runtime` must get dropped first, so we declare it before the event_loop: |
| 183 | // https://doc.rust-lang.org/reference/destructors.html |
| 184 | _runtime: Pin<Box<CppEventLoopRuntime>>, |
| 185 | _event_loop: T, |
| 186 | } |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 187 | |
| 188 | impl<T: EventLoopHolder> EventLoopRuntimeHolder<T> { |
| 189 | /// Creates a new [`EventLoopRuntime`] and runs an initialization function on it. This is a |
| 190 | /// safe wrapper around [`EventLoopRuntime.new`] (although see [`EventLoopHolder`]'s safety |
| 191 | /// requirements, part of them are just delegated there). |
| 192 | /// |
| 193 | /// If you have an `aos::EventLoop` provided from C++ code, don't use this, just call |
| 194 | /// [`EventLoopRuntime.new`] directly. |
| 195 | /// |
| 196 | /// All setup of the runtime must be performed with `fun`, which is called before this function |
| 197 | /// returns. `fun` may create further objects to use in async functions via [`EventLoop.spawn`] |
| 198 | /// etc, but it is the only place to set things up before the EventLoop is run. |
| 199 | /// |
| 200 | /// `fun` cannot capture things outside of the event loop, because the event loop might outlive |
| 201 | /// them: |
| 202 | /// ```compile_fail |
| 203 | /// # use aos_events_event_loop_runtime::*; |
| 204 | /// # fn bad(event_loop: impl EventLoopHolder) { |
| 205 | /// let mut x = 0; |
| 206 | /// EventLoopRuntimeHolder::new(event_loop, |runtime| { |
| 207 | /// runtime.spawn(async { |
| 208 | /// x = 1; |
| 209 | /// loop {} |
| 210 | /// }); |
| 211 | /// }); |
| 212 | /// # } |
| 213 | /// ``` |
| 214 | /// |
| 215 | /// But it can capture `'event_loop` references: |
| 216 | /// ``` |
| 217 | /// # use aos_events_event_loop_runtime::*; |
| 218 | /// # use aos_configuration::ChannelExt; |
| 219 | /// # fn good(event_loop: impl EventLoopHolder) { |
| 220 | /// EventLoopRuntimeHolder::new(event_loop, |runtime| { |
| 221 | /// let channel = runtime.get_raw_channel("/test", "aos.examples.Ping").unwrap(); |
| 222 | /// runtime.spawn(async { |
| 223 | /// loop { |
| 224 | /// eprintln!("{:?}", channel.type_()); |
| 225 | /// } |
| 226 | /// }); |
| 227 | /// }); |
| 228 | /// # } |
| 229 | /// ``` |
| 230 | pub fn new<F>(event_loop: T, fun: F) -> Self |
| 231 | where |
Adam Snaider | e4367cb | 2023-10-20 15:14:31 -0400 | [diff] [blame] | 232 | F: for<'event_loop> FnOnce(EventLoopRuntime<'event_loop>), |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 233 | { |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 234 | // SAFETY: The event loop pointer produced by as_raw must be valid and it will get dropped |
| 235 | // first (see https://doc.rust-lang.org/reference/destructors.html) |
| 236 | let runtime = unsafe { CppEventLoopRuntime::new(event_loop.as_raw()).within_box() }; |
| 237 | EventLoopRuntime::with(&runtime, fun); |
| 238 | Self { |
| 239 | _runtime: runtime, |
| 240 | _event_loop: event_loop, |
| 241 | } |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 242 | } |
| 243 | } |
| 244 | |
Adam Snaider | cd53e48 | 2023-10-23 09:37:42 -0400 | [diff] [blame] | 245 | /// Manages the Rust interface to a *single* `aos::EventLoop`. |
| 246 | /// |
| 247 | /// This is intended to be used by a single application. |
Adam Snaider | e4367cb | 2023-10-20 15:14:31 -0400 | [diff] [blame] | 248 | #[derive(Copy, Clone)] |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 249 | pub struct EventLoopRuntime<'event_loop>( |
Adam Snaider | e98c248 | 2023-10-17 19:02:03 -0700 | [diff] [blame] | 250 | &'event_loop CppEventLoopRuntime, |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 251 | // See documentation of [`new`] for details. |
| 252 | InvariantLifetime<'event_loop>, |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 253 | ); |
| 254 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 255 | impl<'event_loop> EventLoopRuntime<'event_loop> { |
Adam Snaider | cd53e48 | 2023-10-23 09:37:42 -0400 | [diff] [blame] | 256 | /// Creates a new runtime for the underlying event loop. |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 257 | /// |
| 258 | /// Consider using [`EventLoopRuntimeHolder.new`] instead, if you're working with an |
Adam Snaider | cd53e48 | 2023-10-23 09:37:42 -0400 | [diff] [blame] | 259 | /// `aos::EventLoop` owned (indirectly) by Rust code or using [`EventLoopRuntime::with`] as a safe |
| 260 | /// alternative. |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 261 | /// |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 262 | /// One common pattern is wrapping the lifetime behind a higher-rank trait bound (such as |
| 263 | /// [`FnOnce`]). This would constraint the lifetime to `'static` and objects with `'event_loop` |
| 264 | /// returned by this runtime. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 265 | /// |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 266 | /// Call [`EventLoopRuntime::spawn`] to respond to events. The non-event-driven APIs may be used without calling |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 267 | /// this. |
| 268 | /// |
| 269 | /// This is an async runtime, but it's a somewhat unusual one. See the module-level |
| 270 | /// documentation for details. |
| 271 | /// |
| 272 | /// # Safety |
| 273 | /// |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 274 | /// This function is where all the tricky lifetime guarantees to ensure soundness come |
| 275 | /// together. It all boils down to choosing `'event_loop` correctly, which is very complicated. |
| 276 | /// Here are the rules: |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 277 | /// |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 278 | /// 1. `'event_loop` extends until after the last time the underlying `aos::EventLoop` is run. |
| 279 | /// **This is often beyond the lifetime of this Rust `EventLoopRuntime` object**. |
| 280 | /// 2. `'event_loop` must outlive this object, because this object stores references to the |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 281 | /// underlying `aos::EventLoop`. |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 282 | /// 3. Any other references stored in the underlying `aos::EventLoop` must be valid for |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 283 | /// `'event_loop`. The easiest way to ensure this is by not using the `aos::EventLoop` before |
| 284 | /// passing it to this object. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 285 | /// |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 286 | /// Here are some corollaries: |
| 287 | /// |
| 288 | /// 1. The underlying `aos::EventLoop` must be dropped after this object. |
| 289 | /// 2. This object will store various references valid for `'event_loop` with a duration of |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 290 | /// `'event_loop`, which is safe as long as |
| 291 | /// |
| 292 | /// * `'event_loop` outlives the underlying event loop, and |
| 293 | /// * `'event_loop` references are not used once the event loop is destroyed |
| 294 | /// |
| 295 | /// Note that this requires this type to be invariant with respect to `'event_loop`. This can |
| 296 | /// be achieved by using [`EventLoopRuntime::with`] since `'event_loop` referenes can't leave |
| 297 | /// `fun` and the runtime holding `'event_loop` references will be destroyed before the event |
| 298 | /// loop. |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 299 | /// |
| 300 | /// `aos::EventLoop`'s public API is exclusively for consumers of the event loop. Some |
| 301 | /// subclasses extend this API. Additionally, all useful implementations of `aos::EventLoop` |
| 302 | /// must have some way to process events. Sometimes this is additional API surface (such as |
| 303 | /// `aos::ShmEventLoop`), in other cases comes via other objects holding references to the |
| 304 | /// `aos::EventLoop` (such as `aos::SimulatedEventLoopFactory`). This access to run the event |
| 305 | /// loop functions independently of the consuming functions in every way except lifetime of the |
| 306 | /// `aos::EventLoop`, and may be used independently of `'event_loop`. |
| 307 | /// |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 308 | /// ## Alternatives and why they don't work |
| 309 | /// |
| 310 | /// Making the argument `Pin<&'event_loop mut EventLoop>` would express some (but not all) of |
| 311 | /// these restrictions within the Rust type system. However, having an actual Rust mutable |
| 312 | /// reference like that prevents anything else from creating one via other pointers to the |
| 313 | /// same object from C++, which is a common operation. See the module-level documentation for |
| 314 | /// details. |
| 315 | /// |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 316 | /// spawned tasks need to hold `&'event_loop` references to things like channels. Using a |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 317 | /// separate `'config` lifetime wouldn't change much; the tasks still need to do things which |
| 318 | /// require them to not outlive something they don't control. This is fundamental to |
| 319 | /// self-referential objects, which `aos::EventLoop` is based around, but Rust requires unsafe |
| 320 | /// code to manage manually. |
| 321 | /// |
| 322 | /// ## Final cautions |
| 323 | /// |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 324 | /// Following these rules is very tricky. Be very cautious calling this function. The |
| 325 | /// exposed lifetime doesn't actually convey all the rules to the compiler. To the compiler, |
| 326 | /// `'event_loop` ends when this object is dropped which is not the case! |
Adam Snaider | e98c248 | 2023-10-17 19:02:03 -0700 | [diff] [blame] | 327 | pub unsafe fn new(event_loop: &'event_loop CppEventLoopRuntime) -> Self { |
| 328 | Self(event_loop, InvariantLifetime::default()) |
Brian Silverman | 2ee175e | 2023-07-11 16:32:08 -0700 | [diff] [blame] | 329 | } |
| 330 | |
Adam Snaider | cd53e48 | 2023-10-23 09:37:42 -0400 | [diff] [blame] | 331 | /// Safely builds a "constrained" EventLoopRuntime with `fun`. |
| 332 | /// |
| 333 | /// We constrain the scope of the `[EventLoopRuntime]` by tying it to **any** `'a` lifetime. The |
| 334 | /// idea is that the only things that satisfy this lifetime are either ``static` or produced by |
| 335 | /// the event loop itself with a '`event_loop` runtime. |
| 336 | pub fn with<F>(event_loop: &'event_loop CppEventLoopRuntime, fun: F) |
| 337 | where |
| 338 | F: for<'a> FnOnce(EventLoopRuntime<'a>), |
| 339 | { |
| 340 | // SAFETY: We satisfy the event loop lifetime constraint by scoping it inside of a higher- |
| 341 | // rank lifetime in FnOnce. This is similar to what is done in std::thread::scope, and the |
Adam Snaider | 014f88e | 2023-10-24 13:21:42 -0400 | [diff] [blame] | 342 | // point is that `fun` can only assume that `'static` and types produced by this type with a |
Adam Snaider | cd53e48 | 2023-10-23 09:37:42 -0400 | [diff] [blame] | 343 | // 'event_loop lifetime are the only lifetimes that will satisfy `'a`. This is possible due |
| 344 | // to this type's invariance over its lifetime, otherwise, one could easily make a Subtype |
| 345 | // that, due to its shorter lifetime, would include things from its outer scope. |
| 346 | unsafe { |
| 347 | fun(Self::new(event_loop)); |
| 348 | } |
| 349 | } |
| 350 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 351 | /// Returns the pointer passed into the constructor. |
| 352 | /// |
| 353 | /// The returned value should only be used for destroying it (_after_ `self` is dropped) or |
| 354 | /// calling other C++ APIs. |
Adam Snaider | 8809723 | 2023-10-17 18:43:14 -0700 | [diff] [blame] | 355 | pub fn raw_event_loop(&self) -> *mut CppEventLoop { |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 356 | self.0.event_loop() |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 357 | } |
| 358 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 359 | /// Returns a reference to the name of this EventLoop. |
| 360 | /// |
| 361 | /// TODO(Brian): Come up with a nice way to expose this safely, without memory allocations, for |
| 362 | /// logging etc. |
| 363 | /// |
| 364 | /// # Safety |
| 365 | /// |
| 366 | /// The result must not be used after C++ could change it. Unfortunately C++ can change this |
| 367 | /// name from most places, so you should be really careful what you do with the result. |
| 368 | pub unsafe fn raw_name(&self) -> &str { |
| 369 | self.0.name() |
| 370 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 371 | |
| 372 | pub fn get_raw_channel( |
| 373 | &self, |
| 374 | name: &str, |
| 375 | typename: &str, |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 376 | ) -> Result<&'event_loop Channel, ChannelLookupError> { |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 377 | self.configuration().get_channel( |
| 378 | name, |
| 379 | typename, |
| 380 | // SAFETY: We're not calling any EventLoop methods while C++ is using this for the |
| 381 | // channel lookup. |
| 382 | unsafe { self.raw_name() }, |
| 383 | self.node(), |
| 384 | ) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 385 | } |
| 386 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 387 | pub fn get_channel<T: FullyQualifiedName>( |
| 388 | &self, |
| 389 | name: &str, |
| 390 | ) -> Result<&'event_loop Channel, ChannelLookupError> { |
| 391 | self.get_raw_channel(name, T::get_fully_qualified_name()) |
| 392 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 393 | |
| 394 | /// Starts running the given `task`, which may not return (as specified by its type). If you |
| 395 | /// want your task to stop, return the result of awaiting [`futures::future::pending`], which |
| 396 | /// will never complete. `task` will not be polled after the underlying `aos::EventLoop` exits. |
| 397 | /// |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 398 | /// Note that task will be polled immediately, to give it a chance to initialize. If you want to |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 399 | /// defer work until the event loop starts running, await [`EventLoopRuntime::on_run`] in the task. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 400 | /// |
| 401 | /// # Panics |
| 402 | /// |
| 403 | /// Panics if called more than once. See the module-level documentation for alternatives if you |
| 404 | /// want to do this. |
| 405 | /// |
| 406 | /// # Examples with interesting return types |
| 407 | /// |
| 408 | /// These are all valid futures which never return: |
| 409 | /// ``` |
| 410 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 411 | /// # use futures::{never::Never, future::pending}; |
| 412 | /// async fn pending_wrapper() -> Never { |
| 413 | /// pending().await |
| 414 | /// } |
| 415 | /// async fn loop_forever() -> Never { |
| 416 | /// loop {} |
| 417 | /// } |
| 418 | /// |
| 419 | /// runtime.spawn(pending()); |
| 420 | /// runtime.spawn(async { pending().await }); |
| 421 | /// runtime.spawn(pending_wrapper()); |
| 422 | /// runtime.spawn(async { loop {} }); |
| 423 | /// runtime.spawn(loop_forever()); |
| 424 | /// runtime.spawn(async { println!("all done"); pending().await }); |
| 425 | /// # } |
| 426 | /// ``` |
| 427 | /// but this is not: |
| 428 | /// ```compile_fail |
| 429 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 430 | /// # use futures::ready; |
| 431 | /// runtime.spawn(ready()); |
| 432 | /// # } |
| 433 | /// ``` |
| 434 | /// and neither is this: |
| 435 | /// ```compile_fail |
| 436 | /// # fn compile_check(mut runtime: aos_events_event_loop_runtime::EventLoopRuntime) { |
| 437 | /// # use futures::ready; |
| 438 | /// runtime.spawn(async { println!("all done") }); |
| 439 | /// # } |
| 440 | /// ``` |
| 441 | /// |
| 442 | /// # Examples with capturing |
| 443 | /// |
| 444 | /// The future can capture things. This is important to access other objects created from the |
| 445 | /// runtime, either before calling this function: |
| 446 | /// ``` |
| 447 | /// # fn compile_check<'event_loop>( |
| 448 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 449 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 450 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 451 | /// # ) { |
| 452 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 453 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 454 | /// runtime.spawn(async move { loop { |
| 455 | /// watcher1.next().await; |
| 456 | /// watcher2.next().await; |
| 457 | /// }}); |
| 458 | /// # } |
| 459 | /// ``` |
| 460 | /// or after: |
| 461 | /// ``` |
| 462 | /// # fn compile_check<'event_loop>( |
| 463 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 464 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 465 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 466 | /// # ) { |
| 467 | /// # use std::{cell::RefCell, rc::Rc}; |
| 468 | /// let runtime = Rc::new(RefCell::new(runtime)); |
| 469 | /// runtime.borrow_mut().spawn({ |
| 470 | /// let mut runtime = runtime.clone(); |
| 471 | /// async move { |
| 472 | /// let mut runtime = runtime.borrow_mut(); |
| 473 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 474 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 475 | /// loop { |
| 476 | /// watcher1.next().await; |
| 477 | /// watcher2.next().await; |
| 478 | /// } |
| 479 | /// } |
| 480 | /// }); |
| 481 | /// # } |
| 482 | /// ``` |
| 483 | /// or both: |
| 484 | /// ``` |
| 485 | /// # fn compile_check<'event_loop>( |
| 486 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 487 | /// # channel1: &'event_loop aos_events_event_loop_runtime::Channel, |
| 488 | /// # channel2: &'event_loop aos_events_event_loop_runtime::Channel, |
| 489 | /// # ) { |
| 490 | /// # use std::{cell::RefCell, rc::Rc}; |
| 491 | /// let mut watcher1 = runtime.make_raw_watcher(channel1); |
| 492 | /// let runtime = Rc::new(RefCell::new(runtime)); |
| 493 | /// runtime.borrow_mut().spawn({ |
| 494 | /// let mut runtime = runtime.clone(); |
| 495 | /// async move { |
| 496 | /// let mut runtime = runtime.borrow_mut(); |
| 497 | /// let mut watcher2 = runtime.make_raw_watcher(channel2); |
| 498 | /// loop { |
| 499 | /// watcher1.next().await; |
| 500 | /// watcher2.next().await; |
| 501 | /// } |
| 502 | /// } |
| 503 | /// }); |
| 504 | /// # } |
| 505 | /// ``` |
| 506 | /// |
| 507 | /// But you cannot capture local variables: |
| 508 | /// ```compile_fail |
| 509 | /// # fn compile_check<'event_loop>( |
| 510 | /// # mut runtime: aos_events_event_loop_runtime::EventLoopRuntime<'event_loop>, |
| 511 | /// # ) { |
| 512 | /// let mut local: i32 = 971; |
| 513 | /// let local = &mut local; |
| 514 | /// runtime.spawn(async move { loop { |
| 515 | /// println!("have: {}", local); |
| 516 | /// }}); |
| 517 | /// # } |
| 518 | /// ``` |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 519 | pub fn spawn(&self, task: impl Future<Output = Never> + 'event_loop) { |
| 520 | self.0.Spawn(RustApplicationFuture::new(task)); |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 521 | } |
| 522 | |
| 523 | pub fn configuration(&self) -> &'event_loop Configuration { |
| 524 | // SAFETY: It's always a pointer valid for longer than the underlying EventLoop. |
| 525 | unsafe { &*self.0.configuration() } |
| 526 | } |
| 527 | |
| 528 | pub fn node(&self) -> Option<&'event_loop Node> { |
| 529 | // SAFETY: It's always a pointer valid for longer than the underlying EventLoop, or null. |
| 530 | unsafe { self.0.node().as_ref() } |
| 531 | } |
| 532 | |
| 533 | pub fn monotonic_now(&self) -> MonotonicInstant { |
| 534 | MonotonicInstant(self.0.monotonic_now()) |
| 535 | } |
| 536 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 537 | pub fn realtime_now(&self) -> RealtimeInstant { |
| 538 | RealtimeInstant(self.0.realtime_now()) |
| 539 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 540 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 541 | /// part of `self.configuration()`, which will always have this lifetime. |
| 542 | /// |
| 543 | /// # Panics |
| 544 | /// |
| 545 | /// Dropping `self` before the returned object is dropped will panic. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 546 | pub fn make_raw_watcher(&self, channel: &'event_loop Channel) -> RawWatcher { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 547 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 548 | // the usual autocxx heuristics. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 549 | RawWatcher(unsafe { self.0.MakeWatcher(channel) }.within_box()) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 550 | } |
| 551 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 552 | /// Provides type-safe async blocking access to messages on a channel. `T` should be a |
| 553 | /// generated flatbuffers table type, the lifetime parameter does not matter, using `'static` |
| 554 | /// is easiest. |
| 555 | /// |
| 556 | /// # Panics |
| 557 | /// |
| 558 | /// Dropping `self` before the returned object is dropped will panic. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 559 | pub fn make_watcher<T>(&self, channel_name: &str) -> Result<Watcher<T>, ChannelLookupError> |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 560 | where |
| 561 | for<'a> T: FollowWith<'a>, |
| 562 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 563 | T: FullyQualifiedName, |
| 564 | { |
| 565 | let channel = self.get_channel::<T>(channel_name)?; |
| 566 | Ok(Watcher(self.make_raw_watcher(channel), PhantomData)) |
| 567 | } |
| 568 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 569 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 570 | /// part of `self.configuration()`, which will always have this lifetime. |
| 571 | /// |
| 572 | /// # Panics |
| 573 | /// |
| 574 | /// Dropping `self` before the returned object is dropped will panic. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 575 | pub fn make_raw_sender(&self, channel: &'event_loop Channel) -> RawSender { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 576 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 577 | // the usual autocxx heuristics. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 578 | RawSender(unsafe { self.0.MakeSender(channel) }.within_box()) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 579 | } |
| 580 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 581 | /// Allows sending messages on a channel with a type-safe API. |
| 582 | /// |
| 583 | /// # Panics |
| 584 | /// |
| 585 | /// Dropping `self` before the returned object is dropped will panic. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 586 | pub fn make_sender<T>(&self, channel_name: &str) -> Result<Sender<T>, ChannelLookupError> |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 587 | where |
| 588 | for<'a> T: FollowWith<'a>, |
| 589 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 590 | T: FullyQualifiedName, |
| 591 | { |
| 592 | let channel = self.get_channel::<T>(channel_name)?; |
| 593 | Ok(Sender(self.make_raw_sender(channel), PhantomData)) |
| 594 | } |
| 595 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 596 | /// Note that the `'event_loop` input lifetime is intentional. The C++ API requires that it is |
| 597 | /// part of `self.configuration()`, which will always have this lifetime. |
| 598 | /// |
| 599 | /// # Panics |
| 600 | /// |
| 601 | /// Dropping `self` before the returned object is dropped will panic. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 602 | pub fn make_raw_fetcher(&self, channel: &'event_loop Channel) -> RawFetcher { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 603 | // SAFETY: `channel` is valid for the necessary lifetime, all other requirements fall under |
| 604 | // the usual autocxx heuristics. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 605 | RawFetcher(unsafe { self.0.MakeFetcher(channel) }.within_box()) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 606 | } |
| 607 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 608 | /// Provides type-safe access to messages on a channel, without the ability to wait for a new |
| 609 | /// one. This provides APIs to get the latest message, and to follow along and retrieve each |
| 610 | /// message in order. |
| 611 | /// |
| 612 | /// # Panics |
| 613 | /// |
| 614 | /// Dropping `self` before the returned object is dropped will panic. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 615 | pub fn make_fetcher<T>(&self, channel_name: &str) -> Result<Fetcher<T>, ChannelLookupError> |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 616 | where |
| 617 | for<'a> T: FollowWith<'a>, |
| 618 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 619 | T: FullyQualifiedName, |
| 620 | { |
| 621 | let channel = self.get_channel::<T>(channel_name)?; |
| 622 | Ok(Fetcher(self.make_raw_fetcher(channel), PhantomData)) |
| 623 | } |
| 624 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 625 | // TODO(Brian): Expose timers and phased loops. Should we have `sleep`-style methods for those, |
| 626 | // instead of / in addition to mirroring C++ with separate setup and wait? |
| 627 | |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 628 | /// Returns a Future to wait until the underlying EventLoop is running. Once this resolves, all |
| 629 | /// subsequent code will have any realtime scheduling applied. This means it can rely on |
| 630 | /// consistent timing, but it can no longer create any EventLoop child objects or do anything |
| 631 | /// else non-realtime. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 632 | pub fn on_run(&self) -> OnRun { |
| 633 | OnRun(self.0.MakeOnRun().within_box()) |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 634 | } |
| 635 | |
| 636 | pub fn is_running(&self) -> bool { |
| 637 | self.0.is_running() |
| 638 | } |
Adam Snaider | cc8c2f7 | 2023-06-25 20:56:13 -0700 | [diff] [blame] | 639 | |
| 640 | /// Returns an unarmed timer. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 641 | pub fn add_timer(&self) -> Timer { |
| 642 | Timer(self.0.AddTimer()) |
Adam Snaider | cc8c2f7 | 2023-06-25 20:56:13 -0700 | [diff] [blame] | 643 | } |
| 644 | |
| 645 | /// Returns a timer that goes off every `duration`-long ticks. |
Adam Snaider | 48a5468 | 2023-09-28 21:50:42 -0700 | [diff] [blame] | 646 | pub fn add_interval(&self, duration: Duration) -> Timer { |
Adam Snaider | cc8c2f7 | 2023-06-25 20:56:13 -0700 | [diff] [blame] | 647 | let mut timer = self.add_timer(); |
| 648 | timer.setup(self.monotonic_now(), Some(duration)); |
| 649 | timer |
| 650 | } |
Adam Snaider | cf0dac7 | 2023-10-02 14:41:58 -0700 | [diff] [blame] | 651 | |
| 652 | /// Sets the scheduler priority to run the event loop at. |
| 653 | pub fn set_realtime_priority(&self, priority: i32) { |
| 654 | self.0.SetRuntimeRealtimePriority(priority.into()); |
| 655 | } |
Adam Snaider | cc8c2f7 | 2023-06-25 20:56:13 -0700 | [diff] [blame] | 656 | } |
| 657 | |
| 658 | /// An event loop primitive that allows sleeping asynchronously. |
| 659 | /// |
| 660 | /// # Examples |
| 661 | /// |
| 662 | /// ```no_run |
| 663 | /// # use aos_events_event_loop_runtime::EventLoopRuntime; |
| 664 | /// # use std::time::Duration; |
| 665 | /// # fn compile_check(runtime: &mut EventLoopRuntime<'_>) { |
| 666 | /// # let mut timer = runtime.add_timer(); |
| 667 | /// // Goes as soon as awaited. |
| 668 | /// timer.setup(runtime.monotonic_now(), None); |
| 669 | /// // Goes off once in 2 seconds. |
| 670 | /// timer.setup(runtime.monotonic_now() + Duration::from_secs(2), None); |
| 671 | /// // Goes off as soon as awaited and every 2 seconds afterwards. |
| 672 | /// timer.setup(runtime.monotonic_now(), Some(Duration::from_secs(1))); |
| 673 | /// async { |
| 674 | /// for i in 0..10 { |
| 675 | /// timer.tick().await; |
| 676 | /// } |
| 677 | /// // Timer won't off anymore. Next `tick` will never return. |
| 678 | /// timer.disable(); |
| 679 | /// timer.tick().await; |
| 680 | /// }; |
| 681 | /// # } |
| 682 | /// ``` |
| 683 | pub struct Timer(UniquePtr<ffi::aos::TimerForRust>); |
| 684 | |
| 685 | /// A "tick" for a [`Timer`]. |
| 686 | /// |
| 687 | /// This is the raw future generated by the [`Timer::tick`] function. |
| 688 | pub struct TimerTick<'a>(&'a mut Timer); |
| 689 | |
| 690 | impl Timer { |
| 691 | /// Arms the timer. |
| 692 | /// |
| 693 | /// The timer should sleep until `base`, `base + repeat`, `base + repeat * 2`, ... |
| 694 | /// If `repeat` is `None`, then the timer only expires once at `base`. |
| 695 | pub fn setup(&mut self, base: MonotonicInstant, repeat: Option<Duration>) { |
| 696 | self.0.pin_mut().Schedule( |
| 697 | base.0, |
| 698 | repeat |
| 699 | .unwrap_or(Duration::from_nanos(0)) |
| 700 | .as_nanos() |
| 701 | .try_into() |
| 702 | .expect("Out of range: Internal clock uses 64 bits"), |
| 703 | ); |
| 704 | } |
| 705 | |
| 706 | /// Disarms the timer. |
| 707 | /// |
| 708 | /// Can be re-enabled by calling `setup` again. |
| 709 | pub fn disable(&mut self) { |
| 710 | self.0.pin_mut().Disable(); |
| 711 | } |
| 712 | |
| 713 | /// Returns `true` if the timer is enabled. |
| 714 | pub fn is_enabled(&self) -> bool { |
| 715 | !self.0.IsDisabled() |
| 716 | } |
| 717 | |
| 718 | /// Sets the name of the timer. |
| 719 | /// |
| 720 | /// This can be useful to get a descriptive name in the timing reports. |
| 721 | pub fn set_name(&mut self, name: &str) { |
| 722 | self.0.pin_mut().set_name(name); |
| 723 | } |
| 724 | |
| 725 | /// Gets the name of the timer. |
| 726 | pub fn name(&self) -> &str { |
| 727 | self.0.name() |
| 728 | } |
| 729 | |
| 730 | /// Returns a tick which can be `.await`ed. |
| 731 | /// |
| 732 | /// This tick will resolve on the next timer expired. |
| 733 | pub fn tick(&mut self) -> TimerTick { |
| 734 | TimerTick(self) |
| 735 | } |
| 736 | |
| 737 | /// Polls the timer, returning `[Poll::Ready]` only once the timer expired. |
| 738 | fn poll(&mut self) -> Poll<()> { |
| 739 | if self.0.pin_mut().Poll() { |
| 740 | Poll::Ready(()) |
| 741 | } else { |
| 742 | Poll::Pending |
| 743 | } |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | impl Future for TimerTick<'_> { |
| 748 | type Output = (); |
| 749 | |
| 750 | fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> { |
| 751 | self.0.poll() |
| 752 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 753 | } |
| 754 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 755 | /// Provides async blocking access to messages on a channel. This will return every message on the |
| 756 | /// channel, in order. |
| 757 | /// |
| 758 | /// Use [`EventLoopRuntime::make_raw_watcher`] to create one of these. |
| 759 | /// |
| 760 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 761 | /// for actually interpreting messages. You probably want a [`Watcher`] instead. |
| 762 | /// |
| 763 | /// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical |
| 764 | /// reasons. |
| 765 | /// |
| 766 | /// # Design |
| 767 | /// |
| 768 | /// We can't use [`futures::stream::Stream`] because our `Item` type is `Context<'_>`, which means |
| 769 | /// it's different for each `self` lifetime so we can't write a single type alias for it. We could |
| 770 | /// write an intermediate type with a generic lifetime that implements `Stream` and is returned |
| 771 | /// from a `make_stream` method, but that's what `Stream` is doing in the first place so adding |
| 772 | /// another level doesn't help anything. |
| 773 | /// |
| 774 | /// We also drop the extraneous `cx` argument that isn't used by this implementation anyways. |
| 775 | /// |
| 776 | /// We also run into some limitations in the borrow checker trying to implement `poll`, I think it's |
| 777 | /// the same one mentioned here: |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 778 | /// <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> |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 779 | /// We get around that one by moving the unbounded lifetime from the pointer dereference into the |
| 780 | /// function with the if statement. |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 781 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 782 | #[repr(transparent)] |
| 783 | pub struct RawWatcher(Pin<Box<ffi::aos::WatcherForRust>>); |
| 784 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 785 | impl RawWatcher { |
| 786 | /// Returns a Future to await the next value. This can be canceled (ie dropped) at will, |
| 787 | /// without skipping any messages. |
| 788 | /// |
| 789 | /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You |
| 790 | /// will need to call this function again to get the succeeding message. |
| 791 | /// |
| 792 | /// # Examples |
| 793 | /// |
| 794 | /// The common use case is immediately awaiting the next message: |
| 795 | /// ``` |
| 796 | /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 797 | /// println!("received: {:?}", watcher.next().await); |
| 798 | /// # } |
| 799 | /// ``` |
| 800 | /// |
| 801 | /// You can also await the first message from any of a set of channels: |
| 802 | /// ``` |
| 803 | /// # async fn select( |
| 804 | /// # mut watcher1: aos_events_event_loop_runtime::RawWatcher, |
| 805 | /// # mut watcher2: aos_events_event_loop_runtime::RawWatcher, |
| 806 | /// # ) { |
| 807 | /// futures::select! { |
| 808 | /// message1 = watcher1.next() => println!("channel 1: {:?}", message1), |
| 809 | /// message2 = watcher2.next() => println!("channel 2: {:?}", message2), |
| 810 | /// } |
| 811 | /// # } |
| 812 | /// ``` |
| 813 | /// |
| 814 | /// Note that due to the returned object borrowing the `self` reference, the borrow checker will |
| 815 | /// enforce only having a single of these returned objects at a time. Drop the previous message |
| 816 | /// before asking for the next one. That means this will not compile: |
| 817 | /// ```compile_fail |
| 818 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 819 | /// let first = watcher.next(); |
| 820 | /// let second = watcher.next(); |
| 821 | /// first.await; |
| 822 | /// # } |
| 823 | /// ``` |
| 824 | /// and nor will this: |
| 825 | /// ```compile_fail |
| 826 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 827 | /// let first = watcher.next().await; |
| 828 | /// watcher.next(); |
| 829 | /// println!("still have: {:?}", first); |
| 830 | /// # } |
| 831 | /// ``` |
| 832 | /// but this is fine: |
| 833 | /// ``` |
| 834 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::RawWatcher) { |
| 835 | /// let first = watcher.next().await; |
| 836 | /// println!("have: {:?}", first); |
| 837 | /// watcher.next(); |
| 838 | /// # } |
| 839 | /// ``` |
| 840 | pub fn next(&mut self) -> RawWatcherNext { |
| 841 | RawWatcherNext(Some(self)) |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | /// The type returned from [`RawWatcher::next`], see there for details. |
| 846 | pub struct RawWatcherNext<'a>(Option<&'a mut RawWatcher>); |
| 847 | |
| 848 | impl<'a> Future for RawWatcherNext<'a> { |
| 849 | type Output = Context<'a>; |
| 850 | fn poll(mut self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<Context<'a>> { |
| 851 | let inner = self |
| 852 | .0 |
| 853 | .take() |
| 854 | .expect("May not call poll after it returns Ready"); |
| 855 | let maybe_context = inner.0.as_mut().PollNext(); |
| 856 | if maybe_context.is_null() { |
| 857 | // We're not returning a reference into it, so we can safely replace the reference to |
| 858 | // use again in the future. |
| 859 | self.0.replace(inner); |
| 860 | Poll::Pending |
| 861 | } else { |
| 862 | // SAFETY: We just checked if it's null. If not, it will be a valid pointer. It will |
| 863 | // remain a valid pointer for the borrow of the underlying `RawWatcher` (ie `'a`) |
| 864 | // because we're dropping `inner` (which is that reference), so it will need to be |
| 865 | // borrowed again which cannot happen before the end of `'a`. |
| 866 | Poll::Ready(Context(unsafe { &*maybe_context })) |
| 867 | } |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | impl FusedFuture for RawWatcherNext<'_> { |
| 872 | fn is_terminated(&self) -> bool { |
| 873 | self.0.is_none() |
| 874 | } |
| 875 | } |
| 876 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 877 | /// Provides async blocking access to messages on a channel. This will return every message on the |
| 878 | /// channel, in order. |
| 879 | /// |
| 880 | /// Use [`EventLoopRuntime::make_watcher`] to create one of these. |
| 881 | /// |
| 882 | /// This is the same concept as [`futures::stream::Stream`], but can't follow that API for technical |
| 883 | /// reasons. See [`RawWatcher`]'s documentation for details. |
| 884 | pub struct Watcher<T>(RawWatcher, PhantomData<*mut T>) |
| 885 | where |
| 886 | for<'a> T: FollowWith<'a>, |
| 887 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 888 | |
| 889 | impl<T> Watcher<T> |
| 890 | where |
| 891 | for<'a> T: FollowWith<'a>, |
| 892 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 893 | { |
| 894 | /// Returns a Future to await the next value. This can be canceled (ie dropped) at will, |
| 895 | /// without skipping any messages. |
| 896 | /// |
| 897 | /// Remember not to call `poll` after it returns `Poll::Ready`, just like any other future. You |
| 898 | /// will need to call this function again to get the succeeding message. |
| 899 | /// |
| 900 | /// # Examples |
| 901 | /// |
| 902 | /// The common use case is immediately awaiting the next message: |
| 903 | /// ``` |
| 904 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 905 | /// # async fn await_message(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 906 | /// println!("received: {:?}", watcher.next().await); |
| 907 | /// # } |
| 908 | /// ``` |
| 909 | /// |
| 910 | /// You can also await the first message from any of a set of channels: |
| 911 | /// ``` |
| 912 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 913 | /// # async fn select( |
| 914 | /// # mut watcher1: aos_events_event_loop_runtime::Watcher<Pong<'static>>, |
| 915 | /// # mut watcher2: aos_events_event_loop_runtime::Watcher<Pong<'static>>, |
| 916 | /// # ) { |
| 917 | /// futures::select! { |
| 918 | /// message1 = watcher1.next() => println!("channel 1: {:?}", message1), |
| 919 | /// message2 = watcher2.next() => println!("channel 2: {:?}", message2), |
| 920 | /// } |
| 921 | /// # } |
| 922 | /// ``` |
| 923 | /// |
| 924 | /// Note that due to the returned object borrowing the `self` reference, the borrow checker will |
| 925 | /// enforce only having a single of these returned objects at a time. Drop the previous message |
| 926 | /// before asking for the next one. That means this will not compile: |
| 927 | /// ```compile_fail |
| 928 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 929 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 930 | /// let first = watcher.next(); |
| 931 | /// let second = watcher.next(); |
| 932 | /// first.await; |
| 933 | /// # } |
| 934 | /// ``` |
| 935 | /// and nor will this: |
| 936 | /// ```compile_fail |
| 937 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 938 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 939 | /// let first = watcher.next().await; |
| 940 | /// watcher.next(); |
| 941 | /// println!("still have: {:?}", first); |
| 942 | /// # } |
| 943 | /// ``` |
| 944 | /// but this is fine: |
| 945 | /// ``` |
| 946 | /// # use pong_rust_fbs::aos::examples::Pong; |
| 947 | /// # async fn compile_check(mut watcher: aos_events_event_loop_runtime::Watcher<Pong<'static>>) { |
| 948 | /// let first = watcher.next().await; |
| 949 | /// println!("have: {:?}", first); |
| 950 | /// watcher.next(); |
| 951 | /// # } |
| 952 | /// ``` |
| 953 | pub fn next(&mut self) -> WatcherNext<'_, <T as FollowWith<'_>>::Inner> { |
| 954 | WatcherNext(self.0.next(), PhantomData) |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | /// The type returned from [`Watcher::next`], see there for details. |
| 959 | pub struct WatcherNext<'watcher, T>(RawWatcherNext<'watcher>, PhantomData<*mut T>) |
| 960 | where |
| 961 | T: Follow<'watcher> + 'watcher; |
| 962 | |
| 963 | impl<'watcher, T> Future for WatcherNext<'watcher, T> |
| 964 | where |
| 965 | T: Follow<'watcher> + 'watcher, |
| 966 | { |
| 967 | type Output = TypedContext<'watcher, T>; |
| 968 | |
| 969 | fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> { |
| 970 | Pin::new(&mut self.get_mut().0).poll(cx).map(|context| |
| 971 | // SAFETY: The Watcher this was created from verified that the channel is the |
| 972 | // right type, and the C++ guarantees that the buffer's type matches. |
| 973 | TypedContext(context, PhantomData)) |
| 974 | } |
| 975 | } |
| 976 | |
| 977 | impl<'watcher, T> FusedFuture for WatcherNext<'watcher, T> |
| 978 | where |
| 979 | T: Follow<'watcher> + 'watcher, |
| 980 | { |
| 981 | fn is_terminated(&self) -> bool { |
| 982 | self.0.is_terminated() |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | /// A wrapper around [`Context`] which exposes the flatbuffer message with the appropriate type. |
| 987 | pub struct TypedContext<'a, T>( |
| 988 | // SAFETY: This must have a message, and it must be a valid `T` flatbuffer. |
| 989 | Context<'a>, |
| 990 | PhantomData<*mut T>, |
| 991 | ) |
| 992 | where |
| 993 | T: Follow<'a> + 'a; |
| 994 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 995 | impl<'a, T> TypedContext<'a, T> |
| 996 | where |
| 997 | T: Follow<'a> + 'a, |
| 998 | { |
| 999 | pub fn message(&self) -> Option<T::Inner> { |
| 1000 | self.0.data().map(|data| { |
| 1001 | // SAFETY: C++ guarantees that this is a valid flatbuffer. We guarantee it's the right |
| 1002 | // type based on invariants for our type. |
| 1003 | unsafe { root_unchecked::<T>(data) } |
| 1004 | }) |
| 1005 | } |
| 1006 | |
| 1007 | pub fn monotonic_event_time(&self) -> MonotonicInstant { |
| 1008 | self.0.monotonic_event_time() |
| 1009 | } |
| 1010 | pub fn monotonic_remote_time(&self) -> MonotonicInstant { |
| 1011 | self.0.monotonic_remote_time() |
| 1012 | } |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1013 | pub fn realtime_event_time(&self) -> RealtimeInstant { |
| 1014 | self.0.realtime_event_time() |
| 1015 | } |
| 1016 | pub fn realtime_remote_time(&self) -> RealtimeInstant { |
| 1017 | self.0.realtime_remote_time() |
| 1018 | } |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1019 | pub fn queue_index(&self) -> u32 { |
| 1020 | self.0.queue_index() |
| 1021 | } |
| 1022 | pub fn remote_queue_index(&self) -> u32 { |
| 1023 | self.0.remote_queue_index() |
| 1024 | } |
| 1025 | pub fn buffer_index(&self) -> i32 { |
| 1026 | self.0.buffer_index() |
| 1027 | } |
| 1028 | pub fn source_boot_uuid(&self) -> &Uuid { |
| 1029 | self.0.source_boot_uuid() |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | impl<'a, T> fmt::Debug for TypedContext<'a, T> |
| 1034 | where |
| 1035 | T: Follow<'a> + 'a, |
| 1036 | T::Inner: fmt::Debug, |
| 1037 | { |
| 1038 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1039 | f.debug_struct("TypedContext") |
| 1040 | .field("monotonic_event_time", &self.monotonic_event_time()) |
| 1041 | .field("monotonic_remote_time", &self.monotonic_remote_time()) |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1042 | .field("realtime_event_time", &self.realtime_event_time()) |
| 1043 | .field("realtime_remote_time", &self.realtime_remote_time()) |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1044 | .field("queue_index", &self.queue_index()) |
| 1045 | .field("remote_queue_index", &self.remote_queue_index()) |
| 1046 | .field("message", &self.message()) |
| 1047 | .field("buffer_index", &self.buffer_index()) |
| 1048 | .field("source_boot_uuid", &self.source_boot_uuid()) |
| 1049 | .finish() |
| 1050 | } |
| 1051 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1052 | |
| 1053 | /// Provides access to messages on a channel, without the ability to wait for a new one. This |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1054 | /// provides APIs to get the latest message, and to follow along and retrieve each message in order. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1055 | /// |
| 1056 | /// Use [`EventLoopRuntime::make_raw_fetcher`] to create one of these. |
| 1057 | /// |
| 1058 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 1059 | /// for actually interpreting messages. You probably want a [`Fetcher`] instead. |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1060 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 1061 | #[repr(transparent)] |
| 1062 | pub struct RawFetcher(Pin<Box<ffi::aos::FetcherForRust>>); |
| 1063 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1064 | impl RawFetcher { |
| 1065 | pub fn fetch_next(&mut self) -> bool { |
| 1066 | self.0.as_mut().FetchNext() |
| 1067 | } |
| 1068 | |
| 1069 | pub fn fetch(&mut self) -> bool { |
| 1070 | self.0.as_mut().Fetch() |
| 1071 | } |
| 1072 | |
| 1073 | pub fn context(&self) -> Context { |
| 1074 | Context(self.0.context()) |
| 1075 | } |
| 1076 | } |
| 1077 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1078 | /// Provides access to messages on a channel, without the ability to wait for a new one. This |
| 1079 | /// provides APIs to get the latest message, and to follow along and retrieve each message in order. |
| 1080 | /// |
| 1081 | /// Use [`EventLoopRuntime::make_fetcher`] to create one of these. |
| 1082 | pub struct Fetcher<T>( |
| 1083 | // SAFETY: This must produce messages of type `T`. |
| 1084 | RawFetcher, |
| 1085 | PhantomData<*mut T>, |
| 1086 | ) |
| 1087 | where |
| 1088 | for<'a> T: FollowWith<'a>, |
| 1089 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 1090 | |
| 1091 | impl<T> Fetcher<T> |
| 1092 | where |
| 1093 | for<'a> T: FollowWith<'a>, |
| 1094 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 1095 | { |
| 1096 | pub fn fetch_next(&mut self) -> bool { |
| 1097 | self.0.fetch_next() |
| 1098 | } |
| 1099 | pub fn fetch(&mut self) -> bool { |
| 1100 | self.0.fetch() |
| 1101 | } |
| 1102 | |
| 1103 | pub fn context(&self) -> TypedContext<'_, <T as FollowWith<'_>>::Inner> { |
| 1104 | // SAFETY: We verified that this is the correct type, and C++ guarantees that the buffer's |
| 1105 | // type matches. |
| 1106 | TypedContext(self.0.context(), PhantomData) |
| 1107 | } |
| 1108 | } |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1109 | |
| 1110 | /// Allows sending messages on a channel. |
| 1111 | /// |
| 1112 | /// This is the non-typed API, which is mainly useful for reflection and does not provide safe APIs |
| 1113 | /// for actually creating messages to send. You probably want a [`Sender`] instead. |
| 1114 | /// |
| 1115 | /// Use [`EventLoopRuntime::make_raw_sender`] to create one of these. |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1116 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 1117 | #[repr(transparent)] |
| 1118 | pub struct RawSender(Pin<Box<ffi::aos::SenderForRust>>); |
| 1119 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1120 | impl RawSender { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1121 | /// Returns an object which can be used to build a message. |
| 1122 | /// |
| 1123 | /// # Examples |
| 1124 | /// |
| 1125 | /// ``` |
| 1126 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 1127 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 1128 | /// # unsafe { |
| 1129 | /// let mut builder = sender.make_builder(); |
| 1130 | /// let pong = PongBuilder::new(builder.fbb()).finish(); |
| 1131 | /// builder.send(pong); |
| 1132 | /// # } |
| 1133 | /// # } |
| 1134 | /// ``` |
| 1135 | /// |
| 1136 | /// You can bail out of building a message and build another one: |
| 1137 | /// ``` |
| 1138 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 1139 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 1140 | /// # unsafe { |
| 1141 | /// let mut builder1 = sender.make_builder(); |
| 1142 | /// builder1.fbb(); |
Adam Snaider | 0126d83 | 2023-10-03 09:59:34 -0700 | [diff] [blame] | 1143 | /// drop(builder1); |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1144 | /// let mut builder2 = sender.make_builder(); |
| 1145 | /// let pong = PongBuilder::new(builder2.fbb()).finish(); |
| 1146 | /// builder2.send(pong); |
| 1147 | /// # } |
| 1148 | /// # } |
| 1149 | /// ``` |
| 1150 | /// but you cannot build two messages at the same time with a single builder: |
| 1151 | /// ```compile_fail |
| 1152 | /// # use pong_rust_fbs::aos::examples::PongBuilder; |
| 1153 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::RawSender) { |
| 1154 | /// # unsafe { |
| 1155 | /// let mut builder1 = sender.make_builder(); |
| 1156 | /// let mut builder2 = sender.make_builder(); |
| 1157 | /// PongBuilder::new(builder2.fbb()).finish(); |
| 1158 | /// PongBuilder::new(builder1.fbb()).finish(); |
| 1159 | /// # } |
| 1160 | /// # } |
| 1161 | /// ``` |
| 1162 | pub fn make_builder(&mut self) -> RawBuilder { |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 1163 | // SAFETY: This is a valid slice, and `u8` doesn't have any alignment |
| 1164 | // requirements. Additionally, the lifetime of the builder is tied to |
| 1165 | // the lifetime of self so the buffer won't be accessible again until |
| 1166 | // the builder is destroyed. |
| 1167 | let allocator = ChannelPreallocatedAllocator::new(unsafe { |
| 1168 | slice::from_raw_parts_mut(self.0.as_mut().data(), self.0.as_mut().size()) |
| 1169 | }); |
| 1170 | let fbb = FlatBufferBuilder::new_in(allocator); |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1171 | RawBuilder { |
| 1172 | raw_sender: self, |
| 1173 | fbb, |
| 1174 | } |
| 1175 | } |
| 1176 | } |
| 1177 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1178 | /// Used for building a message. See [`RawSender::make_builder`] for details. |
| 1179 | pub struct RawBuilder<'sender> { |
| 1180 | raw_sender: &'sender mut RawSender, |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 1181 | fbb: FlatBufferBuilder<'sender, ChannelPreallocatedAllocator<'sender>>, |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1182 | } |
| 1183 | |
| 1184 | impl<'sender> RawBuilder<'sender> { |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 1185 | pub fn fbb( |
| 1186 | &mut self, |
| 1187 | ) -> &mut FlatBufferBuilder<'sender, ChannelPreallocatedAllocator<'sender>> { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1188 | &mut self.fbb |
| 1189 | } |
| 1190 | |
| 1191 | /// # Safety |
| 1192 | /// |
| 1193 | /// `T` must match the type of the channel of the sender this builder was created from. |
| 1194 | pub unsafe fn send<T>(mut self, root: flatbuffers::WIPOffset<T>) -> Result<(), SendError> { |
| 1195 | self.fbb.finish_minimal(root); |
| 1196 | let data = self.fbb.finished_data(); |
| 1197 | |
| 1198 | use ffi::aos::RawSender_Error as FfiError; |
| 1199 | // SAFETY: This is a valid buffer we're passing. |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 1200 | match self.raw_sender.0.as_mut().SendBuffer(data.len()) { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1201 | FfiError::kOk => Ok(()), |
| 1202 | FfiError::kMessagesSentTooFast => Err(SendError::MessagesSentTooFast), |
| 1203 | FfiError::kInvalidRedzone => Err(SendError::InvalidRedzone), |
| 1204 | } |
| 1205 | } |
| 1206 | } |
| 1207 | |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1208 | /// Allows sending messages on a channel with a type-safe API. |
| 1209 | /// |
| 1210 | /// Use [`EventLoopRuntime::make_raw_sender`] to create one of these. |
| 1211 | pub struct Sender<T>( |
| 1212 | // SAFETY: This must accept messages of type `T`. |
| 1213 | RawSender, |
| 1214 | PhantomData<*mut T>, |
| 1215 | ) |
| 1216 | where |
| 1217 | for<'a> T: FollowWith<'a>, |
| 1218 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 1219 | |
| 1220 | impl<T> Sender<T> |
| 1221 | where |
| 1222 | for<'a> T: FollowWith<'a>, |
| 1223 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 1224 | { |
| 1225 | /// Returns an object which can be used to build a message. |
| 1226 | /// |
| 1227 | /// # Examples |
| 1228 | /// |
| 1229 | /// ``` |
| 1230 | /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder}; |
| 1231 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) { |
| 1232 | /// let mut builder = sender.make_builder(); |
| 1233 | /// let pong = PongBuilder::new(builder.fbb()).finish(); |
| 1234 | /// builder.send(pong); |
| 1235 | /// # } |
| 1236 | /// ``` |
| 1237 | /// |
| 1238 | /// You can bail out of building a message and build another one: |
| 1239 | /// ``` |
| 1240 | /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder}; |
| 1241 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) { |
| 1242 | /// let mut builder1 = sender.make_builder(); |
| 1243 | /// builder1.fbb(); |
Adam Snaider | 0126d83 | 2023-10-03 09:59:34 -0700 | [diff] [blame] | 1244 | /// drop(builder1); |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1245 | /// let mut builder2 = sender.make_builder(); |
| 1246 | /// let pong = PongBuilder::new(builder2.fbb()).finish(); |
| 1247 | /// builder2.send(pong); |
| 1248 | /// # } |
| 1249 | /// ``` |
| 1250 | /// but you cannot build two messages at the same time with a single builder: |
| 1251 | /// ```compile_fail |
| 1252 | /// # use pong_rust_fbs::aos::examples::{Pong, PongBuilder}; |
| 1253 | /// # fn compile_check(mut sender: aos_events_event_loop_runtime::Sender<Pong<'static>>) { |
| 1254 | /// let mut builder1 = sender.make_builder(); |
| 1255 | /// let mut builder2 = sender.make_builder(); |
| 1256 | /// PongBuilder::new(builder2.fbb()).finish(); |
| 1257 | /// PongBuilder::new(builder1.fbb()).finish(); |
| 1258 | /// # } |
| 1259 | /// ``` |
| 1260 | pub fn make_builder(&mut self) -> Builder<T> { |
| 1261 | Builder(self.0.make_builder(), PhantomData) |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | /// Used for building a message. See [`Sender::make_builder`] for details. |
| 1266 | pub struct Builder<'sender, T>( |
| 1267 | // SAFETY: This must accept messages of type `T`. |
| 1268 | RawBuilder<'sender>, |
| 1269 | PhantomData<*mut T>, |
| 1270 | ) |
| 1271 | where |
| 1272 | for<'a> T: FollowWith<'a>, |
| 1273 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>; |
| 1274 | |
| 1275 | impl<'sender, T> Builder<'sender, T> |
| 1276 | where |
| 1277 | for<'a> T: FollowWith<'a>, |
| 1278 | for<'a> <T as FollowWith<'a>>::Inner: Follow<'a>, |
| 1279 | { |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 1280 | pub fn fbb( |
| 1281 | &mut self, |
| 1282 | ) -> &mut FlatBufferBuilder<'sender, ChannelPreallocatedAllocator<'sender>> { |
Brian Silverman | 90221f8 | 2022-08-22 23:46:09 -0700 | [diff] [blame] | 1283 | self.0.fbb() |
| 1284 | } |
| 1285 | |
| 1286 | pub fn send<'a>( |
| 1287 | self, |
| 1288 | root: flatbuffers::WIPOffset<<T as FollowWith<'a>>::Inner>, |
| 1289 | ) -> Result<(), SendError> { |
| 1290 | // SAFETY: We guarantee this is the right type based on invariants for our type. |
| 1291 | unsafe { self.0.send(root) } |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | #[derive(Clone, Copy, Eq, PartialEq, Debug, Error)] |
| 1296 | pub enum SendError { |
| 1297 | #[error("messages have been sent too fast on this channel")] |
| 1298 | MessagesSentTooFast, |
| 1299 | #[error("invalid redzone data, shared memory corruption detected")] |
| 1300 | InvalidRedzone, |
| 1301 | } |
| 1302 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1303 | #[repr(transparent)] |
| 1304 | #[derive(Clone, Copy)] |
| 1305 | pub struct Context<'context>(&'context ffi::aos::Context); |
| 1306 | |
| 1307 | impl fmt::Debug for Context<'_> { |
| 1308 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1309 | f.debug_struct("Context") |
| 1310 | .field("monotonic_event_time", &self.monotonic_event_time()) |
| 1311 | .field("monotonic_remote_time", &self.monotonic_remote_time()) |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1312 | .field("realtime_event_time", &self.realtime_event_time()) |
| 1313 | .field("realtime_remote_time", &self.realtime_remote_time()) |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1314 | .field("queue_index", &self.queue_index()) |
| 1315 | .field("remote_queue_index", &self.remote_queue_index()) |
| 1316 | .field("size", &self.data().map(|data| data.len())) |
| 1317 | .field("buffer_index", &self.buffer_index()) |
| 1318 | .field("source_boot_uuid", &self.source_boot_uuid()) |
| 1319 | .finish() |
| 1320 | } |
| 1321 | } |
| 1322 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1323 | impl<'context> Context<'context> { |
| 1324 | pub fn monotonic_event_time(self) -> MonotonicInstant { |
| 1325 | MonotonicInstant(self.0.monotonic_event_time) |
| 1326 | } |
| 1327 | |
| 1328 | pub fn monotonic_remote_time(self) -> MonotonicInstant { |
| 1329 | MonotonicInstant(self.0.monotonic_remote_time) |
| 1330 | } |
| 1331 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1332 | pub fn realtime_event_time(self) -> RealtimeInstant { |
| 1333 | RealtimeInstant(self.0.realtime_event_time) |
| 1334 | } |
| 1335 | |
| 1336 | pub fn realtime_remote_time(self) -> RealtimeInstant { |
| 1337 | RealtimeInstant(self.0.realtime_remote_time) |
| 1338 | } |
| 1339 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1340 | pub fn queue_index(self) -> u32 { |
| 1341 | self.0.queue_index |
| 1342 | } |
| 1343 | pub fn remote_queue_index(self) -> u32 { |
| 1344 | self.0.remote_queue_index |
| 1345 | } |
| 1346 | |
| 1347 | pub fn data(self) -> Option<&'context [u8]> { |
| 1348 | if self.0.data.is_null() { |
| 1349 | None |
| 1350 | } else { |
| 1351 | // SAFETY: |
| 1352 | // * `u8` has no alignment requirements |
| 1353 | // * It must be a single initialized flatbuffers buffer |
| 1354 | // * The borrow in `self.0` guarantees it won't be modified for `'context` |
| 1355 | Some(unsafe { slice::from_raw_parts(self.0.data as *const u8, self.0.size) }) |
| 1356 | } |
| 1357 | } |
| 1358 | |
| 1359 | pub fn buffer_index(self) -> i32 { |
| 1360 | self.0.buffer_index |
| 1361 | } |
| 1362 | |
| 1363 | pub fn source_boot_uuid(self) -> &'context Uuid { |
| 1364 | // SAFETY: `self` has a valid C++ object. C++ guarantees that the return value will be |
| 1365 | // valid until something changes the context, which is `'context`. |
| 1366 | Uuid::from_bytes_ref(&self.0.source_boot_uuid) |
| 1367 | } |
| 1368 | } |
| 1369 | |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 1370 | /// The type returned from [`EventLoopRuntime::on_run`], see there for details. |
| 1371 | // SAFETY: If this outlives the parent EventLoop, the C++ code will LOG(FATAL). |
| 1372 | #[repr(transparent)] |
| 1373 | pub struct OnRun(Pin<Box<ffi::aos::OnRunForRust>>); |
| 1374 | |
Adam Snaider | a3317c8 | 2023-10-02 16:02:36 -0700 | [diff] [blame] | 1375 | impl Future for &'_ OnRun { |
Brian Silverman | 76f4836 | 2022-08-24 21:09:08 -0700 | [diff] [blame] | 1376 | type Output = (); |
| 1377 | |
| 1378 | fn poll(self: Pin<&mut Self>, _: &mut std::task::Context) -> Poll<()> { |
| 1379 | if self.0.is_running() { |
| 1380 | Poll::Ready(()) |
| 1381 | } else { |
| 1382 | Poll::Pending |
| 1383 | } |
| 1384 | } |
| 1385 | } |
| 1386 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1387 | /// Represents a `aos::monotonic_clock::time_point` in a natural Rust way. This |
| 1388 | /// is intended to have the same API as [`std::time::Instant`], any missing |
| 1389 | /// functionality can be added if useful. |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1390 | #[repr(transparent)] |
| 1391 | #[derive(Clone, Copy, Eq, PartialEq)] |
| 1392 | pub struct MonotonicInstant(i64); |
| 1393 | |
| 1394 | impl MonotonicInstant { |
| 1395 | /// `aos::monotonic_clock::min_time`, commonly used as a sentinel value. |
| 1396 | pub const MIN_TIME: Self = Self(i64::MIN); |
| 1397 | |
| 1398 | pub fn is_min_time(self) -> bool { |
| 1399 | self == Self::MIN_TIME |
| 1400 | } |
| 1401 | |
| 1402 | pub fn duration_since_epoch(self) -> Option<Duration> { |
| 1403 | if self.is_min_time() { |
| 1404 | None |
| 1405 | } else { |
| 1406 | Some(Duration::from_nanos(self.0.try_into().expect( |
| 1407 | "monotonic_clock::time_point should always be after the epoch", |
| 1408 | ))) |
| 1409 | } |
| 1410 | } |
| 1411 | } |
| 1412 | |
Adam Snaider | cc8c2f7 | 2023-06-25 20:56:13 -0700 | [diff] [blame] | 1413 | impl Add<Duration> for MonotonicInstant { |
| 1414 | type Output = MonotonicInstant; |
| 1415 | |
| 1416 | fn add(self, rhs: Duration) -> Self::Output { |
| 1417 | Self(self.0 + i64::try_from(rhs.as_nanos()).unwrap()) |
| 1418 | } |
| 1419 | } |
| 1420 | |
Adam Snaider | de51c67 | 2023-09-28 21:55:43 -0700 | [diff] [blame] | 1421 | impl From<MonotonicInstant> for i64 { |
| 1422 | fn from(value: MonotonicInstant) -> Self { |
| 1423 | value.0 |
| 1424 | } |
| 1425 | } |
| 1426 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1427 | impl fmt::Debug for MonotonicInstant { |
| 1428 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 1429 | self.duration_since_epoch().fmt(f) |
| 1430 | } |
| 1431 | } |
| 1432 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1433 | #[repr(transparent)] |
| 1434 | #[derive(Clone, Copy, Eq, PartialEq)] |
| 1435 | pub struct RealtimeInstant(i64); |
| 1436 | |
| 1437 | impl RealtimeInstant { |
| 1438 | pub const MIN_TIME: Self = Self(i64::MIN); |
| 1439 | |
| 1440 | pub fn is_min_time(self) -> bool { |
| 1441 | self == Self::MIN_TIME |
| 1442 | } |
| 1443 | |
| 1444 | pub fn duration_since_epoch(self) -> Option<Duration> { |
| 1445 | if self.is_min_time() { |
| 1446 | None |
| 1447 | } else { |
| 1448 | Some(Duration::from_nanos(self.0.try_into().expect( |
| 1449 | "monotonic_clock::time_point should always be after the epoch", |
| 1450 | ))) |
| 1451 | } |
| 1452 | } |
| 1453 | } |
| 1454 | |
Adam Snaider | de51c67 | 2023-09-28 21:55:43 -0700 | [diff] [blame] | 1455 | impl From<RealtimeInstant> for i64 { |
| 1456 | fn from(value: RealtimeInstant) -> Self { |
| 1457 | value.0 |
| 1458 | } |
| 1459 | } |
| 1460 | |
Ryan Yin | 683a867 | 2022-11-09 20:44:20 -0800 | [diff] [blame] | 1461 | impl fmt::Debug for RealtimeInstant { |
| 1462 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 1463 | self.duration_since_epoch().fmt(f) |
| 1464 | } |
| 1465 | } |
| 1466 | |
Brian Silverman | 9809c5f | 2022-07-23 16:12:23 -0700 | [diff] [blame] | 1467 | mod panic_waker { |
| 1468 | use std::task::{RawWaker, RawWakerVTable, Waker}; |
| 1469 | |
| 1470 | unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker { |
| 1471 | raw_panic_waker() |
| 1472 | } |
| 1473 | |
| 1474 | unsafe fn noop(_data: *const ()) {} |
| 1475 | |
| 1476 | unsafe fn wake_panic(_data: *const ()) { |
| 1477 | panic!("Nothing should wake EventLoopRuntime's waker"); |
| 1478 | } |
| 1479 | |
| 1480 | const PANIC_WAKER_VTABLE: RawWakerVTable = |
| 1481 | RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop); |
| 1482 | |
| 1483 | fn raw_panic_waker() -> RawWaker { |
| 1484 | RawWaker::new(std::ptr::null(), &PANIC_WAKER_VTABLE) |
| 1485 | } |
| 1486 | |
| 1487 | pub fn panic_waker() -> Waker { |
| 1488 | // SAFETY: The implementations of the RawWakerVTable functions do what is required of them. |
| 1489 | unsafe { Waker::from_raw(raw_panic_waker()) } |
| 1490 | } |
| 1491 | } |
| 1492 | |
| 1493 | use panic_waker::panic_waker; |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 1494 | |
| 1495 | pub struct ExitHandle(UniquePtr<CppExitHandle>); |
| 1496 | |
| 1497 | impl ExitHandle { |
| 1498 | /// Exits the EventLoops represented by this handle. You probably want to immediately return |
Adam Snaider | b40b72f | 2023-11-02 19:40:55 -0700 | [diff] [blame] | 1499 | /// from the context this is called in. Awaiting [`ExitHandle::exit`] instead of using this |
| 1500 | /// function is an easy way to do that. |
Adam Snaider | 163800b | 2023-07-12 00:21:17 -0400 | [diff] [blame] | 1501 | pub fn exit_sync(mut self) { |
| 1502 | self.0.as_mut().unwrap().Exit(); |
| 1503 | } |
| 1504 | |
| 1505 | /// Exits the EventLoops represented by this handle, and never returns. Immediately awaiting |
| 1506 | /// this from a [`EventLoopRuntime::spawn`]ed task is usually what you want, it will ensure |
| 1507 | /// that no more code from that task runs. |
| 1508 | pub async fn exit(self) -> Never { |
| 1509 | self.exit_sync(); |
| 1510 | pending().await |
| 1511 | } |
| 1512 | } |
| 1513 | |
| 1514 | impl From<UniquePtr<CppExitHandle>> for ExitHandle { |
| 1515 | fn from(inner: UniquePtr<ffi::aos::ExitHandle>) -> Self { |
| 1516 | Self(inner) |
| 1517 | } |
| 1518 | } |
Adam Snaider | 34072e1 | 2023-10-03 10:04:25 -0700 | [diff] [blame] | 1519 | |
| 1520 | pub struct ChannelPreallocatedAllocator<'a> { |
| 1521 | buffer: &'a mut [u8], |
| 1522 | } |
| 1523 | |
| 1524 | impl<'a> ChannelPreallocatedAllocator<'a> { |
| 1525 | pub fn new(buffer: &'a mut [u8]) -> Self { |
| 1526 | Self { buffer } |
| 1527 | } |
| 1528 | } |
| 1529 | |
| 1530 | #[derive(Debug, Error)] |
| 1531 | #[error("Can't allocate more memory with a fixed size allocator")] |
| 1532 | pub struct OutOfMemory; |
| 1533 | |
| 1534 | // SAFETY: Allocator follows the required behavior. |
| 1535 | unsafe impl Allocator for ChannelPreallocatedAllocator<'_> { |
| 1536 | type Error = OutOfMemory; |
| 1537 | fn grow_downwards(&mut self) -> Result<(), Self::Error> { |
| 1538 | // Fixed size allocator can't grow. |
| 1539 | Err(OutOfMemory) |
| 1540 | } |
| 1541 | |
| 1542 | fn len(&self) -> usize { |
| 1543 | self.buffer.len() |
| 1544 | } |
| 1545 | } |
| 1546 | |
| 1547 | impl Deref for ChannelPreallocatedAllocator<'_> { |
| 1548 | type Target = [u8]; |
| 1549 | |
| 1550 | fn deref(&self) -> &Self::Target { |
| 1551 | self.buffer |
| 1552 | } |
| 1553 | } |
| 1554 | |
| 1555 | impl DerefMut for ChannelPreallocatedAllocator<'_> { |
| 1556 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 1557 | self.buffer |
| 1558 | } |
| 1559 | } |