geese 0.3.11

Dead-simple game event system for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use crate::const_type_id::*;
use crate::*;
use const_list::*;
use private::*;
use std::any::*;
use std::mem::*;

/// Dynamically determines whether a given type implements the provided trait.
macro_rules! implements {
    ($name: ident, $trait: ident) => {{
        use std::cell::*;

        struct TraitTest<'a, T: ?Sized> {
            is_trait: &'a Cell<bool>,
            data: PhantomData<T>,
        }

        impl<T: ?Sized> Clone for TraitTest<'_, T> {
            #[inline(always)]
            fn clone(&self) -> Self {
                self.is_trait.set(false);
                TraitTest {
                    is_trait: self.is_trait,
                    data: PhantomData,
                }
            }
        }

        impl<T: ?Sized + $trait> Copy for TraitTest<'_, T> {}

        let is_trait = Cell::new(true);

        _ = [TraitTest::<$name> {
            is_trait: &is_trait,
            data: PhantomData,
        }]
        .clone();

        is_trait.get()
    }};
}

/// Represents a collection of event handlers with internal state.
pub trait GeeseSystem: 'static + Sized {
    /// The set of dependencies that this system has.
    const DEPENDENCIES: Dependencies = dependencies();

    /// The set of events to which this system responds.
    const EVENT_HANDLERS: EventHandlers<Self> = event_handlers();

    /// Creates a new instance of the system for the given system handle.
    fn new(ctx: GeeseContextHandle<Self>) -> Self;
}

/// Denotes a list of system dependencies.
#[derive(Copy, Clone, Debug)]
pub struct Dependencies {
    /// The inner list of dependencies.
    inner: ConstList<'static, Dependency>,
}

impl Dependencies {
    /// Creates a new, empty list of dependencies.
    #[inline(always)]
    const fn new() -> Self {
        Self {
            inner: ConstList::new(),
        }
    }

    /// Adds the given type to the dependency list, returning the modified list.
    #[inline(always)]
    pub const fn with<S: DependencyRef>(&'static self) -> Self {
        self.with_dependency(Dependency::new::<S>())
    }

    /// Adds the given type to the dependency list, returning the modified list.
    #[inline(always)]
    pub const fn with_dependency(&'static self, dependency: Dependency) -> Self {
        Self {
            inner: self.inner.push(dependency),
        }
    }

    /// Gets a reference to the inner list of dependency holders.
    #[inline(always)]
    pub(crate) const fn as_inner(&self) -> &ConstList<'static, Dependency> {
        &self.inner
    }

    /// Determines the local index in this dependency list of the provided system.
    #[inline(always)]
    pub(crate) const fn index_of<S: GeeseSystem>(&self) -> Option<usize> {
        let mut i = 0;
        while i < self.inner.len() {
            if const_unwrap(self.inner.get(i))
                .dependency_id()
                .eq(&ConstTypeId::of::<S>())
            {
                return Some(i);
            }
            i += 1;
        }
        None
    }
}

/// Creates a new, empty list of dependencies.
#[inline(always)]
pub const fn dependencies() -> Dependencies {
    Dependencies::new()
}

/// Describes a system dependency.
#[derive(Copy, Clone, Debug)]
pub struct Dependency {
    /// A function which retrieves a descriptor at runtime.
    descriptor_getter: fn() -> Box<dyn SystemDescriptor>,
    /// The list of this dependency's subdependencies.
    dependencies: &'static Dependencies,
    /// Whether this dependency may be mutably borrowed.
    mutable: bool,
    /// The type ID of the system.
    type_id: ConstTypeId,
}

impl Dependency {
    /// Creates a new dependency for the provided type.
    #[inline(always)]
    pub const fn new<S: DependencyRef>() -> Self {
        Self {
            descriptor_getter: Self::get_descriptor::<S::System>,
            dependencies: &S::System::DEPENDENCIES,
            mutable: S::MUTABLE,
            type_id: ConstTypeId::of::<S::System>(),
        }
    }

