SEDSnet 4.0.0

A memory safe, no_std-capable networking stack with routing, discovery, reliability, and Rust/C/Python bindings.
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
// std on host/tests; no_std when the `std` feature is OFF

// Dear programmer:
// When I wrote this code, only god and I knew how it worked.
// Now, only god knows it!
// Therefore, if you are trying to optimize
// this routine, and it fails (it most surely will),
// please increase this counter as a warning for the next person:
// total hours wasted on this project = 3154

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(unused_doc_comments)]
//! SEDSnet is a compact networking stack for embedded and host telemetry systems.
//!
//! It provides runtime schema registration, compact packet packing, discovery-driven routing,
//! reliable delivery, managed state synchronization, time synchronization, P2P service ports and
//! streams, optional E2E payload cryptography, and C/Python bindings.
//!
//! Most user-facing APIs live in:
//! - [`config`]: schema + data type/endpoint configuration.
//! - [`router`]: routers, relays, sides, discovery, routing policy, P2P, and managed variables.
//! - [`packet`]: `Packet` and friends.
//! - [`wire_format`]: packet packing, unpacking, and wire inspection helpers.
//!
//! Version 4.0.0 highlights:
//! - Telemetry endpoints and data types are runtime IDs with process-local registry metadata.
//! - The build no longer reads `telemetry_config.json` or generates schema-specific Rust enums.
//! - A JSON schema can still seed the runtime registry with `SEDSNET_STATIC_SCHEMA_PATH`.
//! - Nodes can export known endpoints/types, sync schemas through discovery, and register new
//!   schema entries over time.
//! - Discovery assigns compact node addresses and hostnames for P2P service traffic while
//!   broadcast endpoint telemetry continues to use endpoint subscriptions.

extern crate alloc;
extern crate core;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "std")]
use std::io::Error;

use crate::config::{
    DataEndpoint, DataType, STATIC_HEX_LENGTH, STATIC_STRING_LENGTH, get_endpoint_meta,
    get_message_meta, max_data_type_id, max_endpoint_id,
};
use crate::macros::{ReprI32Enum, ReprU32Enum};
use alloc::string::ToString;
use alloc::sync::Arc;
use core::fmt::Formatter;
use core::mem::size_of;
use core::ops::Mul;

// ============================================================================
//  Test / Python FFI modules (std-only)
// ============================================================================

#[cfg(all(test, feature = "std"))]
mod tests;

#[cfg(feature = "python")]
#[cfg(feature = "std")]
mod python_api;

// ============================================================================
//  Allocator & panic handlers (embedded no_std)
// ============================================================================
//
// For EMBEDDED builds (no_std + bare-metal target), provide Telemetry allocator
// + panic handler. Host builds rely on the system allocator / default panic.

#[cfg(all(not(feature = "std"), target_os = "none"))]
unsafe extern "C" {
    fn seds_error_msg(msg: *const u8, len: usize);
}

#[cfg(all(not(feature = "std"), target_os = "none"))]
mod embedded_alloc {
    use core::alloc::{GlobalAlloc, Layout};
    use core::mem::size_of;

    unsafe extern "C" {
        fn telemetryMalloc(size: usize) -> *mut core::ffi::c_void;
        fn telemetryFree(ptr: *mut core::ffi::c_void);
        fn telemetry_panic_hook(msg: *const u8, len: usize);
    }

    /// Global allocator that forwards to `telemetryMalloc` / `telemetryFree`
    /// provided by the host environment.
    struct TelemetryAlloc;

    #[inline]
    fn align_up(addr: usize, align: usize) -> usize {
        (addr + (align - 1)) & !(align - 1)
    }

    unsafe impl GlobalAlloc for TelemetryAlloc {
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            let align = layout.align().max(size_of::<usize>());
            let header = size_of::<usize>();
            let total = match layout
                .size()
                .checked_add(align)
                .and_then(|v| v.checked_add(header))
            {
                Some(v) => v,
                None => return core::ptr::null_mut(),
            };

            let raw = unsafe { telemetryMalloc(total) as *mut u8 };
            if raw.is_null() {
                return core::ptr::null_mut();
            }

