cu29-traits 1.0.0-rc1

Common systems and robotics traits designed to decouple the components of your robotic system. These can be used independently from the Copper project.
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
//! Common copper traits and types for robotics systems.
//!
//! This crate is no_std compatible by default. Enable the "std" feature for additional
//! functionality like implementing `std::error::Error` for `CuError` and the
//! `new_with_cause` method that accepts types implementing `std::error::Error`.
//!
//! # Features
//!
//! - `std` (default): Enables standard library support
//!   - Implements `std::error::Error` for `CuError`
//!   - Adds `CuError::new_with_cause()` method for interop with std error types
//!
//! # no_std Usage
//!
//! To use without the standard library:
//!
//! ```toml
//! [dependencies]
//! cu29-traits = { version = "0.9", default-features = false }
//! ```

#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;

#[cfg(feature = "reflect")]
pub use bevy_reflect::Reflect;
use bincode::de::{BorrowDecoder, Decoder};
use bincode::enc::Encoder;
use bincode::enc::write::Writer;
use bincode::error::{DecodeError, EncodeError};
use bincode::{BorrowDecode, Decode as dDecode, Decode, Encode, Encode as dEncode};
use compact_str::CompactString;
use cu29_clock::{PartialCuTimeRange, Tov};
use serde::de::{self, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};

use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[cfg(feature = "std")]
use core::cell::Cell;
#[cfg(not(feature = "std"))]
use core::error::Error as CoreError;
use core::fmt::{Debug, Display, Formatter};
#[cfg(feature = "std")]
use std::error::Error;

#[cfg(not(feature = "std"))]
use spin::Mutex as SpinMutex;

// Type alias for the boxed error type to simplify conditional compilation
#[cfg(feature = "std")]
type DynError = dyn std::error::Error + Send + Sync + 'static;
#[cfg(not(feature = "std"))]
type DynError = dyn core::error::Error + Send + Sync + 'static;

/// A simple wrapper around String that implements Error trait.
/// Used for cloning and deserializing CuError causes.
#[derive(Debug)]
struct StringError(String);

impl Display for StringError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StringError {}

#[cfg(not(feature = "std"))]
impl core::error::Error for StringError {}

/// Common copper Error type.
///
/// This error type stores an optional cause as a boxed dynamic error,
/// allowing for proper error chaining while maintaining Clone and
/// Serialize/Deserialize support through custom implementations.
pub struct CuError {
    message: String,
    cause: Option<Box<DynError>>,
}

// Custom Debug implementation that formats cause as string
impl Debug for CuError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CuError")
            .field("message", &self.message)
            .field("cause", &self.cause.as_ref().map(|e| e.to_string()))
            .finish()
    }
}

// Custom Clone implementation - clones cause as StringError wrapper
impl Clone for CuError {
    fn clone(&self) -> Self {
        CuError {
            message: self.message.clone(),
            cause: self
                .cause
                .as_ref()
                .map(|e| Box::new(StringError(e.to_string())) as Box<DynError>),
        }
    }
}

// Custom Serialize - serializes cause as Option<String>
impl Serialize for CuError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("CuError", 2)?;
        state.serialize_field("message", &self.message)?;
        state.serialize_field("cause", &self.cause.as_ref().map(|e| e.to_string()))?;
        state.end()
    }
}

// Custom Deserialize - deserializes cause as StringError wrapper
impl<'de> Deserialize<'de> for CuError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct CuErrorHelper {
            message: String,
            cause: Option<String>,
        }

        let helper = CuErrorHelper::deserialize(deserializer)?;
        Ok(CuError {
            message: helper.message,
            cause: helper
                .cause
                .map(|s| Box::new(StringError(s)) as Box<DynError>),
        })
    }
}

impl Display for CuError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        let context_str = match &self.cause {
            Some(c) => c.to_string(),
            None => "None".to_string(),
        };
        write!(f, "{}\n   context:{}", self.message, context_str)?;
        Ok(())
    }
}