    /// Gets the type ID of this dependency.
    #[inline(always)]
    pub(crate) const fn dependency_id(&self) -> ConstTypeId {
        self.type_id
    }

    /// Determines whether this dependency may be mutably borrowed.
    #[inline(always)]
    pub(crate) const fn mutable(&self) -> bool {
        self.mutable
    }

    /// Gets a descriptor for use with system instantiation.
    #[inline(always)]
    pub(crate) fn descriptor(&self) -> Box<dyn SystemDescriptor> {
        (self.descriptor_getter)()
    }

    /// Creates a descriptor for instantiation with the given system.
    #[inline(always)]
    fn get_descriptor<S: GeeseSystem>() -> Box<dyn SystemDescriptor> {
        Box::<TypedSystemDescriptor<S>>::default()
    }
}

/// Denotes a list of system methods that respond to events.
#[allow(unused_variables)]
pub struct EventHandlers<S: GeeseSystem> {
    /// The inner list of event handlers.
    inner: ConstList<'static, EventHandlerRaw>,
    /// Phantom data to mark the system as used.
    data: PhantomData<fn(S)>,
}

impl<S: GeeseSystem> EventHandlers<S> {
    /// Creates a new, empty list of event handlers.
    #[inline(always)]
    const fn new() -> Self {
        Self {
            inner: ConstList::new(),
            data: PhantomData,
        }
    }

    /// Adds the given event handler to the list, returning the modified list.
    #[inline(always)]
    pub const fn with<Q: MutableRef<S>, T: 'static + Send + Sync>(
        &'static self,
        handler: fn(Q, &T),
    ) -> Self {
        Self {
            inner: self.inner.push(EventHandlerRaw::new(handler)),
            data: PhantomData,
        }
    }

    /// Adds the given wrapped event handler to the list, returning the modified list.
    pub const fn with_handler(&'static self, handler: EventHandler<S>) -> Self {
        Self {
            inner: self.inner.push(handler.raw),
            data: PhantomData,
        }
    }

    /// Gets a reference to the inner list of event handlers.
    #[inline(always)]
    fn as_inner(&self) -> &ConstList<'_, EventHandlerRaw> {
        &self.inner
    }
}

impl<S: GeeseSystem> Copy for EventHandlers<S> {}

impl<S: GeeseSystem> Clone for EventHandlers<S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S: GeeseSystem> std::fmt::Debug for EventHandlers<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventHandlers")
            .field("inner", &self.inner)
            .finish()
    }
}

/// Creates a new, empty list of event handlers.
#[inline(always)]
pub const fn event_handlers<S: GeeseSystem>() -> EventHandlers<S> {
    EventHandlers::new()
}

/// Wraps an event handler function for a system.
pub struct EventHandler<S: GeeseSystem> {
    /// The inner event handler.
    raw: EventHandlerRaw,
    /// Phantom data to mark the system as used.
    data: PhantomData<fn(S)>,
}

impl<S: GeeseSystem> EventHandler<S> {
    /// Creates a new event handler to wrap the given function pointer.
    #[inline(always)]
    pub const fn new<Q: MutableRef<S>, T: 'static + Send + Sync>(handler: fn(Q, &T)) -> Self {
        Self {
            raw: EventHandlerRaw::new(handler),
            data: PhantomData,
        }
    }
}

impl<S: GeeseSystem> Copy for EventHandler<S> {}

impl<S: GeeseSystem> Clone for EventHandler<S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S: GeeseSystem> std::fmt::Debug for EventHandler<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventHandler")
            .field("raw", &self.raw)
            .finish()
    }
}

/// Describes an event handler for a system.
#[derive(Copy, Clone, Debug)]
pub(crate) struct EventHandlerRaw {
    /// A function that retrieves the type ID of the event.
    event_id: fn() -> TypeId,
    /// A reference to the event handler function.
    handler: EventInvoker,
}