            let base = raw as usize + header;
            let aligned = align_up(base, align) as *mut u8;

            // Store the original pointer just before the aligned pointer.
            unsafe {
                let slot = (aligned as *mut usize).offset(-1);
                *slot = raw as usize;
            }

            aligned
        }

        unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
            if ptr.is_null() {
                return;
            }

            let raw = unsafe {
                let slot = (ptr as *mut usize).offset(-1);
                *slot as *mut core::ffi::c_void
            };
            unsafe { telemetryFree(raw) };
        }
    }

    #[global_allocator]
    static A: TelemetryAlloc = TelemetryAlloc;

    // Panic handler for embedded
    use core::panic::PanicInfo;

    #[panic_handler]
    fn panic(_info: &PanicInfo) -> ! {
        let msg = b"rust panic";
        unsafe {
            telemetry_panic_hook(msg.as_ptr(), msg.len());
        }

        // Halt forever after panic.
        loop {}
    }

    // ensure cortex-m only compiles on embedded
    // use cortex_m as _;
}

// For HOST builds (std is ON), the system allocator is used automatically.
// No custom panic handler needed.

// ============================================================================
//  Portable core logic: modules
// ============================================================================

mod c_api;
pub mod config;
#[cfg(feature = "cryptography")]
pub mod crypto;
pub mod diagnostics;
#[cfg(feature = "discovery")]
pub mod discovery;
mod lock;
mod macros;
pub mod packet;
mod queue;
pub mod relay;
pub mod router;
mod small_payload;
#[cfg(feature = "timesync")]
pub mod timesync;
pub mod wire_format;
// ============================================================================
//  Schema-derived global constants
// ============================================================================

/// Maximum enum value for `DataEndpoint` (inclusive), derived from the schema.
pub const MAX_VALUE_DATA_ENDPOINT: u32 = 255;

/// Maximum enum value for `DataType` (inclusive), derived from the schema.
pub const MAX_VALUE_DATA_TYPE: u32 = 4095;

/// Maximum enum value for `RouteSelectionMode` (inclusive).
pub const MAX_VALUE_ROUTE_SELECTION_MODE: i32 = 2;

impl crate::macros::ReprU32Enum for DataType {
    const MAX: u32 = MAX_VALUE_DATA_TYPE;

    #[inline]
    fn from_u32(x: u32) -> Option<Self> {
        DataType::try_from_u32(x)
    }
}

impl crate::macros::ReprU32Enum for DataEndpoint {
    const MAX: u32 = MAX_VALUE_DATA_ENDPOINT;

    #[inline]
    fn from_u32(x: u32) -> Option<Self> {
        DataEndpoint::try_from_u32(x)
    }
}

#[inline]
pub fn current_max_endpoint_id() -> u32 {
    max_endpoint_id()
}

#[inline]
pub fn current_max_data_type_id() -> u32 {
    max_data_type_id()
}

#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum RouteSelectionMode {
    Fanout = 0,
    Weighted = 1,
    Failover = 2,
}

impl_repr_i32_enum!(
    RouteSelectionMode,
    RouteSelectionMode::Fanout as i32,
    RouteSelectionMode::Failover as i32
);

#[inline]
const fn parse_usize(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut val = 0;

    while i < bytes.len() {
        let c = bytes[i];
        if c < b'0' || c > b'9' {
            panic!("Invalid digit");
        }
        val = val * 10 + (c - b'0') as usize;
        i += 1;
    }
    val
}

#[inline]
pub const fn parse_f64(s: &str) -> f64 {
    let bytes = s.as_bytes();
    let mut i = 0;

    if bytes.is_empty() {
        panic!("empty string");
    }

    // sign
    let mut sign = 1.0;
    if bytes[i] == b'-' {
        sign = -1.0;
        i += 1;
    } else if bytes[i] == b'+' {
        i += 1;
    }

    let mut int_part: f64 = 0.0;
    let mut has_digits = false;

    while i < bytes.len() && bytes[i] >= b'0' && bytes[i] <= b'9' {
        int_part = int_part * 10.0 + (bytes[i] - b'0') as f64;
        i += 1;
        has_digits = true;
    }

    let mut frac_part: f64 = 0.0;
    let mut scale: f64 = 1.0;

    if i < bytes.len() && bytes[i] == b'.' {
        i += 1;

        while i < bytes.len() && bytes[i] >= b'0' && bytes[i] <= b'9' {
            scale *= 10.0;
            frac_part += (bytes[i] - b'0') as f64 / scale;
            i += 1;
            has_digits = true;
        }
    }

    if !has_digits || i != bytes.len() {
        panic!("invalid f64 literal");
    }

    sign * (int_part + frac_part)
}