#[cfg(not(feature = "std"))]
impl CoreError for CuError {
    fn source(&self) -> Option<&(dyn CoreError + 'static)> {
        self.cause
            .as_deref()
            .map(|e| e as &(dyn CoreError + 'static))
    }
}

#[cfg(feature = "std")]
impl Error for CuError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.cause.as_deref().map(|e| e as &(dyn Error + 'static))
    }
}

impl From<&str> for CuError {
    fn from(s: &str) -> CuError {
        CuError {
            message: s.to_string(),
            cause: None,
        }
    }
}

impl From<String> for CuError {
    fn from(s: String) -> CuError {
        CuError {
            message: s,
            cause: None,
        }
    }
}

impl CuError {
    /// Creates a new CuError from an interned string index.
    /// Used by the cu_error! macro.
    ///
    /// The index is stored as a placeholder string `[interned:{index}]`.
    /// Actual string resolution happens at logging time via the unified logger.
    pub fn new(message_index: usize) -> CuError {
        CuError {
            message: format!("[interned:{}]", message_index),
            cause: None,
        }
    }

    /// Creates a new CuError with a message and an underlying cause.
    ///
    /// # Example
    /// ```
    /// use cu29_traits::CuError;
    ///
    /// let io_err = std::io::Error::other("io error");
    /// let err = CuError::new_with_cause("Failed to read file", io_err);
    /// ```
    #[cfg(feature = "std")]
    pub fn new_with_cause<E>(message: &str, cause: E) -> CuError
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        CuError {
            message: message.to_string(),
            cause: Some(Box::new(cause)),
        }
    }

    /// Creates a new CuError with a message and an underlying cause.
    #[cfg(not(feature = "std"))]
    pub fn new_with_cause<E>(message: &str, cause: E) -> CuError
    where
        E: core::error::Error + Send + Sync + 'static,
    {
        CuError {
            message: message.to_string(),
            cause: Some(Box::new(cause)),
        }
    }

    /// Adds or replaces the cause with a context string.
    ///
    /// This is useful for adding context to errors during propagation.
    ///
    /// # Example
    /// ```
    /// use cu29_traits::CuError;
    ///
    /// let err = CuError::from("base error").add_cause("additional context");
    /// ```
    pub fn add_cause(mut self, context: &str) -> CuError {
        self.cause = Some(Box::new(StringError(context.to_string())));
        self
    }

    /// Adds a cause error to this CuError (builder pattern).
    ///
    /// # Example
    /// ```
    /// use cu29_traits::CuError;
    ///
    /// let io_err = std::io::Error::other("io error");
    /// let err = CuError::from("Operation failed").with_cause(io_err);
    /// ```
    #[cfg(feature = "std")]
    pub fn with_cause<E>(mut self, cause: E) -> CuError
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        self.cause = Some(Box::new(cause));
        self
    }

    /// Adds a cause error to this CuError (builder pattern).
    #[cfg(not(feature = "std"))]
    pub fn with_cause<E>(mut self, cause: E) -> CuError
    where
        E: core::error::Error + Send + Sync + 'static,
    {
        self.cause = Some(Box::new(cause));
        self
    }

    /// Returns a reference to the underlying cause, if any.
    pub fn cause(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
        self.cause.as_deref()
    }

    /// Returns the error message.
    pub fn message(&self) -> &str {
        &self.message
    }
}

/// Creates a CuError with a message and cause in a single call.
///
/// This is a convenience function for use with `.map_err()`.
///
/// # Example
/// ```
/// use cu29_traits::with_cause;
///
/// let result: Result<(), std::io::Error> = Err(std::io::Error::other("io error"));
/// let cu_result = result.map_err(|e| with_cause("Failed to read file", e));
/// ```
#[cfg(feature = "std")]
pub fn with_cause<E>(message: &str, cause: E) -> CuError
where
    E: std::error::Error + Send + Sync + 'static,
{
    CuError::new_with_cause(message, cause)
}

/// Creates a CuError with a message and cause in a single call.
#[cfg(not(feature = "std"))]
pub fn with_cause<E>(message: &str, cause: E) -> CuError
where
    E: core::error::Error + Send + Sync + 'static,
{
    CuError::new_with_cause(message, cause)
}

// Generic Result type for copper.
pub type CuResult<T> = Result<T, CuError>;

#[cfg(feature = "std")]
thread_local! {
    static OBSERVED_ENCODE_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
}

#[cfg(not(feature = "std"))]
static OBSERVED_ENCODE_BYTES: SpinMutex<Option<usize>> = SpinMutex::new(None);