impl EventHandlerRaw {
    /// Creates a new event handler to wrap the given function pointer.
    #[inline(always)]
    pub const fn new<S: GeeseSystem, Q: MutableRef<S>, T: 'static + Send + Sync>(
        handler: fn(Q, &T),
    ) -> Self {
        Self {
            event_id: TypeId::of::<T>,
            handler: EventInvoker::new(handler),
        }
    }

    /// Gets the type ID of the event to which this handler responds.
    #[inline(always)]
    pub fn event_id(&self) -> TypeId {
        (self.event_id)()
    }

    /// Obtains a reference to the event handler function.
    #[inline(always)]
    pub fn handler(&self) -> &EventInvoker {
        &self.handler
    }
}

/// Provides the ability to invoke an event handler method.
#[derive(Copy, Clone, Debug)]
pub(crate) struct EventInvoker {
    /// A function that casts the event and handler function to a concrete type,
    /// and then invokes the handler.
    pointer_flattener: Option<unsafe fn(*mut (), &dyn Any, *const ())>,
    /// The handler associated with this event invoker.
    handler: *const (),
}

impl EventInvoker {
    /// Creates a new event invoker to wrap the given function pointer.
    #[inline(always)]
    pub const fn new<S: GeeseSystem, Q: MutableRef<S>, T: 'static + Send + Sync>(
        handler: fn(Q, &T),
    ) -> Self {
        Self {
            pointer_flattener: Some(Self::pointer_flattener::<T>),
            handler: handler as *const (),
        }
    }

    /// Invokes the event using the given system pointer and event value.
    ///
    /// # Safety
    ///
    /// For this function to be sound, the system pointer must reference a valid
    /// instance of the system type associated with this event handler. No other references
    /// to the system must exist. Further, the provided value must be of the event type
    /// associated with this event handler.
    #[inline(always)]
    pub unsafe fn invoke(&self, system: *mut (), value: &dyn Any) {
        (self.pointer_flattener.unwrap_unchecked())(system, value, self.handler);
    }

    /// Invokes the provided pointer as a function handle with the given system and value as arguments.
    ///
    /// # Safety
    ///
    /// The pointer to run must be a valid event handler function that accepts the system and value
    /// as arguments. These must both refer to valid objects of the correct system and event type.
    #[inline(always)]
    unsafe fn pointer_flattener<T: 'static + Send + Sync>(
        system: *mut (),
        value: &dyn Any,
        to_run: *const (),
    ) {
        transmute::<_, fn(*mut (), &T)>(to_run)(system, value.downcast_ref().unwrap_unchecked())
    }
}

impl Default for EventInvoker {
    #[inline(always)]
    fn default() -> Self {
        Self {
            pointer_flattener: None,
            handler: std::ptr::null_mut(),
        }
    }
}

unsafe impl Send for EventInvoker {}
unsafe impl Sync for EventInvoker {}

/// Describes a system's properties and allows it to be instantiated.
pub(super) trait SystemDescriptor: 'static + Send + Sync {
    /// Creates a new system instance for the provided handle.
    fn create(&self, handle: Arc<ContextHandleInner>) -> Box<dyn Any>;

    /// The set of dependencies that this system has.
    fn dependencies(&self) -> &'static Dependencies;

    /// The number of dependencies that this system has.
    fn dependency_len(&self) -> usize;

    /// The event handlers associated with this system.
    fn event_handlers(&self) -> &'static ConstList<'static, EventHandlerRaw>;

    /// Whether references to this type may be safely shared across threads.
    fn is_sync(&self) -> bool;

    /// Gets the type ID associated with the given system.
    fn system_id(&self) -> TypeId;
}

/// Describes a certain system type's properties and allows it to be instantiated.
pub(crate) struct TypedSystemDescriptor<S: GeeseSystem>(PhantomData<fn(S)>);