#[inline(always)]
const fn parse_strings(s: &str) -> &str {
    s
}

#[inline]
pub const fn parse_u8(s: &str) -> u8 {
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut val: u16 = 0;

    if bytes.is_empty() {
        panic!("empty string");
    }

    while i < bytes.len() {
        let c = bytes[i];
        if c < b'0' || c > b'9' {
            panic!("invalid digit in u8");
        }

        val = val * 10 + (c - b'0') as u16;
        if val > 255 {
            panic!("u8 overflow");
        }

        i += 1;
    }

    val as u8
}

#[inline]
pub const fn parse_u128(s: &str) -> u128 {
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut val: u128 = 0;

    if bytes.is_empty() {
        panic!("empty string");
    }

    while i < bytes.len() {
        let c = bytes[i];
        if c < b'0' || c > b'9' {
            panic!("invalid digit in u128");
        }

        let digit = (c - b'0') as u128;

        // Overflow check: val*10 + digit <= u128::MAX
        // i.e. val <= (u128::MAX - digit) / 10
        if val > (u128::MAX - digit) / 10 {
            panic!("u128 overflow");
        }

        val = val * 10 + digit;
        i += 1;
    }

    val
}

// ============================================================================
//  Message metadata (element counts, data types, sizes)
// ============================================================================
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct EndpointMeta {
    /// Static name of the endpoint
    name: &'static str,
    /// Human-readable description used by schema lookup APIs.
    description: &'static str,
    /// Restrict remote forwarding to link-local/software-bus sides only.
    link_local_only: bool,
}

impl EndpointMeta {
    /// Return a stable string representation used in logs and in
    /// `Packet::to_string()` output.
    ///
    /// This should remain stable over time for compatibility with tests and
    /// external tooling.
    pub fn as_str(&self) -> &'static str {
        self.name
    }

    /// Return the human-readable endpoint description.
    #[inline]
    pub fn description(&self) -> &'static str {
        self.description
    }

    /// Return whether this endpoint is restricted to link-local/software-bus sides.
    #[inline]
    pub fn is_link_local_only(&self) -> bool {
        self.link_local_only
    }
}

impl DataEndpoint {
    /// Return a stable string representation used in logs and in
    /// `Packet::to_string()` output.
    ///
    /// This should remain stable over time for compatibility with tests and
    /// external tooling.
    pub fn as_str(&self) -> &'static str {
        get_endpoint_meta(*self).name
    }

    /// Return the human-readable endpoint description.
    pub fn description(&self) -> &'static str {
        get_endpoint_meta(*self).description
    }

    /// Return whether this endpoint is restricted to link-local/software-bus sides.
    #[inline]
    pub fn is_link_local_only(&self) -> bool {
        get_endpoint_meta(*self).link_local_only
    }
}

/// Describes how many elements are present for a given message type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum MessageElement {
    /// Fixed number of elements.
    ///
    /// (count, MessageDataType, MessageClass)
    Static(usize, MessageDataType, MessageClass),
    /// Variable number of elements (payload size can vary).
    ///
    /// (MessageDataType, MessageClass)
    Dynamic(MessageDataType, MessageClass),
}

impl MessageElement {
    /// Get the `MessageDataType` for this element count.
    #[inline]
    pub const fn data_type(&self) -> MessageDataType {
        match self {
            MessageElement::Static(_, dt, _) => *dt,
            MessageElement::Dynamic(dt, _) => *dt,
        }
    }