/// Starts observed byte counting for the current encode pass.
pub fn begin_observed_encode() {
    #[cfg(feature = "std")]
    OBSERVED_ENCODE_BYTES.with(|bytes| {
        debug_assert!(
            bytes.get().is_none(),
            "observed encode measurement must not be nested"
        );
        bytes.set(Some(0));
    });

    #[cfg(not(feature = "std"))]
    {
        let mut bytes = OBSERVED_ENCODE_BYTES.lock();
        debug_assert!(
            bytes.is_none(),
            "observed encode measurement must not be nested"
        );
        *bytes = Some(0);
    }
}

/// Ends observed byte counting and returns the total bytes written.
pub fn finish_observed_encode() -> usize {
    #[cfg(feature = "std")]
    {
        OBSERVED_ENCODE_BYTES.with(|bytes| bytes.replace(None).unwrap_or(0))
    }

    #[cfg(not(feature = "std"))]
    {
        OBSERVED_ENCODE_BYTES.lock().take().unwrap_or(0)
    }
}

/// Aborts any active observed byte counting session.
pub fn abort_observed_encode() {
    #[cfg(feature = "std")]
    OBSERVED_ENCODE_BYTES.with(|bytes| bytes.set(None));

    #[cfg(not(feature = "std"))]
    {
        *OBSERVED_ENCODE_BYTES.lock() = None;
    }
}

/// Returns the number of bytes written so far in the current observed encode pass.
pub fn observed_encode_bytes() -> usize {
    #[cfg(feature = "std")]
    {
        OBSERVED_ENCODE_BYTES.with(|bytes| bytes.get().unwrap_or(0))
    }

    #[cfg(not(feature = "std"))]
    {
        OBSERVED_ENCODE_BYTES.lock().as_ref().copied().unwrap_or(0)
    }
}

/// Records bytes written by an observed writer.
pub fn record_observed_encode_bytes(bytes: usize) {
    #[cfg(feature = "std")]
    OBSERVED_ENCODE_BYTES.with(|total| {
        if let Some(current) = total.get() {
            total.set(Some(current.saturating_add(bytes)));
        }
    });

    #[cfg(not(feature = "std"))]
    {
        let mut total = OBSERVED_ENCODE_BYTES.lock();
        if let Some(current) = *total {
            *total = Some(current.saturating_add(bytes));
        }
    }
}

/// A bincode writer wrapper that reports every encoded byte to Copper's
/// observation counters.
pub struct ObservedWriter<W> {
    inner: W,
}

impl<W> ObservedWriter<W> {
    pub const fn new(inner: W) -> Self {
        Self { inner }
    }

    pub fn into_inner(self) -> W {
        self.inner
    }

    pub fn inner(&self) -> &W {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut W {
        &mut self.inner
    }
}

impl<W: Writer> Writer for ObservedWriter<W> {
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
        self.inner.write(bytes)?;
        record_observed_encode_bytes(bytes.len());
        Ok(())
    }
}

/// Defines a basic write, append only stream trait to be able to log or send serializable objects.
pub trait WriteStream<E: Encode>: Debug + Send + Sync {
    fn log(&mut self, obj: &E) -> CuResult<()>;
    fn flush(&mut self) -> CuResult<()> {
        Ok(())
    }
    /// Optional byte count of the last successful `log` call, if the implementation can report it.
    fn last_log_bytes(&self) -> Option<usize> {
        None
    }
}

/// Defines the types of what can be logged in the unified logger.
#[derive(dEncode, dDecode, Copy, Clone, Debug, PartialEq)]
pub enum UnifiedLogType {
    Empty,             // Dummy default used as a debug marker
    StructuredLogLine, // This is for the structured logs (ie. debug! etc..)
    CopperList,        // This is the actual data log storing activities between tasks.
    FrozenTasks,       // Log of all frozen state of the tasks.
    LastEntry,         // This is a special entry that is used to signal the end of the log.
    RuntimeLifecycle,  // Runtime lifecycle events (mission/config/stack context).
}
/// Represent the minimum set of traits to be usable as Metadata in Copper.
pub trait Metadata: Default + Debug + Clone + Encode + Decode<()> + Serialize {}

impl Metadata for () {}

/// Origin metadata captured when a Copper-aware transport receives a remote message.
#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, Serialize, Deserialize)]
#[cfg_attr(feature = "reflect", derive(Reflect))]
pub struct CuMsgOrigin {
    pub subsystem_code: u16,
    pub instance_id: u32,
    pub cl_id: u64,
}

/// Key metadata piece attached to every message in Copper.
pub trait CuMsgMetadataTrait {
    /// The time range used for the processing of this message
    fn process_time(&self) -> PartialCuTimeRange;