impl<S: GeeseSystem> Default for TypedSystemDescriptor<S> {
    #[inline(always)]
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<S: GeeseSystem> SystemDescriptor for TypedSystemDescriptor<S> {
    fn create(&self, handle: Arc<ContextHandleInner>) -> Box<dyn Any> {
        Box::new(S::new(GeeseContextHandle::new(handle)))
    }

    fn dependencies(&self) -> &'static Dependencies {
        &S::DEPENDENCIES
    }

    fn dependency_len(&self) -> usize {
        const_eval!(S::DEPENDENCIES.as_inner().len(), usize, S)
    }

    fn event_handlers(&self) -> &'static ConstList<'static, EventHandlerRaw> {
        S::EVENT_HANDLERS.as_inner()
    }

    fn is_sync(&self) -> bool {
        implements!(S, Sync)
    }

    fn system_id(&self) -> TypeId {
        TypeId::of::<S>()
    }
}

/// Marks that a dependency may be mutably borrowed.
#[derive(Copy, Clone, Debug)]
pub struct Mut<S: GeeseSystem>(PhantomData<fn(S)>);

/// Determines whether the given list of dependencies, or any subdependency lists,
/// have unnecessary duplicates.
#[inline(always)]
pub(crate) const fn has_duplicate_dependencies(dependencies: &Dependencies) -> bool {
    let inner_deps = dependencies.as_inner();

    let mut i = 0;

    while i < inner_deps.len() {
        if has_duplicate_dependencies(const_unwrap(inner_deps.get(i)).dependencies) {
            return true;
        }

        let mut j = i + 1;

        while j < inner_deps.len() {
            if const_unwrap(inner_deps.get(i))
                .dependency_id()
                .eq(&const_unwrap(inner_deps.get(j)).dependency_id())
            {
                return true;
            }

            j += 1;
        }

        i += 1;
    }

    false
}

/// Describes a series of events that the context should execute.
pub trait EventQueue: Sized {
    /// Adds a single event to the queue.
    fn with<T: 'static + Send + Sync>(self, event: T) -> Self {
        self.with_boxed(Box::new(event))
    }

    /// Adds a single boxed event to the queue.
    fn with_boxed(self, event: Box<dyn Any + Send + Sync>) -> Self {
        self.with_many_boxed(std::iter::once(event))
    }

    /// Adds a buffer of events to the queue.
    fn with_buffer(self, events: EventBuffer) -> Self {
        self.with_many_boxed(events.events)
    }

    /// Adds a list of events to the queue.
    fn with_many<T: 'static + Send + Sync>(self, events: impl IntoIterator<Item = T>) -> Self {
        self.with_many_boxed(
            events
                .into_iter()
                .map(|x| Box::new(x) as Box<dyn Any + Send + Sync>),
        )
    }

    /// Adds a list of boxed events to the queue.
    fn with_many_boxed(self, events: impl IntoIterator<Item = Box<dyn Any + Send + Sync>>) -> Self;
}

/// Provides a backing implementation for multithreaded Geese contexts. This trait
/// allows for defining and customizing how multiple threads complete the work of a context.
pub trait GeeseThreadPool: 'static + Send + Sync {
    /// Sets a callback that threadpool workers should repeatedly invoke.
    fn set_callback(&self, callback: Option<Arc<dyn Fn() + Send + Sync>>);
}

/// Hides traits from being externally visible.
mod private {
    use super::*;

    /// Describes one system's dependency on another.
    pub trait DependencyRef {
        /// The underlying type of the dependency.
        type System: GeeseSystem;

        /// Whether the dependency may be mutably borrowed.
        const MUTABLE: bool;
    }

    impl<S: GeeseSystem> DependencyRef for S {
        type System = S;

        const MUTABLE: bool = false;
    }

    impl<S: GeeseSystem> DependencyRef for Mut<S> {
        type System = S;

        const MUTABLE: bool = true;
    }

    /// Trait that marks a type as a mutable reference. This is used to
    /// hide mutable references from `const` functions, so that they may
    /// be manipulated in a `const` context.
    pub trait MutableRef<T> {}

    impl<'a, T> MutableRef<T> for &'a mut T {}
}