    /// Get the `MessageType` for this element count.
    #[inline]
    pub const fn message_type(&self) -> MessageClass {
        match self {
            MessageElement::Static(_, _, mt) => *mt,
            MessageElement::Dynamic(_, mt) => *mt,
        }
    }
}

/// Reliable delivery mode for a data type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum ReliableMode {
    /// No reliable delivery/acknowledgement on the wire.
    None,
    /// Reliable delivery with strict ordering.
    Ordered,
    /// Reliable delivery without ordering guarantees.
    Unordered,
}

/// End-to-end cryptography preference for a data type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum E2eEncryptionPolicy {
    /// Send unencrypted unless a router-level policy forces cryptography.
    PreferOff,
    /// Encrypt when the local router supports E2E cryptography, but allow plaintext fallback.
    PreferOn,
    /// Require E2E cryptography support before sending or locally consuming this type.
    RequireOn,
}

/// Static metadata for a message type: element count and valid endpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct MessageMeta {
    name: &'static str,
    /// Human-readable description used by schema lookup APIs.
    description: &'static str,
    /// How many elements are present (fixed vs dynamic).
    element: MessageElement,
    /// Allowed endpoints for this message type.
    endpoints: &'static [DataEndpoint],
    /// Reliable delivery mode for this type.
    reliable: ReliableMode,
    /// Queue priority for this type. Higher values are serviced first.
    priority: u8,
    /// End-to-end cryptography policy for this type.
    e2e_encryption: E2eEncryptionPolicy,
}

impl DataType {
    /// Get the string representation of the DataType
    pub fn as_str(&self) -> &'static str {
        get_message_meta(*self).name
    }

    /// Return the human-readable data type description.
    pub fn description(&self) -> &'static str {
        get_message_meta(*self).description
    }
}
/// Lookup `MessageMeta` for a given [`DataType`] using the generated config.
/// # Arguments
/// - `ty`: Logical data type to query.
/// # Returns
/// - `MessageMeta` struct with element count and allowed endpoints.
#[inline]
pub fn message_meta(ty: DataType) -> MessageMeta {
    get_message_meta(ty)
}

/// Return whether the given [`DataType`] is configured for reliable delivery.
#[inline]
pub fn is_reliable_type(ty: DataType) -> bool {
    !matches!(get_message_meta(ty).reliable, ReliableMode::None)
}

/// Return the reliable delivery mode for the given [`DataType`].
#[inline]
pub fn reliable_mode(ty: DataType) -> ReliableMode {
    get_message_meta(ty).reliable
}

/// Return the queue priority for the given [`DataType`].
#[inline]
pub fn message_priority(ty: DataType) -> u8 {
    get_message_meta(ty).priority
}

/// Return the end-to-end cryptography policy for a data type.
#[inline]
pub fn message_e2e_encryption_policy(ty: DataType) -> E2eEncryptionPolicy {
    get_message_meta(ty).e2e_encryption
}

// ---- Convenience multiplication helpers ----

impl Mul<MessageElement> for usize {
    type Output = usize;

    #[inline]
    fn mul(self, rhs: MessageElement) -> usize {
        self * rhs.into()
    }
}

impl Mul<usize> for MessageElement {
    type Output = usize;

    #[inline]
    fn mul(self, rhs: usize) -> usize {
        self.into() * rhs
    }
}

impl MessageElement {
    /// Convert the element count to a `usize`.
    ///
    /// - `Static(n)` → `n`
    /// - `Dynamic`   → `0` (caller must handle dynamic sizing separately)
    #[inline]
    fn into(self) -> usize {
        match self {
            MessageElement::Static(a, _, _) => a,
            _ => 0,
        }
    }
}

/// Return the total payload size (in bytes) required for a given `DataType`
/// under the *static* schema.
///
/// This is `element_size * element_count`. For dynamic types, the
/// configuration ensures we only call this where it makes sense.
/// # Arguments
/// - `ty`: Logical data type to query.
/// # Returns
/// - Total static payload size in bytes.
#[inline]
pub fn get_needed_message_size(ty: DataType) -> usize {
    data_type_size(get_data_type(ty)) * get_message_meta(ty).element
}