    /// Small status text for user UI to get the realtime state of task (max 24 chrs)
    fn status_txt(&self) -> &CuCompactString;

    /// Remote Copper provenance captured on receive.
    fn origin(&self) -> Option<&CuMsgOrigin> {
        None
    }
}

/// A generic trait to expose the generated CuStampedDataSet from the task graph.
pub trait ErasedCuStampedData {
    fn payload(&self) -> Option<&dyn erased_serde::Serialize>;
    #[cfg(feature = "reflect")]
    fn payload_reflect(&self) -> Option<&dyn Reflect>;
    fn tov(&self) -> Tov;
    fn metadata(&self) -> &dyn CuMsgMetadataTrait;
}

/// Trait to get a vector of type-erased CuStampedDataSet
/// This is used for generic serialization of the copperlists
pub trait ErasedCuStampedDataSet {
    fn cumsgs(&self) -> Vec<&dyn ErasedCuStampedData>;
}

/// Provides per-output raw payload sizes aligned with `ErasedCuStampedDataSet::cumsgs` order.
pub trait CuPayloadRawBytes {
    /// Returns raw payload sizes (stack + heap) for each output message.
    /// `None` indicates the payload was not produced for that output.
    fn payload_raw_bytes(&self) -> Vec<Option<u64>>;
}

/// Trait to trace back from the CopperList the origin of each message slot.
///
/// The returned slice must be aligned with `ErasedCuStampedDataSet::cumsgs()`:
/// index `i` maps to copperlist slot `i`.
#[derive(Debug, Clone, Copy)]
pub struct TaskOutputSpec {
    pub task_id: &'static str,
    pub msg_type: &'static str,
    pub payload_type_path_fn: fn() -> &'static str,
}

impl TaskOutputSpec {
    #[inline]
    pub fn payload_type_path(&self) -> &'static str {
        (self.payload_type_path_fn)()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum DebugFieldSemantics {
    Time,
    OptionalTime,
    Duration,
    GeodeticPosition,
    Quantity {
        quantity_name: String,
        unit_symbol: String,
    },
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DebugFieldKind {
    Scalar,
    Struct,
    TupleStruct,
    Tuple,
    List,
    Array,
    Map,
    Set,
    Enum,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DebugFieldDescriptor {
    pub display_path: String,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_debug_binding_name"
    )]
    pub binding_name: Option<String>,
    pub field_type: String,
    pub value_type_path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantics: Option<DebugFieldSemantics>,
    pub nullable: bool,
    pub kind: DebugFieldKind,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<DebugFieldDescriptor>,
}

fn deserialize_debug_binding_name<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    struct BindingNameVisitor;

    impl<'de> Visitor<'de> for BindingNameVisitor {
        type Value = Option<String>;

        fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            formatter.write_str("a string, null, or an empty sequence")
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserialize_debug_binding_name(deserializer)
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Some(value.to_owned()))
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Some(value))
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            if seq.next_element::<de::IgnoredAny>()?.is_none() {
                return Ok(None);
            }
            Err(de::Error::invalid_type(
                de::Unexpected::Seq,
                &"an empty sequence",
            ))
        }
    }

    deserializer.deserialize_any(BindingNameVisitor)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DebugScalarRegistration {
    pub type_path: &'static str,
    pub field_type: &'static str,
    pub semantics: DebugFieldSemantics,
}

pub trait DebugScalarType: 'static {
    fn debug_scalar_registration() -> DebugScalarRegistration;
}

pub trait MatchingTasks {
    fn get_all_task_ids() -> &'static [&'static str];

    fn get_output_specs() -> &'static [TaskOutputSpec] {
        &[]
    }
}

/// Trait for providing JSON schemas for CopperList payload types.
///
/// This trait is implemented by the generated CuMsgs type via the `gen_cumsgs!` macro
/// when MCAP export support is enabled. It provides compile-time schema information
/// for each task's payload type, enabling proper schema generation for Foxglove.
///
/// The default implementation returns an empty vector for backwards compatibility
/// with code that doesn't need MCAP export support.
pub trait PayloadSchemas {
    /// Returns a vector of (task_id, schema_json) pairs.
    ///
    /// Each entry corresponds to a CopperList output slot, in slot order.
    /// The schema is a JSON Schema string generated from the payload type.
    fn get_payload_schemas() -> Vec<(&'static str, String)> {
        Vec::new()
    }
}

