cu29-runtime 0.15.0

Copper Runtime Runtime crate. Copper is an engine for robotics.
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
//! CopperList is the main data structure used by Copper to communicate between tasks.
//! It is a queue that can be used to store preallocated messages between tasks in memory order.
#[cfg(not(feature = "std"))]
extern crate alloc;

use alloc::alloc::{alloc_zeroed, handle_alloc_error};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::alloc::Layout;

use bincode::{Decode, Encode};
use core::fmt;

use core::fmt::Display;
use core::iter::{Chain, Rev};
use core::slice::{Iter as SliceIter, IterMut as SliceIterMut};
use cu29_traits::{CopperListTuple, ErasedCuStampedData, ErasedCuStampedDataSet};
use serde_derive::{Deserialize, Serialize};

const MAX_TASKS: usize = 512;

/// Not implemented yet.
/// This mask will be used to for example filter out necessary regions of a copper list between remote systems.
#[derive(Debug, Encode, Decode, PartialEq, Clone, Copy)]
pub struct CopperLiskMask {
    #[allow(dead_code)]
    mask: [u128; MAX_TASKS / 128 + 1],
}

/// Those are the possible states along the lifetime of a CopperList.
#[derive(Debug, Encode, Decode, Serialize, Deserialize, PartialEq, Copy, Clone)]
pub enum CopperListState {
    Free,
    Initialized,
    Processing,
    DoneProcessing,
    QueuedForSerialization,
    BeingSerialized,
}

impl Display for CopperListState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CopperListState::Free => write!(f, "Free"),
            CopperListState::Initialized => write!(f, "Initialized"),
            CopperListState::Processing => write!(f, "Processing"),
            CopperListState::DoneProcessing => write!(f, "DoneProcessing"),
            CopperListState::QueuedForSerialization => write!(f, "QueuedForSerialization"),
            CopperListState::BeingSerialized => write!(f, "BeingSerialized"),
        }
    }
}

#[derive(Debug, Encode, Decode, Serialize, Deserialize)]
pub struct CopperList<P: CopperListTuple> {
    pub id: u64,
    state: CopperListState,
    pub msgs: P, // This is generated from the runtime.
}

impl<P: CopperListTuple> Default for CopperList<P> {
    fn default() -> Self {
        CopperList {
            id: 0,
            state: CopperListState::Free,
            msgs: P::default(),
        }
    }
}

impl<P: CopperListTuple> CopperList<P> {
    // This is not the usual way to create a CopperList, this is just for testing.
    pub fn new(id: u64, msgs: P) -> Self {
        CopperList {
            id,
            state: CopperListState::Initialized,
            msgs,
        }
    }

    pub fn change_state(&mut self, new_state: CopperListState) {
        self.state = new_state; // TODO: probably wise here to enforce a state machine.
    }

    pub fn get_state(&self) -> CopperListState {
        self.state
    }
}

impl<P: CopperListTuple> ErasedCuStampedDataSet for CopperList<P> {
    fn cumsgs(&self) -> Vec<&dyn ErasedCuStampedData> {
        self.msgs.cumsgs()
    }
}

/// This structure maintains the entire memory needed by Copper for one loop for the inter tasks communication within a process.
/// P or Payload is typically a Tuple of various types of messages that are exchanged between tasks.
/// N is the maximum number of in flight Copper List the runtime can support.
pub struct CuListsManager<P: CopperListTuple, const N: usize> {
    data: Box<[CopperList<P>; N]>,
    length: usize,
    insertion_index: usize,
    current_cl_id: u64,
}

impl<P: CopperListTuple + fmt::Debug, const N: usize> fmt::Debug for CuListsManager<P, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CuListsManager")
            .field("data", &self.data)
            .field("length", &self.length)
            .field("insertion_index", &self.insertion_index)
            // Do not include on_drop field
            .finish()
    }
}

pub type Iter<'a, T> = Chain<Rev<SliceIter<'a, T>>, Rev<SliceIter<'a, T>>>;
pub type IterMut<'a, T> = Chain<Rev<SliceIterMut<'a, T>>, Rev<SliceIterMut<'a, T>>>;
pub type AscIter<'a, T> = Chain<SliceIter<'a, T>, SliceIter<'a, T>>;
pub type AscIterMut<'a, T> = Chain<SliceIterMut<'a, T>, SliceIterMut<'a, T>>;

/// Initializes fields that cannot be zeroed after allocating a zeroed
/// [`CopperList`].
pub trait CuListZeroedInit: CopperListTuple {
    /// Fixes up a zero-initialized copper list so that all internal fields are
    /// in a valid state.
    fn init_zeroed(&mut self);
}