/// Return the logical "info" type (Info/Error) for a given `DataType`.
/// # Arguments
/// - `ty`: Logical data type to query.
/// # Returns
/// - `MessageType` enum value.
#[inline]
pub fn get_info_type(ty: DataType) -> MessageClass {
    get_message_meta(ty).element.message_type()
}

/// Return the *element* data type (e.g., `Float32`, `Int16`, `String`) for a
/// given `DataType`.
/// # Arguments
/// - `ty`: Logical data type to query.
/// # Returns
/// - `MessageDataType` enum value.
#[inline]
pub fn get_data_type(ty: DataType) -> MessageDataType {
    get_message_meta(ty).element.data_type()
}

/// Return the message name for a given `DataType`.
/// # Arguments
/// - `ty`: Logical data type to query.
/// # Returns
/// - Static string name of the message type.
#[inline]
pub fn get_message_name(ty: DataType) -> &'static str {
    get_message_meta(ty).name
}

/// Return the default endpoints for a given `DataType`.
/// # Arguments
/// - `ty`: Logical data type to query.
/// # Returns
/// - Slice of allowed `DataEndpoint` values.
#[inline]
pub fn endpoints_from_datatype(ty: DataType) -> &'static [DataEndpoint] {
    get_message_meta(ty).endpoints
}

/// Primitive element type used by a message.
///
/// This is the underlying "slot" type, not the high-level `DataType`
/// (which is the logical schema type).
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum MessageDataType {
    Float64,
    Float32,
    UInt8,
    UInt16,
    UInt32,
    UInt64,
    UInt128,
    Int8,
    Int16,
    Int32,
    Int64,
    Int128,
    Bool,
    String,
    Binary,
    NoData,
}

/// Size in bytes of a single element for the given [`MessageDataType`].
///
/// For `String` / `Hex`, this returns the fixed maximum static length
/// configured by the schema (`MAX_STATIC_STRING_LENGTH`, `MAX_STATIC_HEX_LENGTH`).
/// # Arguments
/// - `dt`: Logical data type to query.
/// # Returns
/// - Size in bytes of a single element of that type.
#[inline]
pub const fn data_type_size(dt: MessageDataType) -> usize {
    match dt {
        MessageDataType::Float64 => size_of::<f64>(),
        MessageDataType::Float32 => size_of::<f32>(),
        MessageDataType::UInt8 => size_of::<u8>(),
        MessageDataType::UInt16 => size_of::<u16>(),
        MessageDataType::UInt32 => size_of::<u32>(),
        MessageDataType::UInt64 => size_of::<u64>(),
        MessageDataType::UInt128 => size_of::<u128>(),
        MessageDataType::Int8 => size_of::<i8>(),
        MessageDataType::Int16 => size_of::<i16>(),
        MessageDataType::Int32 => size_of::<i32>(),
        MessageDataType::Int64 => size_of::<i64>(),
        MessageDataType::Int128 => size_of::<i128>(),
        MessageDataType::Bool => size_of::<bool>(),
        MessageDataType::String => STATIC_STRING_LENGTH,
        MessageDataType::Binary => STATIC_HEX_LENGTH,
        MessageDataType::NoData => 0,
    }
}

/// High-level classification of message kind.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum MessageClass {
    /// Informational telemetry.
    Data,
    /// Error / fault telemetry.
    Error,
    /// Warning telemetry.
    Warning,
}

// ============================================================================
//  Error types and error codes
// ============================================================================