/// A CopperListTuple needs to be encodable, decodable and fixed size in memory.
pub trait CopperListTuple:
    bincode::Encode
    + bincode::Decode<()>
    + Debug
    + Serialize
    + ErasedCuStampedDataSet
    + MatchingTasks
    + Default
{
} // Decode forces Sized already

// Also anything that follows this contract can be a payload (blanket implementation)
impl<T> CopperListTuple for T where
    T: bincode::Encode
        + bincode::Decode<()>
        + Debug
        + Serialize
        + ErasedCuStampedDataSet
        + MatchingTasks
        + Default
{
}

// We use this type to convey very small status messages.
// MAX_SIZE from their repr module is not accessible so we need to copy paste their definition for 24
// which is the maximum size for inline allocation (no heap)
pub const COMPACT_STRING_CAPACITY: usize = size_of::<String>();

#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CuCompactString(pub CompactString);

impl Encode for CuCompactString {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        let CuCompactString(compact_string) = self;
        let bytes = &compact_string.as_bytes();
        bytes.encode(encoder)
    }
}

impl Debug for CuCompactString {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        if self.0.is_empty() {
            return write!(f, "CuCompactString(Empty)");
        }
        write!(f, "CuCompactString({})", self.0)
    }
}

impl<Context> Decode<Context> for CuCompactString {
    fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
        let bytes = <Vec<u8> as Decode<D::Context>>::decode(decoder)?; // Decode into a byte buffer
        let compact_string =
            CompactString::from_utf8(bytes).map_err(|e| DecodeError::Utf8 { inner: e })?;
        Ok(CuCompactString(compact_string))
    }
}

