|
| 1 | +/* |
| 2 | + * Copyright (c) godot-rust; Bromeon and contributors. |
| 3 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | + * file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 6 | + */ |
| 7 | + |
| 8 | +use std::mem; |
| 9 | + |
| 10 | +/// Ergonomic late-initialization container with `ready()` support. |
| 11 | +/// |
| 12 | +/// While deferred initialization is generally seen as bad practice, it is often inevitable in game development. |
| 13 | +/// Godot in particular encourages initialization inside `ready()`, e.g. to access the scene tree after a node is inserted into it. |
| 14 | +/// The alternative to using this pattern is [`Option<T>`][option], which needs to be explicitly unwrapped with `unwrap()` or `expect()` each time. |
| 15 | +/// |
| 16 | +/// `OnReady<T>` should always be used as a field. There are two modes to use it: |
| 17 | +/// |
| 18 | +/// 1. **Automatic mode, using [`new()`](Self::new).**<br> |
| 19 | +/// Before `ready()` is called, all `OnReady` fields constructed with `new()` are automatically initialized, in the order of |
| 20 | +/// declaration. This means that you can safely access them in `ready()`.<br><br> |
| 21 | +/// 2. **Manual mode, using [`manual()`](Self::manual).**<br> |
| 22 | +/// These fields are left uninitialized until you call [`init()`][Self::init] on them. This is useful if you need more complex |
| 23 | +/// initialization scenarios than a closure allows. If you forget initialization, a panic will occur on first access. |
| 24 | +/// |
| 25 | +/// Conceptually, `OnReady<T>` is very close to [once_cell's `Lazy<T>`][lazy], with additional hooks into the Godot lifecycle. |
| 26 | +/// The absence of methods to check initialization state is deliberate: you don't need them if you follow the above two patterns. |
| 27 | +/// This container is not designed as a general late-initialization solution, but tailored to the `ready()` semantics of Godot. |
| 28 | +/// |
| 29 | +/// This type is not thread-safe. `ready()` runs on the main thread and you are expected to access its value on the main thread, as well. |
| 30 | +/// |
| 31 | +/// [option]: std::option::Option |
| 32 | +/// [lazy]: https://docs.rs/once_cell/1/once_cell/unsync/struct.Lazy.html |
| 33 | +/// |
| 34 | +/// # Example |
| 35 | +/// ``` |
| 36 | +/// use godot::prelude::*; |
| 37 | +/// |
| 38 | +/// #[derive(GodotClass)] |
| 39 | +/// #[class(base = Node)] |
| 40 | +/// struct MyClass { |
| 41 | +/// auto: OnReady<i32>, |
| 42 | +/// manual: OnReady<i32>, |
| 43 | +/// } |
| 44 | +/// |
| 45 | +/// #[godot_api] |
| 46 | +/// impl INode for MyClass { |
| 47 | +/// fn init(_base: Base<Node>) -> Self { |
| 48 | +/// Self { |
| 49 | +/// auto: OnReady::new(|| 11), |
| 50 | +/// manual: OnReady::manual(), |
| 51 | +/// } |
| 52 | +/// } |
| 53 | +/// |
| 54 | +/// fn ready(&mut self) { |
| 55 | +/// // self.auto is now ready with value 11. |
| 56 | +/// assert_eq!(*self.auto, 11); |
| 57 | +/// |
| 58 | +/// // self.manual needs to be initialized manually. |
| 59 | +/// self.manual.init(22); |
| 60 | +/// assert_eq!(*self.manual, 22); |
| 61 | +/// } |
| 62 | +/// } |
| 63 | +pub struct OnReady<T> { |
| 64 | + state: InitState<T>, |
| 65 | +} |
| 66 | + |
| 67 | +impl<T> OnReady<T> { |
| 68 | + /// Schedule automatic initialization before `ready()`. |
| 69 | + /// |
| 70 | + /// This guarantees that the value is initialized once `ready()` starts running. |
| 71 | + /// Until then, accessing the object may panic. In particular, the object is _not_ initialized on first use. |
| 72 | + /// |
| 73 | + /// The value is also initialized when you don't override `ready()`. |
| 74 | + /// |
| 75 | + /// For more control over initialization, use the [`OnReady::manual()`] constructor, followed by a [`self.init()`][OnReady::init] |
| 76 | + /// call during `ready()`. |
| 77 | + pub fn new<F>(init_fn: F) -> Self |
| 78 | + where |
| 79 | + F: FnOnce() -> T + 'static, |
| 80 | + { |
| 81 | + Self { |
| 82 | + state: InitState::AutoPrepared { |
| 83 | + initializer: Box::new(init_fn), |
| 84 | + }, |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + /// Leave uninitialized, expects manual initialization during `ready()`. |
| 89 | + /// |
| 90 | + /// If you use this method, you _must_ call [`init()`][Self::init] during the `ready()` callback, otherwise a panic will occur. |
| 91 | + pub fn manual() -> Self { |
| 92 | + Self { |
| 93 | + state: InitState::ManualUninitialized, |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + /// Runs manual initialization. |
| 98 | + /// |
| 99 | + /// # Panics |
| 100 | + /// - If `init()` was called before. |
| 101 | + /// - If this object was already provided with a closure during construction, in [`Self::new()`]. |
| 102 | + pub fn init(&mut self, value: T) { |
| 103 | + match &self.state { |
| 104 | + InitState::ManualUninitialized { .. } => { |
| 105 | + self.state = InitState::Initialized { value }; |
| 106 | + } |
| 107 | + InitState::AutoPrepared { .. } => { |
| 108 | + panic!("cannot call init() on auto-initialized OnReady objects") |
| 109 | + } |
| 110 | + InitState::AutoInitializing => { |
| 111 | + // SAFETY: Loading is ephemeral state that is only set in init_auto() and immediately overwritten. |
| 112 | + unsafe { std::hint::unreachable_unchecked() } |
| 113 | + } |
| 114 | + InitState::Initialized { .. } => { |
| 115 | + panic!("already initialized; did you call init() more than once?") |
| 116 | + } |
| 117 | + }; |
| 118 | + } |
| 119 | + |
| 120 | + /// Runs initialization. |
| 121 | + /// |
| 122 | + /// # Panics |
| 123 | + /// If the value is already initialized. |
| 124 | + pub(crate) fn init_auto(&mut self) { |
| 125 | + // Two branches needed, because mem::replace() could accidentally overwrite an already initialized value. |
| 126 | + match &self.state { |
| 127 | + InitState::ManualUninitialized => return, // skipped |
| 128 | + InitState::AutoPrepared { .. } => {} // handled below |
| 129 | + InitState::AutoInitializing => { |
| 130 | + // SAFETY: Loading is ephemeral state that is only set below and immediately overwritten. |
| 131 | + unsafe { std::hint::unreachable_unchecked() } |
| 132 | + } |
| 133 | + InitState::Initialized { .. } => panic!("OnReady object already initialized"), |
| 134 | + }; |
| 135 | + |
| 136 | + // Temporarily replace with dummy state, as it's not possible to take ownership of the initializer closure otherwise. |
| 137 | + let InitState::AutoPrepared { initializer } = |
| 138 | + mem::replace(&mut self.state, InitState::AutoInitializing) |
| 139 | + else { |
| 140 | + // SAFETY: condition checked above. |
| 141 | + unsafe { std::hint::unreachable_unchecked() } |
| 142 | + }; |
| 143 | + |
| 144 | + self.state = InitState::Initialized { |
| 145 | + value: initializer(), |
| 146 | + }; |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +// Panicking Deref is not best practice according to Rust, but constant get() calls are significantly less ergonomic and make it harder to |
| 151 | +// migrate between T and LateInit<T>, because all the accesses need to change. |
| 152 | +impl<T> std::ops::Deref for OnReady<T> { |
| 153 | + type Target = T; |
| 154 | + |
| 155 | + /// Returns a shared reference to the value. |
| 156 | + /// |
| 157 | + /// # Panics |
| 158 | + /// If the value is not yet initialized. |
| 159 | + fn deref(&self) -> &Self::Target { |
| 160 | + match &self.state { |
| 161 | + InitState::ManualUninitialized => { |
| 162 | + panic!("OnReady manual value uninitialized, did you call init()?") |
| 163 | + } |
| 164 | + InitState::AutoPrepared { .. } => { |
| 165 | + panic!("OnReady automatic value uninitialized, is only available in ready()") |
| 166 | + } |
| 167 | + InitState::AutoInitializing => unreachable!(), |
| 168 | + InitState::Initialized { value } => value, |
| 169 | + } |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +impl<T> std::ops::DerefMut for OnReady<T> { |
| 174 | + /// Returns an exclusive reference to the value. |
| 175 | + /// |
| 176 | + /// # Panics |
| 177 | + /// If the value is not yet initialized. |
| 178 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 179 | + match &mut self.state { |
| 180 | + InitState::Initialized { value } => value, |
| 181 | + InitState::ManualUninitialized { .. } | InitState::AutoPrepared { .. } => { |
| 182 | + panic!("value not yet initialized") |
| 183 | + } |
| 184 | + InitState::AutoInitializing => unreachable!(), |
| 185 | + } |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +// ---------------------------------------------------------------------------------------------------------------------------------------------- |
| 190 | + |
| 191 | +enum InitState<T> { |
| 192 | + ManualUninitialized, |
| 193 | + AutoPrepared { initializer: Box<dyn FnOnce() -> T> }, |
| 194 | + AutoInitializing, // needed because state cannot be empty |
| 195 | + Initialized { value: T }, |
| 196 | +} |
0 commit comments