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