impl<P: CopperListTuple + CuListZeroedInit, const N: usize> Default for CuListsManager<P, N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<P: CopperListTuple, const N: usize> CuListsManager<P, N> {
    pub fn new() -> Self
    where
        P: CuListZeroedInit,
    {
        // SAFETY: We allocate zeroed memory and immediately initialize required fields.
        let data = unsafe {
            let layout = Layout::new::<[CopperList<P>; N]>();
            let ptr = alloc_zeroed(layout) as *mut [CopperList<P>; N];
            if ptr.is_null() {
                handle_alloc_error(layout);
            }
            Box::from_raw(ptr)
        };
        let mut manager = CuListsManager {
            data,
            length: 0,
            insertion_index: 0,
            current_cl_id: 0,
        };

        for cl in manager.data.iter_mut() {
            cl.msgs.init_zeroed();
        }

        manager
    }

    /// Returns the current number of elements in the queue.
    ///
    #[inline]
    pub fn len(&self) -> usize {
        self.length
    }

    /// Returns `true` if the queue contains no elements.
    ///
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns `true` if the queue is full.
    ///
    #[inline]
    pub fn is_full(&self) -> bool {
        N == self.len()
    }

    /// Clears the queue.
    ///
    #[inline]
    pub fn clear(&mut self) {
        self.insertion_index = 0;
        self.length = 0;
    }

    #[inline]
    pub fn create(&mut self) -> Option<&mut CopperList<P>> {
        if self.is_full() {
            return None;
        }
        let result = &mut self.data[self.insertion_index];
        self.insertion_index = (self.insertion_index + 1) % N;
        self.length += 1;

        // We assign a unique id to each CopperList to be able to track them across their lifetime.
        result.id = self.current_cl_id;
        self.current_cl_id += 1;

        Some(result)
    }

    /// Returns the next copper-list id that will be assigned by [`create`](Self::create).
    #[inline]
    pub fn next_cl_id(&self) -> u64 {
        self.current_cl_id
    }

    /// Returns the most recently assigned copper-list id.
    ///
    /// Before the first call to [`create`](Self::create), this returns `0`.
    #[inline]
    pub fn last_cl_id(&self) -> u64 {
        self.current_cl_id.saturating_sub(1)
    }

    /// Peeks at the last element in the queue.
    #[inline]
    pub fn peek(&self) -> Option<&CopperList<P>> {
        if self.length == 0 {
            return None;
        }
        let index = if self.insertion_index == 0 {
            N - 1
        } else {
            self.insertion_index - 1
        };
        Some(&self.data[index])
    }

    #[inline]
    #[allow(dead_code)]
    fn drop_last(&mut self) {
        if self.length == 0 {
            return;
        }
        if self.insertion_index == 0 {
            self.insertion_index = N - 1;
        } else {
            self.insertion_index -= 1;
        }
        self.length -= 1;
    }

    #[inline]
    pub fn pop(&mut self) -> Option<&mut CopperList<P>> {
        if self.length == 0 {
            return None;
        }
        if self.insertion_index == 0 {
            self.insertion_index = N - 1;
        } else {
            self.insertion_index -= 1;
        }
        self.length -= 1;
        Some(&mut self.data[self.insertion_index])
    }