/// Rich error type used throughout the telemetry crate.
///
/// Most public APIs expose a `TelemetryResult<T>` alias for
/// `Result<T, TelemetryError>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TelemetryError {
    /// Generic / unspecified error.
    GenericError(Option<Arc<str>>),

    /// Logical type ID is not a valid [`DataType`].
    InvalidType,

    /// Payload size doesn't match the schema's expectations.
    SizeMismatch { expected: usize, got: usize },

    /// Legacy / generic size mismatch error (for C/Python parity).
    SizeMismatchError,

    /// No endpoints were supplied where they are required.
    EmptyEndpoints,

    /// Timestamp is invalid (e.g., zero when disallowed).
    TimestampInvalid,

    /// A packet is missing its payload bytes.
    MissingPayload,

    /// A handler (C/Python callback) returned an error.
    HandlerError(&'static str),

    /// Generic invalid argument from caller.
    BadArg,

    /// Operation is not permitted for the current router/device policy.
    PermissionDenied,

    /// Packing error.
    Pack(&'static str),

    /// Unpacking error.
    Unpack(&'static str),

    /// IO / transport error.
    Io(&'static str),

    /// UTF-8 decoding failed where string payloads are expected.
    InvalidUtf8,

    /// Payload type size mismatch.
    TypeMismatch { expected: usize, got: usize },

    /// Invalid link ID provided.
    InvalidLinkId(&'static str),

    /// Packet is bigger than the queue size
    PacketTooLarge(&'static str),
}

impl TelemetryError {
    /// Map a rich [`TelemetryError`] to a stable numeric error code
    /// used by the FFI layers.
    pub const fn to_error_code(&self) -> TelemetryErrorCode {
        match self {
            TelemetryError::GenericError(_) => TelemetryErrorCode::GenericError,
            TelemetryError::InvalidType => TelemetryErrorCode::InvalidType,
            TelemetryError::SizeMismatch { .. } => TelemetryErrorCode::SizeMismatch,
            TelemetryError::SizeMismatchError => TelemetryErrorCode::SizeMismatchError,
            TelemetryError::EmptyEndpoints => TelemetryErrorCode::EmptyEndpoints,
            TelemetryError::TimestampInvalid => TelemetryErrorCode::TimestampInvalid,
            TelemetryError::MissingPayload => TelemetryErrorCode::MissingPayload,
            TelemetryError::HandlerError(_) => TelemetryErrorCode::HandlerError,
            TelemetryError::BadArg => TelemetryErrorCode::BadArg,
            TelemetryError::PermissionDenied => TelemetryErrorCode::PermissionDenied,
            TelemetryError::Pack(_) => TelemetryErrorCode::Pack,
            TelemetryError::Unpack(_) => TelemetryErrorCode::Unpack,
            TelemetryError::Io(_) => TelemetryErrorCode::Io,
            TelemetryError::InvalidUtf8 => TelemetryErrorCode::InvalidUtf8,
            TelemetryError::TypeMismatch { .. } => TelemetryErrorCode::TypeMismatch,
            TelemetryError::InvalidLinkId(_) => TelemetryErrorCode::InvalidLinkId,
            TelemetryError::PacketTooLarge(_) => TelemetryErrorCode::PacketTooLarge,
        }
    }
}

/// Allow conversion of `TelemetryError` to human-readable string.
impl core::fmt::Display for TelemetryError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.write_str(&TelemetryError::to_string(self))
    }
}

/// Implement `std::error::Error` for `TelemetryError` when `std` is enabled.
#[cfg(feature = "std")]
impl std::error::Error for TelemetryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

/// Allow the conversion from std error to telemetry error
#[cfg(feature = "std")]
impl From<Error> for TelemetryError {
    fn from(error: Error) -> Self {
        let str = error.to_string();
        let astr: Arc<str> = Arc::from(str.as_str());
        TelemetryError::GenericError(Some(astr))
    }
}

/// Allow the conversion from boxed std error to telemetry error
#[cfg(feature = "std")]
impl From<Box<dyn std::error::Error>> for TelemetryError {
    fn from(err: Box<dyn std::error::Error>) -> Self {
        let str = err.to_string();
        let astr: Arc<str> = Arc::from(str.as_str());
        TelemetryError::GenericError(Some(astr))
    }
}

/// Numeric error codes used on the C/Python FFI boundary.
///
/// Negative values are used to avoid collisions with success codes
/// and other positive return values (e.g. lengths).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum TelemetryErrorCode {
    GenericError = -2,
    InvalidType = -3,
    SizeMismatch = -4,
    SizeMismatchError = -5,
    EmptyEndpoints = -6,
    TimestampInvalid = -7,
    MissingPayload = -8,
    HandlerError = -9,
    BadArg = -10,
    PermissionDenied = -11,
    Pack = -12,
    Unpack = -13,
    Io = -14,
    InvalidUtf8 = -15,
    TypeMismatch = -16,
    InvalidLinkId = -17,
    PacketTooLarge = -18,
}

// Generate ReprI32Enum helpers for TelemetryErrorCode
impl_repr_i32_enum!(
    TelemetryErrorCode,
    TelemetryErrorCode::MAX,
    TelemetryErrorCode::MIN
);

impl TelemetryErrorCode {
    /// Maximum valid numeric error code value.
    pub const MAX: i32 = TelemetryErrorCode::InvalidType as i32;

    /// Minimum valid numeric error code value.
    pub const MIN: i32 = TelemetryErrorCode::PacketTooLarge as i32;

    /// Human-readable string for logging / debugging.
    /// # Returns
    /// - Static string representation of the error code.
    #[inline]
    pub fn as_str(&self) -> &'static str {
        match self {
            TelemetryErrorCode::GenericError => "GenericError",
            TelemetryErrorCode::InvalidType => "{Invalid Type}",
            TelemetryErrorCode::SizeMismatch => "{Size Mismatch}",
            TelemetryErrorCode::SizeMismatchError => "{Size Mismatch Error}",
            TelemetryErrorCode::EmptyEndpoints => "{Empty Endpoints}",
            TelemetryErrorCode::TimestampInvalid => "{Timestamp Invalid}",
            TelemetryErrorCode::MissingPayload => "{Missing Payload}",
            TelemetryErrorCode::HandlerError => "{Handler Error}",
            TelemetryErrorCode::BadArg => "{Bad Arg}",
            TelemetryErrorCode::PermissionDenied => "{Permission Denied}",
            TelemetryErrorCode::Pack => "{Pack Error}",
            TelemetryErrorCode::Unpack => "{Unpack Error}",
            TelemetryErrorCode::Io => "{IO Error}",
            TelemetryErrorCode::InvalidUtf8 => "{Invalid UTF-8}",
            TelemetryErrorCode::TypeMismatch => "{Type Mismatch}",
            TelemetryErrorCode::InvalidLinkId => "{Invalid Link ID}",
            TelemetryErrorCode::PacketTooLarge => "{Packet Too Large}",
        }
    }

    /// Try to convert a raw i32 error code into a [`TelemetryErrorCode`].
    ///
    /// Returns `None` if the code is out of range or not recognized.
    /// # Arguments
    /// - `x`: Raw i32 error code to convert.
    /// # Returns
    /// - `Some(TelemetryErrorCode)` if valid, `None` if invalid.
    #[inline]
    pub fn try_from_i32(x: i32) -> Option<Self> {
        try_enum_from_i32(x)
    }
}

/// Common result alias for telemetry operations.
pub type TelemetryResult<T> = Result<T, TelemetryError>;

// ============================================================================
//  Generic enum helpers (repr(u32) / repr(i32))
// ============================================================================

/// Try to convert a `u32` into a `#[repr(u32)]` enum `E`.
///
/// Returns `None` if the value is out of range (greater than `E::MAX`).
/// # Arguments
/// - `x`: Raw u32 value to convert.
/// # Returns
/// - `Some(E)` if valid, `None` if invalid.
#[inline]
pub fn try_enum_from_u32<E: ReprU32Enum>(x: u32) -> Option<E> {
    if x > E::MAX {
        return None;
    }
    E::from_u32(x)
}

/// Try to convert an `i32` into a `#[repr(i32)]` enum `E`.
///
/// Returns `None` if the value is outside the `[E::MIN, E::MAX]` range.
/// # Arguments
/// - `x`: Raw i32 value to convert.
/// # Returns
/// - `Some(E)` if valid, `None` if invalid.
#[inline]
pub fn try_enum_from_i32<E: ReprI32Enum>(x: i32) -> Option<E> {
    if x < E::MIN || x > E::MAX {
        return None;
    }

    // SAFETY: `E` is promised to be a fieldless #[repr(i32)] enum (thus 4 bytes, Copy).
    let e = unsafe { (&x as *const i32 as *const E).read() };
    Some(e)
}