impl<'de, Context> BorrowDecode<'de, Context> for CuCompactString {
    fn borrow_decode<D: BorrowDecoder<'de>>(decoder: &mut D) -> Result<Self, DecodeError> {
        CuCompactString::decode(decoder)
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for CuError {
    fn format(&self, f: defmt::Formatter) {
        match &self.cause {
            Some(c) => {
                let cause_str = c.to_string();
                defmt::write!(
                    f,
                    "CuError {{ message: {}, cause: {} }}",
                    defmt::Display2Format(&self.message),
                    defmt::Display2Format(&cause_str),
                )
            }
            None => defmt::write!(
                f,
                "CuError {{ message: {}, cause: None }}",
                defmt::Display2Format(&self.message),
            ),
        }
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for CuCompactString {
    fn format(&self, f: defmt::Formatter) {
        if self.0.is_empty() {
            defmt::write!(f, "CuCompactString(Empty)");
        } else {
            defmt::write!(f, "CuCompactString({})", defmt::Display2Format(&self.0));
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::CuCompactString;
    use bincode::{config, decode_from_slice, encode_to_vec};
    use compact_str::CompactString;

    #[test]
    fn test_cucompactstr_encode_decode_empty() {
        let cstr = CuCompactString(CompactString::from(""));
        let config = config::standard();
        let encoded = encode_to_vec(&cstr, config).expect("Encoding failed");
        assert_eq!(encoded.len(), 1); // This encodes the usize 0 in variable encoding so 1 byte which is 0.
        let (decoded, _): (CuCompactString, usize) =
            decode_from_slice(&encoded, config).expect("Decoding failed");
        assert_eq!(cstr.0, decoded.0);
    }

    #[test]
    fn test_cucompactstr_encode_decode_small() {
        let cstr = CuCompactString(CompactString::from("test"));
        let config = config::standard();
        let encoded = encode_to_vec(&cstr, config).expect("Encoding failed");
        assert_eq!(encoded.len(), 5); // This encodes a 4-byte string "test" plus 1 byte for the length prefix.
        let (decoded, _): (CuCompactString, usize) =
            decode_from_slice(&encoded, config).expect("Decoding failed");
        assert_eq!(cstr.0, decoded.0);
    }
}

// Tests that require std feature
#[cfg(all(test, feature = "std"))]
mod std_tests {
    use crate::{CuError, DebugFieldDescriptor, DebugFieldKind, DebugFieldSemantics, with_cause};
    use serde_json::json;

    #[test]
    fn test_cuerror_from_str() {
        let err = CuError::from("test error");
        assert_eq!(err.message(), "test error");
        assert!(err.cause().is_none());
    }

    #[test]
    fn test_cuerror_from_string() {
        let err = CuError::from(String::from("test error"));
        assert_eq!(err.message(), "test error");
        assert!(err.cause().is_none());
    }

    #[test]
    fn test_cuerror_new_index() {
        let err = CuError::new(42);
        assert_eq!(err.message(), "[interned:42]");
        assert!(err.cause().is_none());
    }

    #[test]
    fn test_cuerror_new_with_cause() {
        let io_err = std::io::Error::other("io error");
        let err = CuError::new_with_cause("wrapped error", io_err);
        assert_eq!(err.message(), "wrapped error");
        assert!(err.cause().is_some());
        assert!(err.cause().unwrap().to_string().contains("io error"));
    }

    #[test]
    fn test_cuerror_add_cause() {
        let err = CuError::from("base error").add_cause("additional context");
        assert_eq!(err.message(), "base error");
        assert!(err.cause().is_some());
        assert_eq!(err.cause().unwrap().to_string(), "additional context");
    }

    #[test]
    fn test_cuerror_with_cause_method() {
        let io_err = std::io::Error::other("io error");
        let err = CuError::from("base error").with_cause(io_err);
        assert_eq!(err.message(), "base error");
        assert!(err.cause().is_some());
    }

    #[test]
    fn test_cuerror_with_cause_free_function() {
        let io_err = std::io::Error::other("io error");
        let err = with_cause("wrapped", io_err);
        assert_eq!(err.message(), "wrapped");
        assert!(err.cause().is_some());
    }

    #[test]
    fn test_cuerror_clone() {
        let io_err = std::io::Error::other("io error");
        let err = CuError::new_with_cause("test", io_err);
        let cloned = err.clone();
        assert_eq!(err.message(), cloned.message());
        // Cause string representation should match
        assert_eq!(
            err.cause().map(|c| c.to_string()),
            cloned.cause().map(|c| c.to_string())
        );
    }

    #[test]
    fn test_cuerror_serialize_deserialize_json() {
        let io_err = std::io::Error::other("io error");
        let err = CuError::new_with_cause("test", io_err);

        let serialized = serde_json::to_string(&err).unwrap();
        let deserialized: CuError = serde_json::from_str(&serialized).unwrap();

        assert_eq!(err.message(), deserialized.message());
        // Cause should be preserved as string
        assert!(deserialized.cause().is_some());
    }

    #[test]
    fn test_cuerror_serialize_deserialize_no_cause() {
        let err = CuError::from("simple error");

        let serialized = serde_json::to_string(&err).unwrap();
        let deserialized: CuError = serde_json::from_str(&serialized).unwrap();

        assert_eq!(err.message(), deserialized.message());
        assert!(deserialized.cause().is_none());
    }

    #[test]
    fn test_cuerror_display() {
        let err = CuError::from("test error").add_cause("some context");
        let display = format!("{}", err);
        assert!(display.contains("test error"));
        assert!(display.contains("some context"));
    }

    #[test]
    fn test_cuerror_debug() {
        let err = CuError::from("test error").add_cause("some context");
        let debug = format!("{:?}", err);
        assert!(debug.contains("test error"));
        assert!(debug.contains("some context"));
    }

    #[test]
    fn debug_field_descriptor_skips_missing_binding_name_on_serialize() {
        let descriptor = DebugFieldDescriptor {
            display_path: "meta.process_time.start_ns".to_owned(),
            binding_name: None,
            field_type: "integer".to_owned(),
            value_type_path: "cu29_clock::CuTime".to_owned(),
            semantics: Some(DebugFieldSemantics::Time),
            nullable: true,
            kind: DebugFieldKind::Scalar,
            children: Vec::new(),
        };

        let encoded = serde_json::to_value(&descriptor).unwrap();
        assert!(encoded.get("binding_name").is_none());
    }

    #[test]
    fn debug_field_descriptor_accepts_empty_array_binding_name() {
        let encoded = json!({
            "display_path": "meta.process_time.start_ns",
            "binding_name": [],
            "field_type": "integer",
            "value_type_path": "cu29_clock::CuTime",
            "semantics": "Time",
            "nullable": true,
            "kind": "scalar",
        });

        let descriptor: DebugFieldDescriptor = serde_json::from_value(encoded).unwrap();
        assert_eq!(descriptor.binding_name, None);
        assert_eq!(descriptor.semantics, Some(DebugFieldSemantics::Time));
        assert_eq!(descriptor.kind, DebugFieldKind::Scalar);
        assert!(descriptor.children.is_empty());
    }
}