rrtk 0.7.0-beta.0

Rust Robotics ToolKit
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
// SPDX-License-Identifier: BSD-3-Clause
// Copyright 2024-2026 UxuginPython
//!# Rust Robotics ToolKit
//!**A set of algorithms and other tools for robotics in Rust.**
//!
//!It is almost entirely `no_std` and most things work without `alloc`. It does not currently integrate with any API directly. This may be added in the future, probably through another crate.
//!## Feature Flags
//!- `alloc` - Enable items requiring dynamic allocation through Rust's builtin `alloc` crate.
//!- `std` - Enable items requiring the Rust standard library. Requires `alloc` feature. Enabled by default.
//!- `devices` - Enable RRTK's graph-based device system.
//!- `libm` - Use [`libm`](https://crates.io/crates/libm) for float exponentiation when `std` is not available.
//!- `micromath` - Use [`micromath`](https://crates.io/crates/micromath) for float exponentiation
//!  when `std` and `libm` are unavailable.
//!- `internal_enhanced_float` - Do not enable this yourself.
//!
//!RRTK prefers **`std`** over **`libm`** and `libm` over **`micromath`** when multiple are
//!available.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(all(
    feature = "internal_enhanced_float",
    not(feature = "std"),
    not(feature = "libm"),
    not(feature = "micromath")
))]
compile_error!("internal_enhanced_float must only be enabled by another feature.");
#[cfg(feature = "std")]
use alloc::sync::Arc;
#[cfg(feature = "std")]
use std::sync::{Mutex, RwLock};
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::rc::Rc;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::cell::RefCell;
use core::fmt;
use core::marker::PhantomData;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Not, Sub, SubAssign};
use fmt::Debug;
mod command;
pub mod compile_time_integer;
mod datum;
#[cfg(feature = "devices")]
pub mod devices;
pub mod dimensions;
#[cfg(feature = "internal_enhanced_float")]
mod enhanced_float;
pub use dimensions::*;
mod motion_profile;
mod state;
pub mod streams;
pub mod stulta;
pub use command::*;
pub use datum::*;
#[cfg(feature = "internal_enhanced_float")]
use enhanced_float::*;
pub use motion_profile::*;
pub use state::*;
///Error types used for various things in RRTK. Currently they are only zero-sized types, but this
///may change.
pub mod error {
    use super::*;
    ///The error type used when a `TryFrom` fails.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct CannotConvert;
    ///A type for when multiple things may error independently and both errors must be able to be
    ///returned. This only keeps track of when at least one has errored; it should usually be used
    ///in combination with [`Option`], [`Result`], or the [`NothingOrError`] type alias of `Result`.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub enum PossibleDoubleError<E> {
        ///The variant for when Side A errors and Side B does not.
        A(E),
        ///The variant for when Side B errors and Side A does not.
        B(E),
        ///The variant for when both Side A and Side B error.
        AB(E, E),
    }
    impl<E> PossibleDoubleError<E> {
        ///Constructs `PossibleDoubleError` from a possible Side A error and a possible Side B
        ///error. Returns `None` if neither side has an error and `Some(PossibleDoubleError)` if at
        ///least one side does. You may want to use this in conjunction with
        ///[`NothingOrErrorExt::from_option`].
        #[inline]
        pub fn from_options(a: Option<E>, b: Option<E>) -> Option<Self> {
            match (a, b) {
                (None, None) => None,
                (Some(a), None) => Some(Self::A(a)),
                (None, Some(b)) => Some(Self::B(b)),
                (Some(a), Some(b)) => Some(Self::AB(a, b)),
            }
        }
    }
}
///A derivative of position: position, velocity, or acceleration.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PositionDerivative {
    ///Where you are.
    Position,
    ///How fast you're going.
    Velocity,
    ///How fast how fast you're going's changing.
    Acceleration,
}
impl TryFrom<MotionProfilePiece> for PositionDerivative {
    type Error = error::CannotConvert;
    fn try_from(was: MotionProfilePiece) -> Result<Self, error::CannotConvert> {
        match was {
            MotionProfilePiece::BeforeStart | MotionProfilePiece::Complete => {
                Err(error::CannotConvert)
            }
            MotionProfilePiece::InitialAcceleration | MotionProfilePiece::EndAcceleration => {
                Ok(PositionDerivative::Acceleration)
            }
            MotionProfilePiece::ConstantVelocity => Ok(PositionDerivative::Velocity),
        }
    }
}
///Coefficients for a PID controller.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PIDKValues {
    ///Proportional coefficient.
    pub kp: f32,
    ///Integral coefficient.
    pub ki: f32,
    ///Derivative coefficient.
    pub kd: f32,
}
impl PIDKValues {
    ///Constructor for [`PIDKValues`].
    pub const fn new(kp: f32, ki: f32, kd: f32) -> Self {
        Self { kp, ki, kd }
    }
    ///Calculate the control variable using the coefficients given error, its integral, and its
    ///derivative.
    #[inline]
    pub const fn evaluate(&self, error: f32, error_integral: f32, error_derivative: f32) -> f32 {
        self.kp * error + self.ki * error_integral + self.kd * error_derivative
    }
}
///A set of PID k-values for controlling each position derivative.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PositionDerivativeDependentPIDKValues {
    ///Use these k-values when controlling position.
    pub position: PIDKValues,
    ///Use these k-values when controlling velocity.
    pub velocity: PIDKValues,
    ///Use these k-values when controlling acceleration.
    pub acceleration: PIDKValues,
}
impl PositionDerivativeDependentPIDKValues {
    ///Constructor for [`PositionDerivativeDependentPIDKValues`].
    pub const fn new(position: PIDKValues, velocity: PIDKValues, acceleration: PIDKValues) -> Self {
        Self {
            position,
            velocity,
            acceleration,
        }
    }
    ///Get the k-values for a specific position derivative.
    #[inline]
    pub const fn get_k_values(&self, position_derivative: PositionDerivative) -> PIDKValues {
        match position_derivative {
            PositionDerivative::Position => self.position,
            PositionDerivative::Velocity => self.velocity,
            PositionDerivative::Acceleration => self.acceleration,
        }
    }
    ///Calculate the control variable using the coefficients for a given position derivative given
    ///error, its integral, and its derivative.
    #[inline]
    pub const fn evaluate(
        &self,
        position_derivative: PositionDerivative,
        error: f32,
        error_integral: f32,
        error_derivative: f32,
    ) -> f32 {
        self.get_k_values(position_derivative)
            .evaluate(error, error_integral, error_derivative)
    }
}
///A generic output type when something may return an error, nothing, or something with a
///timestamp.
pub type Output<T, E> = Result<Option<Datum<T>>, E>;
///Returned from [`TimeGetter`] objects, which may return either a time or an error.
pub type TimeOutput<E> = Result<Time, E>;
///Returned when something may return either nothing or an error.
pub type NothingOrError<E> = Result<(), E>;
///An extension trait for [`NothingOrError`].
pub trait NothingOrErrorExt<E> {
    ///Converts from `Option<E>` to `NothingOrError<E>`.
    fn from_option(option: Option<E>) -> Self;
    ///Converts from `NothingOrError<E>` to `Option<E>`.
    fn into_option(self) -> Option<E>;
}
impl<E> NothingOrErrorExt<E> for NothingOrError<E> {
    fn from_option(option: Option<E>) -> Self {
        match option {
            None => Ok(()),
            Some(x) => {
                core::hint::cold_path();
                Err(x)
            }
        }
    }
    fn into_option(self) -> Option<E> {
        match self {
            Ok(()) => None,
            Err(x) => {
                core::hint::cold_path();
                Some(x)
            }
        }
    }
}
///An object for getting the absolute time.
pub trait TimeGetter<E: Clone + Debug>: Updatable<E> {
    ///Get the time.
    fn get(&self) -> TimeOutput<E>;
}
///An object that can return a value, like a [`Getter`], for a given time.
pub trait Chronology<T> {
    ///Get a value at a time.
    fn get(&self, time: Time) -> Option<Datum<T>>;
}
///Something with an [`update`](Updatable::update) method. Mostly for subtraiting.
pub trait Updatable<E: Clone + Debug> {
    ///As this trait is very generic, exactly what this does will be very dependent on the
    ///implementor.
    fn update(&mut self) -> NothingOrError<E>;
}
///Something with a [`get`](Getter::get) method. Structs implementing this will often be chained for easier data
///processing, with a struct having other implementors in fields which will have some operation
///performed on their output before it being passed on. Data processing Getters with other Getters
///as fields can be referred to as streams, though this is only in naming and trait-wise there is
///no distinction. The other common use for this trait is encoders. These should not be called
///streams.
pub trait Getter<G, E: Clone + Debug>: Updatable<E> {
    ///Get something.
    fn get(&self) -> Output<G, E>;
    ///Update with [`Updatable`] and then call [`get`](Getter::get).
    fn update_and_get(&mut self) -> Output<G, E> {
        self.update()?;
        self.get()
    }
}
///Something with a [`set`](Settable::set) method. Usually used for motors and other mechanical components and
///systems. This trait too is fairly broad.
pub trait Settable<S, E: Clone + Debug>: Updatable<E> {
    ///Set something to a value. For example, this could set a motor to a voltage.
    fn set(&mut self, value: S) -> NothingOrError<E>;
}
///Feeds the output of a [`Getter`] into a [`Settable`].
///
///There are two ways of thinking about how this does error handling. The first way is this
///flowchart:
#[doc = include_str!("../feeder-flowchart.svg")]
///
///Here is corresponding pseudocode. This is one of few cases that could probably be simplified if
///Rust had goto.
///```text
///getter.update();
///if (update errored) {
///    goto X;
///}
///getter.get();
///if (get returned Ok(Some(_)) ) {
///    settable.set(value get returned);
///    if (set errored) {
///        goto Y;
///    }
///}
///X: settable.update();
///Y: error_collection_magic()
///```
///
///The second way to think about this error handling is closer to how the code is actually written.
///Here it is:
///
///There is a Getter Side and a Settable Side. The Getter Side calls `update` on the getter and, if
///that didn't fail, calls `get`. The Getter Side is literally just [`Getter::update_and_get`] and a
///little logic for feeding into the Settable Side.
///
///The Settable Side calls `set` on the settable if `get` ran and got
///`Ok(Some(_))` and then calls `update` on the settable as long as `set` either didn't run or
///succeeded. There's then some more magic to collect the possible errors into
///[`PossibleDoubleError`](error::PossibleDoubleError).
///
///That's pretty hard to parse in English, so here's some Rust-like pseudocode:
///```text
///fn getter_side {
///    getter.update()?;
///    getter.get()?;
///}
///fn settable_side {
///    //true as long as both:
///    //1. getter.get() ran, i.e., getter.update() didn't error
///    //2. getter.get() returned Ok(Some(_))
///    if have_something_from_getter {
///        settable.set(something_from_getter)?;
///    }
///    //The only way for settable_side to return before here is if both:
///    //1. settable.set() ran (see previous comment)
///    //2. settable.set() errored directly
///    settable.update()?;
///}
///getter_side();
///settable_side();
///error_collection_magic()
///```
///Also, here's a flowchart:
#[doc = include_str!("../feeder-flowchart-2.svg")]
///
///(For some reason, this flowchart svg doesn't show up quite correctly in Rustdoc. Inkscape,
///Firefox, and Chromium all read it fine.)
///
///As for `PossibleDoubleError`, Side A corresponds to the Getter Side and Side B corresponds to the
///Settable Side.
pub struct Feeder<T, G, S, E>
where
    G: Getter<T, E>,
    S: Settable<T, E>,
    E: Clone + Debug,
{
    getter: G,
    settable: S,
    phantom_t: PhantomData<T>,
    phantom_e: PhantomData<E>,
}
impl<T, G, S, E> Feeder<T, G, S, E>
where
    G: Getter<T, E>,
    S: Settable<T, E>,
    E: Clone + Debug,
{
    ///Constructor for `Feeder`.
    pub const fn new(getter: G, settable: S) -> Self {
        Self {
            getter,
            settable,
            phantom_t: PhantomData,
            phantom_e: PhantomData,
        }
    }
}
impl<T, G, S, E> Updatable<error::PossibleDoubleError<E>> for Feeder<T, G, S, E>
where
    G: Getter<T, E>,
    S: Settable<T, E>,
    E: Clone + Debug,
{
    fn update(&mut self) -> NothingOrError<error::PossibleDoubleError<E>> {
        //"Getter Side"
        let gotten = self.getter.update_and_get();
        let (gotten_ok, gotten_err) = match gotten {
            Ok(Some(datum)) => (Some(datum.value), None),
            Ok(None) => (None, None),
            Err(err) => (None, Some(err)),
        };
        //"Settable Side"
        //We can't use the parameters from the outer item, so we use these parameters, which are
        //the same types respectively, to make the compiler happy.
        fn settable_side<Si, Ti, Ei>(settable: &mut Si, set_value: Option<Ti>) -> NothingOrError<Ei>
        where
            Si: Settable<Ti, Ei>,
            Ei: Clone + Debug,
        {
            if let Some(value) = set_value {
                settable.set(value)?;
            }
            settable.update()
        }
        let settable_out = settable_side(&mut self.settable, gotten_ok);
        let settable_err = settable_out.err();
        //"error collection magic"
        NothingOrError::from_option(error::PossibleDoubleError::from_options(
            gotten_err,
            settable_err,
        ))
    }
}
///Because [`Getter`]s always return a timestamp (as long as they don't return `Err(_)` or
///`Ok(None)`), we can use this to treat them like [`TimeGetter`]s.
pub struct TimeGetterFromGetter<T, G: Getter<T, E>, E: Clone + Debug> {
    getter: G,
    none_error: E,
    phantom_t: PhantomData<T>,
}
impl<T, G: Getter<T, E>, E: Clone + Debug> TimeGetterFromGetter<T, G, E> {
    ///Constructor for [`TimeGetterFromGetter`].
    pub const fn new(getter: G, none_error: E) -> Self {
        Self {
            getter,
            none_error,
            phantom_t: PhantomData,
        }
    }
}
impl<T, G: Getter<T, E>, E: Clone + Debug> TimeGetter<E> for TimeGetterFromGetter<T, G, E> {
    fn get(&self) -> TimeOutput<E> {
        match self.getter.get() {
            Err(error) => Err(error),
            Ok(None) => Err(self.none_error.clone()),
            Ok(Some(datum)) => Ok(datum.time),
        }
    }
}
impl<T, G: Getter<T, E>, E: Clone + Debug> Updatable<E> for TimeGetterFromGetter<T, G, E> {
    fn update(&mut self) -> NothingOrError<E> {
        Ok(())
    }
}
///As histories return values at times, we can ask them to return values at the time of now or now
///with a delta. This makes that much easier and is the recommended way of following
///[`MotionProfile`]s.
pub struct GetterFromChronology<T, C: Chronology<T>, TG: TimeGetter<E>, E: Clone + Debug> {
    chronology: C,
    time_getter: TG,
    time_delta: Time,
    phantom_t: PhantomData<T>,
    phantom_e: PhantomData<E>,
}
impl<T, C: Chronology<T>, TG: TimeGetter<E>, E: Clone + Debug> GetterFromChronology<T, C, TG, E> {
    ///Constructor such that the time in the request to the chronology will be directly that returned
    ///from the [`TimeGetter`] with no delta.
    pub const fn new_no_delta(chronology: C, time_getter: TG) -> Self {
        Self {
            chronology,
            time_getter,
            time_delta: Time::ZERO,
            phantom_t: PhantomData,
            phantom_e: PhantomData,
        }
    }
    ///Constructor such that the times requested from the [`Chronology`] will begin at zero where zero
    ///is the moment this constructor is called.
    pub fn new_start_at_zero(chronology: C, time_getter: TG) -> Result<Self, E> {
        let time_delta = -time_getter.get()?;
        Ok(Self {
            chronology,
            time_getter,
            time_delta,
            phantom_t: PhantomData,
            phantom_e: PhantomData,
        })
    }
    ///Constructor such that the times requested from the [`Chronology`] will start at a given time with
    ///that time defined as the moment of construction.
    pub fn new_custom_start(chronology: C, time_getter: TG, start: Time) -> Result<Self, E> {
        let time_delta = start - time_getter.get()?;
        Ok(Self {
            chronology,
            time_getter,
            time_delta,
            phantom_t: PhantomData,
            phantom_e: PhantomData,
        })
    }
    ///Constructor with a custom time delta.
    pub const fn new_custom_delta(chronology: C, time_getter: TG, time_delta: Time) -> Self {
        Self {
            chronology,
            time_getter,
            time_delta,
            phantom_t: PhantomData,
            phantom_e: PhantomData,
        }
    }
    ///Set the time delta.
    pub const fn set_delta(&mut self, time_delta: Time) {
        self.time_delta = time_delta;
    }
    ///Define now as a given time in the chronology. Mostly used when construction and use are far
    ///apart in time.
    pub fn set_time(&mut self, time: Time) -> NothingOrError<E> {
        let time_delta = time - self.time_getter.get()?;
        self.time_delta = time_delta;
        Ok(())
    }
}
//TODO: Maybe one day with specialization, it will be possible to update self.chronology only if it
//implements it. I think that's really the only reason that Chronology: Updatable (then History: Updatable)
//stayed around for so long: It's easier to force empty impls every once in a while than to figure
//out a really wierd specialization thing. Overall, though, you almost never actually need an
//Updatable Chronology anyway, so the bound really doesn't make that much sense in the first place.
impl<T, C: Chronology<T>, TG: TimeGetter<E>, E: Clone + Debug> Updatable<E>
    for GetterFromChronology<T, C, TG, E>
{
    fn update(&mut self) -> NothingOrError<E> {
        self.time_getter.update()?;
        Ok(())
    }
}
impl<T, C: Chronology<T>, TG: TimeGetter<E>, E: Clone + Debug> Getter<T, E>
    for GetterFromChronology<T, C, TG, E>
{
    fn get(&self) -> Output<T, E> {
        let time = self.time_getter.get()?;
        Ok(match self.chronology.get(time + self.time_delta) {
            Some(datum) => Some(Datum::new(time, datum.value)),
            None => None,
        })
    }
}
///Getter for returning a constant value.
pub struct ConstantGetter<T, TG, E>
where
    T: Clone,
    TG: TimeGetter<E>,
    E: Clone + Debug,
{
    time_getter: TG,
    value: T,
    phantom_e: PhantomData<E>,
}
impl<T, TG, E> ConstantGetter<T, TG, E>
where
    T: Clone,
    TG: TimeGetter<E>,
    E: Clone + Debug,
{
    ///Constructor for [`ConstantGetter`].
    pub const fn new(time_getter: TG, value: T) -> Self {
        Self {
            time_getter,
            value,
            phantom_e: PhantomData,
        }
    }
}
impl<T, TG, E> Getter<T, E> for ConstantGetter<T, TG, E>
where
    T: Clone,
    TG: TimeGetter<E>,
    E: Clone + Debug,
{
    fn get(&self) -> Output<T, E> {
        let time = self.time_getter.get()?;
        Ok(Some(Datum::new(time, self.value.clone())))
    }
}
impl<T, TG, E> Settable<T, E> for ConstantGetter<T, TG, E>
where
    T: Clone,
    TG: TimeGetter<E>,
    E: Clone + Debug,
{
    fn set(&mut self, value: T) -> NothingOrError<E> {
        self.value = value;
        Ok(())
    }
}
impl<T, TG, E> Updatable<E> for ConstantGetter<T, TG, E>
where
    T: Clone,
    TG: TimeGetter<E>,
    E: Clone + Debug,
{
    fn update(&mut self) -> NothingOrError<E> {
        self.time_getter.update()?;
        Ok(())
    }
}
///Getter always returning `Ok(None)`.
#[derive(Default)]
pub struct NoneGetter;
impl NoneGetter {
    ///Constructor for [`NoneGetter`]. Since [`NoneGetter`] is a unit struct, you can use this, its
    ///[`Default`] implementation, or just the struct's name.
    pub const fn new() -> Self {
        Self
    }
}
impl<T, E: Clone + Debug> Getter<T, E> for NoneGetter {
    fn get(&self) -> Output<T, E> {
        Ok(None)
    }
}
impl<E: Clone + Debug> Updatable<E> for NoneGetter {
    fn update(&mut self) -> NothingOrError<E> {
        Ok(())
    }
}
impl<E: Clone + Debug> TimeGetter<E> for Time {
    fn get(&self) -> TimeOutput<E> {
        Ok(*self)
    }
}
impl<E: Clone + Debug> Updatable<E> for Time {
    fn update(&mut self) -> NothingOrError<E> {
        Ok(())
    }
}
///Get the newer of two [`Datum`] objects.
pub fn latest<T>(dat1: Datum<T>, dat2: Datum<T>) -> Datum<T> {
    if dat1.time >= dat2.time { dat1 } else { dat2 }
}
///[`Updatable`], [`Getter`], [`Settable`], and [`TimeGetter`] are passed through `Box`,
///`Rc<RefCell<T>>`, `Arc<RwLock<T>>`, and `Arc<Mutex<T>>`, but this cannot be done safely for
///references involving raw pointer dereferencing. This is a wrapper struct that provides this
///functionality for `*mut T`, `*const RwLock<T>`, and `*const Mutex<T>`. It's constructor is
///`unsafe fn`, so this is considered sound.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct PointerDereferencer<P> {
    pointer: P,
}
impl<P> PointerDereferencer<P> {
    ///The constructor for `PointerDereferencer`. Although this constructor itself does not run any
    ///unsafe code, it is `unsafe fn` since this type inherently performs unsafe functions. See the
    ///[type documentation](`PointerDereferencer`) for more information.
    ///
    ///Although it is technically possible to construct a `PointerDereferencer<P>` where `P` is not
    ///a raw pointer, there is no valid reason to do so and the object would be entirely useless.
    pub const unsafe fn new(pointer: P) -> Self {
        Self { pointer }
    }
    ///Returns the inner pointer that the wrapper contains by consuming it. Due to the fact that
    ///pointers are `Copy`, [`copy_ptr`](Self::copy_ptr), which does not consume `self` and is
    ///`const fn`, is preferred in almost all cases however.
    #[inline]
    pub fn into_ptr(self) -> P {
        self.pointer
    }
}
impl<P: Clone> PointerDereferencer<P> {
    ///Clones and returns the inner pointer that the wrapper contains. Due to the fact that
    ///pointers are `Copy`, [`copy_ptr`](Self::copy_ptr) is nearly always preferred both for
    ///clarity and because it is `const fn` however.
    #[inline]
    pub fn clone_ptr(&self) -> P {
        self.pointer.clone()
    }
}
impl<P: Copy> PointerDereferencer<P> {
    ///This function is be identical to [`clone_ptr`](Self::clone_ptr) when `P: Copy`. However,
    ///`copy_ptr` should be preferred where possible because, unlike `clone_inner`, it is
    ///`const fn`. It is also clearer that the clone is very light.
    #[inline]
    pub const fn copy_ptr(&self) -> P {
        self.pointer
    }
}
macro_rules! as_dyn_updatable {
    ($return_type:ty) => {
        //The way documentation for these function has to work is unfortunate, but there's not
        //really a better way.
        #[allow(missing_docs)]
        #[inline]
        pub const fn as_dyn_updatable<E: Clone + Debug>(&self) -> PointerDereferencer<$return_type>
        where
            T: Updatable<E>,
        {
            let ptr = self.copy_ptr() as $return_type;
            unsafe { PointerDereferencer::new(ptr) }
        }
    };
}
macro_rules! as_dyn_getter {
    ($return_type:ty) => {
        #[allow(missing_docs)]
        #[inline]
        pub const fn as_dyn_getter<U, E: Clone + Debug>(&self) -> PointerDereferencer<$return_type>
        where
            T: Getter<U, E>,
        {
            let ptr = self.copy_ptr() as $return_type;
            unsafe { PointerDereferencer::new(ptr) }
        }
    };
}
macro_rules! as_dyn_settable {
    ($return_type:ty) => {
        #[allow(missing_docs)]
        #[inline]
        pub const fn as_dyn_settable<U, E: Clone + Debug>(
            &self,
        ) -> PointerDereferencer<$return_type>
        where
            T: Settable<U, E>,
        {
            let ptr = self.copy_ptr() as $return_type;
            unsafe { PointerDereferencer::new(ptr) }
        }
    };
}
macro_rules! as_dyn_time_getter {
    ($return_type:ty) => {
        #[allow(missing_docs)]
        #[inline]
        pub const fn as_dyn_time_getter<E: Clone + Debug>(
            &self,
        ) -> PointerDereferencer<$return_type>
        where
            T: TimeGetter<E>,
        {
            let ptr = self.copy_ptr() as $return_type;
            unsafe { PointerDereferencer::new(ptr) }
        }
    };
}
//TODO: Chronology is different because it's not always Updatable and so probably isn't mutable.
//Figure out what to do about that. (Currently, as_dyn_chronology only works for mutable references
//and there are no impls for Rc<RefCell>, etc., either mutable or immutable.)
macro_rules! as_dyn_chronology {
    ($return_type:ty) => {
        #[allow(missing_docs)]
        #[inline]
        pub const fn as_dyn_chronology<U>(&self) -> PointerDereferencer<$return_type>
        where
            T: Chronology<U>,
        {
            let ptr = self.copy_ptr() as $return_type;
            unsafe { PointerDereferencer::new(ptr) }
        }
    };
}
//TODO: Remove the notices below the docs when you do actually learn more.
///These functions get a `PointerDereferencer<*mut dyn Trait>` from a `PointerDereferencer<*mut T>`
///where `T: Trait`. Because raw pointers are `Copy`, they only require `&self` and do not consume
///the original `PointerDereferencer`. Unfortunately `T` currently must be `Sized` due to language
///limitations.
impl<T> PointerDereferencer<*mut T> {
    as_dyn_updatable!(*mut (dyn Updatable<E> + '_));
    as_dyn_getter!(*mut (dyn Getter<U, E> + '_));
    as_dyn_settable!(*mut (dyn Settable<U, E> + '_));
    as_dyn_time_getter!(*mut (dyn TimeGetter<E> + '_));
    as_dyn_chronology!(*mut (dyn Chronology<U> + '_));
}
///These functions get a `PointerDereferencer<*const RwLock<dyn Trait>>` from a
///`PointerDereferencer<*const RwLock<T>>` where `T: Trait`. Because raw pointers are `Copy`, they
///only require `&self` and do not consume the original `PointerDereferencer`. Unfortunately `T`
///currently must be `Sized` due to language limitations.
#[cfg(feature = "std")]
impl<T> PointerDereferencer<*const RwLock<T>> {
    as_dyn_updatable!(*const RwLock<dyn Updatable<E> + '_>);
    as_dyn_getter!(*const RwLock<dyn Getter<U, E> + '_>);
    as_dyn_settable!(*const RwLock<dyn Settable<U, E> + '_>);
    as_dyn_time_getter!(*const RwLock<dyn TimeGetter<E> + '_>);
}
///These functions get a `PointerDereferencer<*const Mutex<dyn Trait>>` from a
///`PointerDereferencer<*const Mutex<T>>` where `T: Trait`. Because raw pointers are `Copy`, they
///only require `&self` and do not consume the original `PointerDereferencer`. Unfortunately `T`
///currently must be `Sized` due to language limitations.
#[cfg(feature = "std")]
impl<T> PointerDereferencer<*const Mutex<T>> {
    as_dyn_updatable!(*const Mutex<dyn Updatable<E> + '_>);
    as_dyn_getter!(*const Mutex<dyn Getter<U, E> + '_>);
    as_dyn_settable!(*const Mutex<dyn Settable<U, E> + '_>);
    as_dyn_time_getter!(*const Mutex<dyn TimeGetter<E> + '_>);
}
//There are Chronology impls for RwLock<C> and Mutex<C> where C: Chronology. It is necessary to
//implement Updatable etc. for *const RwLock<T> and *const Mutex<T> directly rather than doing it
//more generically like for Chronology because they require mutability.
impl<T> PointerDereferencer<*const T> {
    as_dyn_chronology!(*const (dyn Chronology<U> + '_));
}
//FIXME: Make one of these work if you can, preferably From since it implies Into.
/*impl<P> From<PointerDereferencer<P>> for P {
    fn from(was: PointerDereferencer<P>) -> Self {
        was.into_inner()
    }
}*/
/*impl<P> Into<P> for PointerDereferencer<P> {
    fn into(self) -> P {
        self.into_inner()
    }
}*/
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E> for PointerDereferencer<*mut U> {
    fn update(&mut self) -> NothingOrError<E> {
        unsafe { (*self.pointer).update() }
    }
}
impl<T, G: ?Sized + Getter<T, E>, E: Clone + Debug> Getter<T, E> for PointerDereferencer<*mut G> {
    fn get(&self) -> Output<T, E> {
        unsafe { (*self.pointer).get() }
    }
}
impl<T, S: ?Sized + Settable<T, E>, E: Clone + Debug> Settable<T, E>
    for PointerDereferencer<*mut S>
{
    fn set(&mut self, value: T) -> NothingOrError<E> {
        unsafe { (*self.pointer).set(value) }
    }
}
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E> for PointerDereferencer<*mut TG> {
    fn get(&self) -> TimeOutput<E> {
        unsafe { (*self.pointer).get() }
    }
}
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for PointerDereferencer<*mut C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        unsafe { (*self.pointer).get(time) }
    }
}
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for PointerDereferencer<*const C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        unsafe { (*self.pointer).get(time) }
    }
}
#[cfg(feature = "std")]
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E>
    for PointerDereferencer<*const RwLock<U>>
{
    fn update(&mut self) -> NothingOrError<E> {
        unsafe { (*self.pointer).write() }
            .expect("RRTK failed to acquire RwLock write lock for Updatable")
            .update()
    }
}
#[cfg(feature = "std")]
impl<G: ?Sized + Getter<T, E>, T, E: Clone + Debug> Getter<T, E>
    for PointerDereferencer<*const RwLock<G>>
{
    fn get(&self) -> Output<T, E> {
        unsafe { (*self.pointer).read() }
            .expect("RRTK failed to acquire RwLock read lock for Getter")
            .get()
    }
}
#[cfg(feature = "std")]
impl<S: ?Sized + Settable<T, E>, T, E: Clone + Debug> Settable<T, E>
    for PointerDereferencer<*const RwLock<S>>
{
    fn set(&mut self, value: T) -> NothingOrError<E> {
        unsafe { (*self.pointer).write() }
            .expect("RRTK failed to acquire RwLock write lock for Settable")
            .set(value)
    }
}
#[cfg(feature = "std")]
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E>
    for PointerDereferencer<*const RwLock<TG>>
{
    fn get(&self) -> TimeOutput<E> {
        unsafe { (*self.pointer).read() }
            .expect("RRTK failed to acquire RwLock read lock for TimeGetter")
            .get()
    }
}
#[cfg(feature = "std")]
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E>
    for PointerDereferencer<*const Mutex<U>>
{
    fn update(&mut self) -> NothingOrError<E> {
        unsafe { (*self.pointer).lock() }
            .expect("RRTK failed to acquire Mutex lock for Updatable")
            .update()
    }
}
#[cfg(feature = "std")]
impl<G: ?Sized + Getter<T, E>, T, E: Clone + Debug> Getter<T, E>
    for PointerDereferencer<*const Mutex<G>>
{
    fn get(&self) -> Output<T, E> {
        unsafe { (*self.pointer).lock() }
            .expect("RRTK failed to acquire Mutex lock for Getter")
            .get()
    }
}
#[cfg(feature = "std")]
impl<S: ?Sized + Settable<T, E>, T, E: Clone + Debug> Settable<T, E>
    for PointerDereferencer<*const Mutex<S>>
{
    fn set(&mut self, value: T) -> NothingOrError<E> {
        unsafe { (*self.pointer).lock() }
            .expect("RRTK failed to acquire Mutex lock for Settable")
            .set(value)
    }
}
#[cfg(feature = "std")]
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E>
    for PointerDereferencer<*const Mutex<TG>>
{
    fn get(&self) -> TimeOutput<E> {
        unsafe { (*self.pointer).lock() }
            .expect("RRTK failed to acquire Mutex lock for TimeGetter")
            .get()
    }
}
#[cfg(feature = "alloc")]
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E> for Box<U> {
    fn update(&mut self) -> NothingOrError<E> {
        (**self).update()
    }
}
#[cfg(feature = "alloc")]
impl<G: ?Sized + Getter<T, E>, T, E: Clone + Debug> Getter<T, E> for Box<G> {
    fn get(&self) -> Output<T, E> {
        (**self).get()
    }
}
#[cfg(feature = "alloc")]
impl<S: ?Sized + Settable<T, E>, T, E: Clone + Debug> Settable<T, E> for Box<S> {
    fn set(&mut self, value: T) -> NothingOrError<E> {
        (**self).set(value)
    }
}
#[cfg(feature = "alloc")]
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E> for Box<TG> {
    fn get(&self) -> TimeOutput<E> {
        (**self).get()
    }
}
#[cfg(feature = "alloc")]
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for Box<C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        (**self).get(time)
    }
}
#[cfg(feature = "alloc")]
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E> for Rc<RefCell<U>> {
    fn update(&mut self) -> NothingOrError<E> {
        self.borrow_mut().update()
    }
}
#[cfg(feature = "alloc")]
impl<G: ?Sized + Getter<T, E>, T, E: Clone + Debug> Getter<T, E> for Rc<RefCell<G>> {
    fn get(&self) -> Output<T, E> {
        self.borrow().get()
    }
}
#[cfg(feature = "alloc")]
impl<S: ?Sized + Settable<T, E>, T, E: Clone + Debug> Settable<T, E> for Rc<RefCell<S>> {
    fn set(&mut self, value: T) -> NothingOrError<E> {
        self.borrow_mut().set(value)
    }
}
#[cfg(feature = "alloc")]
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E> for Rc<RefCell<TG>> {
    fn get(&self) -> TimeOutput<E> {
        self.borrow().get()
    }
}
#[cfg(feature = "std")]
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E> for Arc<RwLock<U>> {
    fn update(&mut self) -> NothingOrError<E> {
        self.write()
            .expect("RRTK failed to acquire RwLock write lock for Updatable")
            .update()
    }
}
#[cfg(feature = "std")]
impl<G: ?Sized + Getter<T, E>, T, E: Clone + Debug> Getter<T, E> for Arc<RwLock<G>> {
    fn get(&self) -> Output<T, E> {
        self.read()
            .expect("RRTK failed to acquire RwLock read lock for Getter")
            .get()
    }
}
#[cfg(feature = "std")]
impl<S: ?Sized + Settable<T, E>, T, E: Clone + Debug> Settable<T, E> for Arc<RwLock<S>> {
    fn set(&mut self, value: T) -> NothingOrError<E> {
        self.write()
            .expect("RRTK failed to acquire RwLock write lock for Settable")
            .set(value)
    }
}
#[cfg(feature = "std")]
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E> for Arc<RwLock<TG>> {
    fn get(&self) -> TimeOutput<E> {
        self.read()
            .expect("RRTK failed to acquire RwLock read lock for TimeGetter")
            .get()
    }
}
#[cfg(feature = "std")]
impl<U: ?Sized + Updatable<E>, E: Clone + Debug> Updatable<E> for Arc<Mutex<U>> {
    fn update(&mut self) -> NothingOrError<E> {
        self.lock()
            .expect("RRTK failed to acquire Mutex lock for Updatable")
            .update()
    }
}
#[cfg(feature = "std")]
impl<G: ?Sized + Getter<T, E>, T, E: Clone + Debug> Getter<T, E> for Arc<Mutex<G>> {
    fn get(&self) -> Output<T, E> {
        self.lock()
            .expect("RRTK failed to acquire Mutex lock for Getter")
            .get()
    }
}
#[cfg(feature = "std")]
impl<S: ?Sized + Settable<T, E>, T, E: Clone + Debug> Settable<T, E> for Arc<Mutex<S>> {
    fn set(&mut self, value: T) -> NothingOrError<E> {
        self.lock()
            .expect("RRTK failed to acquire Mutex lock for Settable")
            .set(value)
    }
}
#[cfg(feature = "std")]
impl<TG: ?Sized + TimeGetter<E>, E: Clone + Debug> TimeGetter<E> for Arc<Mutex<TG>> {
    fn get(&self) -> TimeOutput<E> {
        self.lock()
            .expect("RRTK failed to acquire Mutex lock for TimeGetter")
            .get()
    }
}
#[cfg(feature = "alloc")]
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for Rc<C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        (**self).get(time)
    }
}
#[cfg(feature = "std")]
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for Arc<C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        (**self).get(time)
    }
}
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for RefCell<C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        self.borrow().get(time)
    }
}
#[cfg(feature = "std")]
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for RwLock<C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        self.read()
            .expect("RRTK failed to acquire RwLock read lock for Chronology")
            .get(time)
    }
}
#[cfg(feature = "std")]
impl<T, C: ?Sized + Chronology<T>> Chronology<T> for Mutex<C> {
    fn get(&self, time: Time) -> Option<Datum<T>> {
        self.lock()
            .expect("RRTK failed to acquire Mutex lock for Chronology")
            .get(time)
    }
}