    /// Returns an iterator over the queue's contents.
    ///
    /// The iterator goes from the most recently pushed items to the oldest ones.
    ///
    #[inline]
    pub fn iter(&self) -> Iter<'_, CopperList<P>> {
        let (a, b) = self.data[0..self.length].split_at(self.insertion_index);
        a.iter().rev().chain(b.iter().rev())
    }

    /// Returns a mutable iterator over the queue's contents.
    ///
    /// The iterator goes from the most recently pushed items to the oldest ones.
    ///
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<'_, CopperList<P>> {
        let (a, b) = self.data.split_at_mut(self.insertion_index);
        a.iter_mut().rev().chain(b.iter_mut().rev())
    }

    /// Returns an ascending iterator over the queue's contents.
    ///
    /// The iterator goes from the least recently pushed items to the newest ones.
    ///
    #[inline]
    pub fn asc_iter(&self) -> AscIter<'_, CopperList<P>> {
        let (a, b) = self.data.split_at(self.insertion_index);
        b.iter().chain(a.iter())
    }

    /// Returns a mutable ascending iterator over the queue's contents.
    ///
    /// The iterator goes from the least recently pushed items to the newest ones.
    ///
    #[inline]
    pub fn asc_iter_mut(&mut self) -> AscIterMut<'_, CopperList<P>> {
        let (a, b) = self.data.split_at_mut(self.insertion_index);
        b.iter_mut().chain(a.iter_mut())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cu29_traits::{ErasedCuStampedData, ErasedCuStampedDataSet, MatchingTasks};
    use serde::{Deserialize, Serialize, Serializer};

    #[derive(Debug, Encode, Decode, PartialEq, Clone, Copy, Serialize, Deserialize, Default)]
    struct CuStampedDataSet(i32);

    impl ErasedCuStampedDataSet for CuStampedDataSet {
        fn cumsgs(&self) -> Vec<&dyn ErasedCuStampedData> {
            Vec::new()
        }
    }

    impl MatchingTasks for CuStampedDataSet {
        fn get_all_task_ids() -> &'static [&'static str] {
            &[]
        }
    }

    impl CuListZeroedInit for CuStampedDataSet {
        fn init_zeroed(&mut self) {}
    }

    #[test]
    fn empty_queue() {
        let q = CuListsManager::<CuStampedDataSet, 5>::new();

        assert!(q.is_empty());
        assert!(q.iter().next().is_none());
    }

    #[test]
    fn partially_full_queue() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;

        assert!(!q.is_empty());
        assert_eq!(q.len(), 3);

        let res: Vec<i32> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [3, 2, 1]);
    }

    #[test]
    fn full_queue() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;
        assert_eq!(q.len(), 5);

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [5, 4, 3, 2, 1]);
    }

    #[test]
    fn over_full_queue() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;
        assert!(q.create().is_none());
        assert_eq!(q.len(), 5);

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [5, 4, 3, 2, 1]);
    }

    #[test]
    fn clear() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;
        assert!(q.create().is_none());
        assert_eq!(q.len(), 5);

        q.clear();

        assert_eq!(q.len(), 0);
        assert!(q.iter().next().is_none());

        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;

        assert_eq!(q.len(), 3);

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [3, 2, 1]);
    }

    #[test]
    fn mutable_iterator() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;

        for x in q.iter_mut() {
            x.msgs.0 *= 2;
        }

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [10, 8, 6, 4, 2]);
    }

    #[test]
    fn test_drop_last() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;
        assert_eq!(q.len(), 5);

        q.drop_last();
        assert_eq!(q.len(), 4);

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [4, 3, 2, 1]);
    }

    #[test]
    fn test_pop() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;
        assert_eq!(q.len(), 5);

        let last = q.pop().unwrap();
        assert_eq!(last.msgs.0, 5);
        assert_eq!(q.len(), 4);

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [4, 3, 2, 1]);
    }

    #[test]
    fn test_peek() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();
        q.create().unwrap().msgs.0 = 1;
        q.create().unwrap().msgs.0 = 2;
        q.create().unwrap().msgs.0 = 3;
        q.create().unwrap().msgs.0 = 4;
        q.create().unwrap().msgs.0 = 5;
        assert_eq!(q.len(), 5);

        let last = q.peek().unwrap();
        assert_eq!(last.msgs.0, 5);
        assert_eq!(q.len(), 5);

        let res: Vec<_> = q.iter().map(|x| x.msgs.0).collect();
        assert_eq!(res, [5, 4, 3, 2, 1]);
    }

    #[test]
    fn next_and_last_cl_id_track_assigned_ids() {
        let mut q = CuListsManager::<CuStampedDataSet, 5>::new();

        // Before first allocation, next id is 0 and last id saturates to 0.
        assert_eq!(q.next_cl_id(), 0);
        assert_eq!(q.last_cl_id(), 0);

        let cl0 = q.create().unwrap();
        assert_eq!(cl0.id, 0);
        assert_eq!(q.next_cl_id(), 1);
        assert_eq!(q.last_cl_id(), 0);

        let cl1 = q.create().unwrap();
        assert_eq!(cl1.id, 1);
        assert_eq!(q.next_cl_id(), 2);
        assert_eq!(q.last_cl_id(), 1);
    }

    #[derive(Decode, Encode, Debug, PartialEq, Clone, Copy)]
    struct TestStruct {
        content: [u8; 10_000_000],
    }

    impl Default for TestStruct {
        fn default() -> Self {
            TestStruct {
                content: [0; 10_000_000],
            }
        }
    }

    impl ErasedCuStampedDataSet for TestStruct {
        fn cumsgs(&self) -> Vec<&dyn ErasedCuStampedData> {
            Vec::new()
        }
    }

    impl Serialize for TestStruct {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_i8(0)
        }
    }

    impl MatchingTasks for TestStruct {
        fn get_all_task_ids() -> &'static [&'static str] {
            &[]
        }
    }

    impl CuListZeroedInit for TestStruct {
        fn init_zeroed(&mut self) {}
    }

    #[test]
    fn be_sure_we_wont_stackoverflow_at_init() {
        let _ = CuListsManager::<TestStruct, 3>::new();
    }
}