thincan 0.1.1

Thin, composable application-layer message routing for UDS-style ISO-TP transports
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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
//! thincan: capnp-only message transport helpers over ISO-TP payloads.
//!
//! `thincan` sits above ISO-TP and defines a tiny wire header:
//! - `u16` message id (little-endian)
//! - message body bytes (Cap'n Proto single segment)
//!
//! The crate provides:
//! - `bus_atlas!` for message marker declarations
//! - `maplet!` for composing a compile-time message set
//! - `bundle_instance!` for generating bundle instance structs and `BundleFactory` impls
//! - maplet-typed `Interface` for async send, ingest, and mailboxed typed receive
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(async_fn_in_trait)]

use core::marker::PhantomData;
use core::time::Duration;

pub use embassy_sync::blocking_mutex::raw::{NoopRawMutex, RawMutex};

/// Simple message metadata (id + body length).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MessageSpec {
    /// 16-bit message id.
    pub id: u16,
    /// Message body size in bytes.
    pub body_size: usize,
}

/// Marker trait for message types declared in a bus atlas.
pub trait Message {
    /// 16-bit message id written to the wire (little endian).
    const ID: u16;
}

/// Marker trait for messages whose body is a Cap'n Proto single segment.
pub trait CapnpMessage: Message {
    /// The Cap'n Proto owned type used for typed decoding.
    type Owned;
}

/// Error classification returned by `thincan` operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
    /// Transport timed out waiting for a payload.
    Timeout,
    /// A caller-provided buffer was too small for the operation.
    BufferTooSmall {
        /// Needed length in bytes.
        needed: usize,
        /// Available length in bytes.
        got: usize,
    },
    /// Catch-all for other errors (parsing, protocol, or transport).
    Other,
}

/// Error type returned by most `thincan` operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Error {
    /// Structured error classification.
    pub kind: ErrorKind,
}

impl Error {
    /// Convenience constructor for a timeout error.
    pub const fn timeout() -> Self {
        Self {
            kind: ErrorKind::Timeout,
        }
    }
}

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

#[cfg(feature = "std")]
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.kind)
    }
}

/// A raw message as received on the wire (already framed/deframed at the ISO-TP layer).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawMessage<'a> {
    /// Message id.
    pub id: u16,
    /// Raw body bytes (without the 2-byte id header).
    pub body: &'a [u8],
}

/// A convenient wrapper for Cap'n Proto decode helpers that borrow a buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capnp<'a> {
    /// Raw message bytes.
    pub bytes: &'a [u8],
}

/// A schema-typed Cap'n Proto decode helper that borrows a buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapnpTyped<'a, Schema>(
    /// Raw bytes wrapped as a Cap'n Proto helper.
    pub Capnp<'a>,
    PhantomData<Schema>,
);

impl<'a, Schema> CapnpTyped<'a, Schema> {
    /// Wrap raw bytes in a schema-typed Cap'n Proto reader.
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self(Capnp::new(bytes), PhantomData)
    }

    #[cfg(feature = "capnp")]
    /// Read the typed root with the provided reader options.
    pub fn with_root<R>(
        &self,
        options: capnp::message::ReaderOptions,
        f: impl FnOnce(<Schema as capnp::traits::Owned>::Reader<'_>) -> R,
    ) -> Result<R, capnp::Error>
    where
        Schema: capnp::traits::Owned,
    {
        self.0.with_root::<Schema, R>(options, f)
    }
}

impl<'a> Capnp<'a> {
    /// Wrap raw bytes in a Cap'n Proto reader helper.
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }

    #[cfg(feature = "capnp")]
    /// Construct a `capnp::message::Reader` over a single segment.
    pub fn with_reader<R>(
        &self,
        options: capnp::message::ReaderOptions,
        f: impl FnOnce(capnp::message::Reader<&[&[u8]]>) -> R,
    ) -> R {
        let segments: [&[u8]; 1] = [self.bytes];
        let reader = capnp::message::Reader::new(&segments[..], options);
        f(reader)
    }

    #[cfg(feature = "capnp")]
    /// Read the typed root with the provided reader options.
    pub fn with_root<O, R>(
        &self,
        options: capnp::message::ReaderOptions,
        f: impl FnOnce(<O as capnp::traits::Owned>::Reader<'_>) -> R,
    ) -> Result<R, capnp::Error>
    where
        O: capnp::traits::Owned,
    {
        self.with_reader(options, |reader| {
            let typed = capnp::message::TypedReader::<_, O>::new(reader);
            let root = typed.get()?;
            Ok(f(root))
        })
    }
}

/// Number of bytes used for the message id header.
pub const HEADER_LEN: usize = 2;

/// Decode a raw ISO-TP payload into a [`RawMessage`].
///
/// Expects the payload to start with a 2-byte little-endian message id.
pub fn decode_wire(payload: &[u8]) -> Result<RawMessage<'_>, Error> {
    if payload.len() < HEADER_LEN {
        return Err(Error {
            kind: ErrorKind::Other,
        });
    }
    let id = u16::from_le_bytes([payload[0], payload[1]]);
    Ok(RawMessage {
        id,
        body: &payload[HEADER_LEN..],
    })
}

/// A trait for values that can encode a Cap'n Proto body for transmission.
pub trait EncodeCapnp<M: CapnpMessage> {
    /// Upper bound on bytes `encode()` may write.
    fn max_encoded_len(&self) -> usize;

    /// Encodes into `out` and returns written body length (excluding header).
    fn encode(&self, out: &mut [u8]) -> Result<usize, Error>;
}

/// Receive metadata provided by transports that can identify the sender.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecvMeta<A> {
    /// Address to use when replying to this payload.
    pub reply_to: A,
}

fn map_isotp_send_error<E>(err: can_isotp_interface::SendError<E>) -> Error {
    Error {
        kind: match err {
            can_isotp_interface::SendError::Timeout => ErrorKind::Timeout,
            can_isotp_interface::SendError::Backend(_) => ErrorKind::Other,
        },
    }
}

/// Optional extension trait: configure ISO-TP receive-side FlowControl (BS/STmin).
pub trait RxFlowControlConfig {
    fn set_rx_flow_control(&mut self, fc: can_isotp_interface::RxFlowControl) -> Result<(), Error>;
}

impl<T> RxFlowControlConfig for T
where
    T: can_isotp_interface::IsoTpRxFlowControlConfig,
{
    fn set_rx_flow_control(&mut self, fc: can_isotp_interface::RxFlowControl) -> Result<(), Error> {
        can_isotp_interface::IsoTpRxFlowControlConfig::set_rx_flow_control(self, fc).map_err(|_| {
            Error {
                kind: ErrorKind::Other,
            }
        })
    }
}

/// Marker for a compile-time message set.
pub trait MapletSpec<const MAX_TYPES: usize> {
    /// Ordered list of message IDs in this maplet.
    const MESSAGE_IDS: [u16; MAX_TYPES];

    /// Resolve message id -> mailbox slot index.
    fn slot_for_id(id: u16) -> Option<usize> {
        let mut i = 0usize;
        while i < MAX_TYPES {
            if Self::MESSAGE_IDS[i] == id {
                return Some(i);
            }
            i += 1;
        }
        None
    }
}

/// Marker for a bundle's declared message set.
pub trait BundleSpec<const N: usize> {
    /// Ordered list of message IDs in this bundle.
    const MESSAGE_IDS: [u16; N];
}

/// Marker: maplet contains bundle `B`.
pub trait MapletHasBundle<B> {}

/// Factory hook used by `maplet!` to build singleton bundle instances.
pub trait BundleFactory<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
>: Sized where
    Maplet: MapletSpec<MAX_TYPES> + MapletHasBundle<Self>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    /// Concrete bundle instance type stored by the generated maplet bundle container.
    type Instance;

    /// Create a bundle instance from a scoped bus handle.
    fn make(
        bus: BusHandle<
            'a,
            Maplet,
            RM,
            Node,
            TxBuf,
            MAX_TYPES,
            DEPTH,
            MAX_BODY,
            MAX_WAITERS,
            Self,
        >,
    ) -> Self::Instance;
}

/// Marker for an unscoped handle that is limited to ingest-only operations.
#[derive(Clone, Copy, Debug, Default)]
pub struct Unscoped;

#[derive(Debug)]
struct TxState<Node, TxBuf> {
    node: Node,
    tx: TxBuf,
}

impl<Node, TxBuf> TxState<Node, TxBuf>
where
    TxBuf: AsMut<[u8]>,
{
    fn encode_capnp_into_buf<'b, M: CapnpMessage, V: EncodeCapnp<M>>(
        buf: &'b mut [u8],
        value: &V,
    ) -> Result<&'b [u8], Error> {
        let max_len = value.max_encoded_len();
        let needed = HEADER_LEN + max_len;
        if buf.len() < needed {
            return Err(Error {
                kind: ErrorKind::BufferTooSmall {
                    needed,
                    got: buf.len(),
                },
            });
        }

        buf[..HEADER_LEN].copy_from_slice(&M::ID.to_le_bytes());
        let used = value.encode(&mut buf[HEADER_LEN..HEADER_LEN + max_len])?;
        if used > max_len {
            return Err(Error {
                kind: ErrorKind::Other,
            });
        }
        Ok(&buf[..HEADER_LEN + used])
    }
}

/// Result of ingesting a payload into a bus mailbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IngestOutcome {
    pub from: u8,
    pub id: u16,
    pub len: usize,
}

/// Error returned while ingesting payloads into a bus mailbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IngestError {
    MalformedPayload,
    UnknownId { id: u16 },
    BodyTooLarge { got: usize, max: usize },
    MailboxFull,
}

/// Result of one integrated transport-ingest pump step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IngestPumpStatus {
    /// No payload arrived before timeout elapsed.
    TimedOut,
    /// One payload was received and ingested into the matching mailbox.
    Delivered(IngestOutcome),
}

/// Error returned by integrated transport-ingest pump operations.
#[derive(Debug)]
pub enum IngestPumpError<E> {
    /// Caller-provided RX scratch buffer was too small.
    RecvBufferTooSmall { needed: usize, got: usize },
    /// Underlying transport receive error.
    RecvBackend(E),
    /// Message could not be ingested into mailbox state.
    Ingest(IngestError),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MailboxSlot<const MAX_BODY: usize> {
    from: u8,
    len: usize,
    body: [u8; MAX_BODY],
}

impl<const MAX_BODY: usize> MailboxSlot<MAX_BODY> {
    const fn empty() -> Self {
        Self {
            from: 0,
            len: 0,
            body: [0u8; MAX_BODY],
        }
    }
}

#[derive(Debug)]
struct TypeMailbox<const DEPTH: usize, const MAX_BODY: usize> {
    slots: [MailboxSlot<MAX_BODY>; DEPTH],
    used: usize,
}

impl<const DEPTH: usize, const MAX_BODY: usize> TypeMailbox<DEPTH, MAX_BODY> {
    fn new() -> Self {
        Self {
            slots: [MailboxSlot::empty(); DEPTH],
            used: 0,
        }
    }

    fn push(&mut self, from: u8, body: &[u8]) -> Result<(), IngestError> {
        if body.len() > MAX_BODY {
            return Err(IngestError::BodyTooLarge {
                got: body.len(),
                max: MAX_BODY,
            });
        }
        if self.used == DEPTH {
            return Err(IngestError::MailboxFull);
        }

        let idx = self.used;
        self.slots[idx].from = from;
        self.slots[idx].len = body.len();
        self.slots[idx].body[..body.len()].copy_from_slice(body);
        self.used += 1;
        Ok(())
    }

    fn pop_matching_where<F>(&mut self, from: u8, mut predicate: F) -> Option<MailboxSlot<MAX_BODY>>
    where
        F: FnMut(&[u8]) -> bool,
    {
        let mut idx = None;
        let mut i = 0usize;
        while i < self.used {
            if self.slots[i].from == from {
                let len = self.slots[i].len;
                if predicate(&self.slots[i].body[..len]) {
                    idx = Some(i);
                    break;
                }
            }
            i += 1;
        }

        let idx = idx?;
        let out = self.slots[idx];
        let mut j = idx;
        while j + 1 < self.used {
            self.slots[j] = self.slots[j + 1];
            j += 1;
        }
        self.slots[self.used - 1] = MailboxSlot::empty();
        self.used -= 1;
        Some(out)
    }
}

#[derive(Debug)]
struct RxState<const MAX_TYPES: usize, const DEPTH: usize, const MAX_BODY: usize> {
    by_type: [TypeMailbox<DEPTH, MAX_BODY>; MAX_TYPES],
}

impl<const MAX_TYPES: usize, const DEPTH: usize, const MAX_BODY: usize>
    RxState<MAX_TYPES, DEPTH, MAX_BODY>
{
    fn new() -> Self {
        Self {
            by_type: core::array::from_fn(|_| TypeMailbox::new()),
        }
    }

    fn push(&mut self, slot: usize, from: u8, body: &[u8]) -> Result<(), IngestError> {
        self.by_type[slot].push(from, body)
    }

    fn pop_matching_where<F>(
        &mut self,
        slot: usize,
        from: u8,
        predicate: F,
    ) -> Option<MailboxSlot<MAX_BODY>>
    where
        F: FnMut(&[u8]) -> bool,
    {
        self.by_type[slot].pop_matching_where(from, predicate)
    }
}

/// Typed received message payload returned by protocol receive helpers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Received<M, const MAX_BODY: usize>
where
    M: CapnpMessage,
{
    /// Sender address.
    pub from: u8,
    /// Message id.
    pub id: u16,
    len: usize,
    body: [u8; MAX_BODY],
    _marker: PhantomData<M>,
}

impl<M, const MAX_BODY: usize> Received<M, MAX_BODY>
where
    M: CapnpMessage,
{
    fn from_slot(from: u8, slot: MailboxSlot<MAX_BODY>) -> Self {
        Self {
            from,
            id: M::ID,
            len: slot.len,
            body: slot.body,
            _marker: PhantomData,
        }
    }

    /// Borrow raw body bytes (without the 2-byte thincan header).
    pub fn body(&self) -> &[u8] {
        &self.body[..self.len]
    }

    /// Borrow this payload as a typed Cap'n Proto helper.
    pub fn as_capnp(&self) -> CapnpTyped<'_, M::Owned> {
        CapnpTyped::new(self.body())
    }

    /// Read the typed Cap'n Proto root.
    #[cfg(feature = "capnp")]
    pub fn with_root<R>(
        &self,
        options: capnp::message::ReaderOptions,
        f: impl FnOnce(<M::Owned as capnp::traits::Owned>::Reader<'_>) -> R,
    ) -> Result<R, capnp::Error>
    where
        M::Owned: capnp::traits::Owned,
    {
        self.as_capnp().with_root(options, f)
    }
}

/// Maplet-typed shared interface containing transport send path and per-message receive mailboxes.
pub struct Interface<
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
> where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    tx_state: embassy_sync::mutex::Mutex<RM, TxState<Node, TxBuf>>,
    rx_transport: embassy_sync::mutex::Mutex<RM, Node>,
    rx_state: embassy_sync::mutex::Mutex<RM, RxState<MAX_TYPES, DEPTH, MAX_BODY>>,
    notify: [embassy_sync::watch::Watch<RM, (), MAX_WAITERS>; MAX_TYPES],
    _maplet: PhantomData<Maplet>,
}

impl<
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
> Interface<Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
    TxBuf: AsMut<[u8]>,
{
    /// Create a new maplet-typed interface from split transport endpoints and caller-provided TX buffer.
    pub fn new(tx_node: Node, rx_node: Node, tx: TxBuf) -> Self {
        Self {
            tx_state: embassy_sync::mutex::Mutex::new(TxState { node: tx_node, tx }),
            rx_transport: embassy_sync::mutex::Mutex::new(rx_node),
            rx_state: embassy_sync::mutex::Mutex::new(RxState::new()),
            notify: core::array::from_fn(|_| embassy_sync::watch::Watch::new_with(())),
            _maplet: PhantomData,
        }
    }

    /// Create a new maplet-typed interface using the same transport endpoint for TX and RX.
    pub fn new_shared(node: Node, tx: TxBuf) -> Self
    where
        Node: Clone,
    {
        Self::new(node.clone(), node, tx)
    }

    /// Create a cloneable bus handle borrowing this interface.
    pub fn bus(
        &self,
    ) -> BusHandle<'_, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS> {
        BusHandle {
            iface: self,
            _bundle: PhantomData,
        }
    }

    /// Mutably borrow the underlying transport node.
    pub fn node_mut(&mut self) -> &mut Node {
        self.tx_node_mut()
    }

    /// Mutably borrow the TX transport endpoint.
    pub fn tx_node_mut(&mut self) -> &mut Node {
        &mut self.tx_state.get_mut().node
    }

    /// Mutably borrow the RX transport endpoint.
    pub fn rx_node_mut(&mut self) -> &mut Node {
        self.rx_transport.get_mut()
    }

    /// Encode a Cap'n Proto value for message `M` into this interface's TX buffer.
    pub fn encode_capnp_into<M: CapnpMessage, V: EncodeCapnp<M>>(
        &mut self,
        value: &V,
    ) -> Result<&[u8], Error> {
        let state = self.tx_state.get_mut();
        TxState::<Node, TxBuf>::encode_capnp_into_buf::<M, V>(state.tx.as_mut(), value)
    }

    /// Encode and send a Cap'n Proto value for message `M` to a specific address.
    pub fn send_capnp_to<M: CapnpMessage, V: EncodeCapnp<M>>(
        &mut self,
        to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error>
    where
        Node: can_isotp_interface::IsoTpEndpoint,
    {
        let tx_state = self.tx_state.get_mut();
        let TxState { node, tx } = tx_state;
        let payload = TxState::<Node, TxBuf>::encode_capnp_into_buf::<M, V>(tx.as_mut(), value)?;
        <Node as can_isotp_interface::IsoTpEndpoint>::send_to(node, to, payload, timeout)
            .map_err(map_isotp_send_error)
    }

    /// Encode and send a Cap'n Proto value for message `M` to a functional address.
    pub fn send_capnp_functional_to<M: CapnpMessage, V: EncodeCapnp<M>>(
        &mut self,
        functional_to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error>
    where
        Node: can_isotp_interface::IsoTpEndpoint,
    {
        let tx_state = self.tx_state.get_mut();
        let TxState { node, tx } = tx_state;
        let payload = TxState::<Node, TxBuf>::encode_capnp_into_buf::<M, V>(tx.as_mut(), value)?;
        <Node as can_isotp_interface::IsoTpEndpoint>::send_functional_to(
            node,
            functional_to,
            payload,
            timeout,
        )
        .map_err(map_isotp_send_error)
    }

    async fn send_capnp_to_async_shared<M: CapnpMessage, V: EncodeCapnp<M>>(
        &self,
        to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error>
    where
        Node: can_isotp_interface::IsoTpAsyncEndpoint,
    {
        let mut state = self.tx_state.lock().await;
        let tx_state = &mut *state;
        let TxState { node, tx } = tx_state;
        let payload = TxState::<Node, TxBuf>::encode_capnp_into_buf::<M, V>(tx.as_mut(), value)?;
        <Node as can_isotp_interface::IsoTpAsyncEndpoint>::send_to(node, to, payload, timeout)
            .await
            .map_err(map_isotp_send_error)
    }

    async fn send_capnp_functional_to_async_shared<M: CapnpMessage, V: EncodeCapnp<M>>(
        &self,
        functional_to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error>
    where
        Node: can_isotp_interface::IsoTpAsyncEndpoint,
    {
        let mut state = self.tx_state.lock().await;
        let tx_state = &mut *state;
        let TxState { node, tx } = tx_state;
        let payload = TxState::<Node, TxBuf>::encode_capnp_into_buf::<M, V>(tx.as_mut(), value)?;
        <Node as can_isotp_interface::IsoTpAsyncEndpoint>::send_functional_to(
            node,
            functional_to,
            payload,
            timeout,
        )
        .await
        .map_err(map_isotp_send_error)
    }
}

impl<
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
> Interface<Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
    Node: can_isotp_interface::IsoTpAsyncEndpoint,
    TxBuf: AsMut<[u8]>,
{
    /// Async addressed send helper.
    pub async fn send_capnp_to_async<M: CapnpMessage, V: EncodeCapnp<M>>(
        &mut self,
        to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error> {
        self.send_capnp_to_async_shared::<M, V>(to, value, timeout)
            .await
    }

    /// Async functional-address send helper.
    pub async fn send_capnp_functional_to_async<M: CapnpMessage, V: EncodeCapnp<M>>(
        &mut self,
        functional_to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error> {
        self.send_capnp_functional_to_async_shared::<M, V>(functional_to, value, timeout)
            .await
    }
}

impl<
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
> Interface<Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
    Node: can_isotp_interface::IsoTpAsyncEndpointRecvInto,
    TxBuf: AsMut<[u8]>,
{
    /// Receive at most one payload from the transport and ingest it into this interface.
    ///
    /// Typical usage is from a dedicated protocol pump task:
    /// - call repeatedly with a reusable RX scratch buffer,
    /// - `TimedOut` can be used to yield/sleep briefly.
    pub async fn pump_ingest_once(
        &self,
        timeout: Duration,
        rx_buf: &mut [u8],
    ) -> Result<IngestPumpStatus, IngestPumpError<Node::Error>> {
        let recv = {
            let mut state = self.rx_transport.lock().await;
            <Node as can_isotp_interface::IsoTpAsyncEndpointRecvInto>::recv_one_into(
                &mut *state,
                timeout,
                rx_buf,
            )
            .await
        };

        match recv {
            Ok(can_isotp_interface::RecvMetaIntoStatus::TimedOut) => Ok(IngestPumpStatus::TimedOut),
            Ok(can_isotp_interface::RecvMetaIntoStatus::DeliveredOne { meta, len }) => {
                let outcome = self
                    .bus()
                    .ingest(meta.reply_to, &rx_buf[..len])
                    .await
                    .map_err(IngestPumpError::Ingest)?;
                Ok(IngestPumpStatus::Delivered(outcome))
            }
            Err(can_isotp_interface::RecvError::BufferTooSmall { needed, got }) => {
                Err(IngestPumpError::RecvBufferTooSmall { needed, got })
            }
            Err(can_isotp_interface::RecvError::Backend(err)) => {
                Err(IngestPumpError::RecvBackend(err))
            }
        }
    }
}

/// Cloneable async protocol handle that borrows a shared [`Interface`].
pub struct BusHandle<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
    B = Unscoped,
> where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    iface: &'a Interface<Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>,
    _bundle: PhantomData<B>,
}

impl<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
    B,
> Copy for BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, B>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
}

impl<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
    B,
> Clone for BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, B>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
    B,
> BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, B>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    /// Ingest one payload delivered by the external demux pump.
    pub async fn ingest(&self, from: u8, payload: &[u8]) -> Result<IngestOutcome, IngestError> {
        let raw = decode_wire(payload).map_err(|_| IngestError::MalformedPayload)?;
        let slot = Maplet::slot_for_id(raw.id).ok_or(IngestError::UnknownId { id: raw.id })?;
        let len = raw.body.len();

        {
            let mut state = self.iface.rx_state.lock().await;
            state.push(slot, from, raw.body)?;
        }

        self.iface.notify[slot].sender().send(());
        Ok(IngestOutcome {
            from,
            id: raw.id,
            len,
        })
    }
}

impl<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
> BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, Unscoped>
where
    Maplet: MapletSpec<MAX_TYPES>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    /// Narrow this handle to a specific bundle's message capabilities.
    pub fn scope<B>(
        self,
    ) -> BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, B>
    where
        Maplet: MapletHasBundle<B>,
    {
        BusHandle {
            iface: self.iface,
            _bundle: PhantomData,
        }
    }
}

impl<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
    B,
> BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, B>
where
    Maplet: MapletSpec<MAX_TYPES> + MapletHasBundle<B>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
    Node: can_isotp_interface::IsoTpAsyncEndpoint,
    TxBuf: AsMut<[u8]>,
{
    /// Hidden protocol primitive: async addressed send.
    #[doc(hidden)]
    pub async fn __send_capnp_to<M: CapnpMessage, V: EncodeCapnp<M>>(
        &self,
        to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error> {
        self.iface
            .send_capnp_to_async_shared::<M, V>(to, value, timeout)
            .await
    }

    /// Hidden protocol primitive: async functional-address send.
    #[doc(hidden)]
    pub async fn __send_capnp_functional_to<M: CapnpMessage, V: EncodeCapnp<M>>(
        &self,
        functional_to: u8,
        value: &V,
        timeout: Duration,
    ) -> Result<(), Error> {
        self.iface
            .send_capnp_functional_to_async_shared::<M, V>(functional_to, value, timeout)
            .await
    }
}

impl<
    'a,
    Maplet,
    RM,
    Node,
    TxBuf,
    const MAX_TYPES: usize,
    const DEPTH: usize,
    const MAX_BODY: usize,
    const MAX_WAITERS: usize,
    B,
> BusHandle<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS, B>
where
    Maplet: MapletSpec<MAX_TYPES> + MapletHasBundle<B>,
    RM: embassy_sync::blocking_mutex::raw::RawMutex,
{
    /// Hidden protocol primitive: wait for the next message of type `M` from `from`.
    #[doc(hidden)]
    pub async fn __recv_next_capnp_from<M: CapnpMessage>(
        &self,
        from: u8,
    ) -> Result<Received<M, MAX_BODY>, Error> {
        self.__recv_next_capnp_from_where::<M, _>(from, |_| true)
            .await
    }

    /// Hidden protocol primitive: wait for the next message of type `M` from `from` that
    /// satisfies `predicate`.
    #[doc(hidden)]
    pub async fn __recv_next_capnp_from_where<M: CapnpMessage, F>(
        &self,
        from: u8,
        mut predicate: F,
    ) -> Result<Received<M, MAX_BODY>, Error>
    where
        F: FnMut(&[u8]) -> bool,
    {
        let slot = Maplet::slot_for_id(M::ID).ok_or(Error {
            kind: ErrorKind::Other,
        })?;

        let mut receiver = self.iface.notify[slot].receiver().ok_or(Error {
            kind: ErrorKind::Other,
        })?;

        loop {
            {
                let mut state = self.iface.rx_state.lock().await;
                if let Some(found) = state.pop_matching_where(slot, from, &mut predicate) {
                    return Ok(Received::from_slot(from, found));
                }
            }

            let _ = receiver.changed().await;
        }
    }
}

/// Define a bus atlas: a registry of message ids and names.
#[macro_export]
macro_rules! bus_atlas {
    (
        $vis:vis mod $atlas:ident {
            $($entries:tt)*
        }
    ) => {
        $vis mod $atlas {
            #[derive(Debug, Clone, Copy, Default)]
            /// Marker type representing this atlas.
            pub struct Atlas;
            $crate::bus_atlas!(@entries $($entries)*);
        }
    };

    (@entries) => {};

    (@entries $(#[$meta:meta])* $id:literal => $name:ident (capnp = $owned:path); $($rest:tt)*) => {
        $(#[$meta])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub struct $name;

        impl $crate::Message for $name {
            const ID: u16 = $id;
        }

        impl $crate::CapnpMessage for $name {
            type Owned = $owned;
        }

        $crate::bus_atlas!(@entries $($rest)*);
    };

    (@entries $(#[$meta:meta])* $id:literal => removed; $($rest:tt)*) => {
        $(#[$meta])*
        #[allow(dead_code)]
        const _: u16 = $id;
        $crate::bus_atlas!(@entries $($rest)*);
    };
}

/// Generate a bundle instance wrapper struct and its [`BundleFactory`] implementation.
///
/// # Usage
///
/// ```rust,ignore
/// thincan::bundle_instance! {
///     pub struct TelemetryBundleInstance for Bundle;
/// }
/// ```
///
/// This expands to:
/// - A struct `TelemetryBundleInstance<'a, Maplet, RM, Node, TxBuf, const MAX_TYPES, ...>`
///   holding a scoped [`BusHandle`].
/// - A `pub const fn new(handle: ...) -> Self` constructor.
/// - A [`BundleFactory`] impl for `Bundle` that delegates to `new`.
///
/// Protocol methods should be added in a separate `impl` block in the same module,
/// where they can access the `handle` field:
///
/// ```rust,ignore
/// impl<
///     'a, Maplet, RM, Node, TxBuf,
///     const MAX_TYPES: usize, const DEPTH: usize, const MAX_BODY: usize, const MAX_WAITERS: usize,
/// > TelemetryBundleInstance<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>
/// where
///     Maplet: thincan::MapletSpec<MAX_TYPES> + thincan::MapletHasBundle<Bundle>,
///     RM: thincan::RawMutex,
///     Node: can_isotp_interface::IsoTpAsyncEndpoint,
///     TxBuf: AsMut<[u8]>,
/// {
///     pub async fn send_status_to(&self, to: u8, ...) -> Result<(), thincan::Error> {
///         self.bus.__send_capnp_to::<atlas::MyMessage, _>(to, &value, timeout).await
///     }
/// }
/// ```
#[macro_export]
macro_rules! bundle_instance {
    (
        $vis:vis struct $name:ident for $bundle:ty;
    ) => {
        $vis struct $name<
            'a,
            Maplet,
            RM,
            Node,
            TxBuf,
            const MAX_TYPES: usize,
            const DEPTH: usize,
            const MAX_BODY: usize,
            const MAX_WAITERS: usize,
        >
        where
            Maplet: $crate::MapletSpec<MAX_TYPES> + $crate::MapletHasBundle<$bundle>,
            RM: $crate::RawMutex,
        {
            pub(super) bus: $crate::BusHandle<
                'a,
                Maplet,
                RM,
                Node,
                TxBuf,
                MAX_TYPES,
                DEPTH,
                MAX_BODY,
                MAX_WAITERS,
                $bundle,
            >,
        }

        impl<
            'a,
            Maplet,
            RM,
            Node,
            TxBuf,
            const MAX_TYPES: usize,
            const DEPTH: usize,
            const MAX_BODY: usize,
            const MAX_WAITERS: usize,
        >
            $name<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>
        where
            Maplet: $crate::MapletSpec<MAX_TYPES> + $crate::MapletHasBundle<$bundle>,
            RM: $crate::RawMutex,
        {
            pub const fn new(
                bus: $crate::BusHandle<
                    'a,
                    Maplet,
                    RM,
                    Node,
                    TxBuf,
                    MAX_TYPES,
                    DEPTH,
                    MAX_BODY,
                    MAX_WAITERS,
                    $bundle,
                >,
            ) -> Self {
                Self { bus }
            }
        }

        impl<
            'a,
            Maplet,
            RM,
            Node,
            TxBuf,
            const MAX_TYPES: usize,
            const DEPTH: usize,
            const MAX_BODY: usize,
            const MAX_WAITERS: usize,
        >
            $crate::BundleFactory<
                'a,
                Maplet,
                RM,
                Node,
                TxBuf,
                MAX_TYPES,
                DEPTH,
                MAX_BODY,
                MAX_WAITERS,
            > for $bundle
        where
            Maplet: $crate::MapletSpec<MAX_TYPES> + $crate::MapletHasBundle<$bundle> + 'a,
            RM: $crate::RawMutex + 'a,
            Node: 'a,
            TxBuf: 'a,
        {
            type Instance =
                $name<'a, Maplet, RM, Node, TxBuf, MAX_TYPES, DEPTH, MAX_BODY, MAX_WAITERS>;

            fn make(
                bus: $crate::BusHandle<
                    'a,
                    Maplet,
                    RM,
                    Node,
                    TxBuf,
                    MAX_TYPES,
                    DEPTH,
                    MAX_BODY,
                    MAX_WAITERS,
                    Self,
                >,
            ) -> Self::Instance {
                $name::new(bus)
            }
        }
    };
}

/// Define a maplet by composing message bundles.
#[macro_export]
macro_rules! maplet {
    (
        $vis:vis mod $maplet:ident : $atlas:ident {
            use msgs [ $($msg:ident),* $(,)? ];
        }
    ) => {
        $crate::maplet!(@define_from_msgs $vis mod $maplet : $atlas { [ $($msg),* ] });
    };

    (
        $vis:vis mod $maplet:ident : $atlas:ident {
            bundles [ $( $bundle:ident ),* $(,)? ];
        }
    ) => {
        $crate::maplet!(@define_from_bundles $vis mod $maplet : $atlas { [ $($bundle),* ] });
    };

    (
        $vis:vis mod $maplet:ident : $atlas:ident {
            bundles [ $( $alias:ident = $bundle:ident ),* $(,)? ];
        }
    ) => {
        $crate::maplet!(@define_from_bundles_aliases $vis mod $maplet : $atlas { [ $( $alias = $bundle ),* ] });
    };

    (
        $vis:vis mod $maplet:ident : $atlas:ident {
            bundles [ $( $bundle:ident => [ $($msg:ident),* $(,)? ] ),* $(,)? ];
        }
    ) => {
        $crate::maplet!(@define_from_msgs $vis mod $maplet : $atlas { [ $($($msg),*),* ] });
    };

    (@define_from_msgs $vis:vis mod $maplet:ident : $atlas:ident { [ $($msg:ident),* ] }) => {
        $vis mod $maplet {
            #[derive(Clone, Copy, Debug, Default)]
            pub struct Maplet;

            pub const MESSAGE_COUNT: usize = [$(<super::$atlas::$msg as $crate::Message>::ID),*].len();

            impl $crate::MapletSpec<{ MESSAGE_COUNT }> for Maplet {
                const MESSAGE_IDS: [u16; MESSAGE_COUNT] = [
                    $(<super::$atlas::$msg as $crate::Message>::ID),*
                ];
            }

            pub type Interface<
                RM,
                Node,
                TxBuf,
                const DEPTH: usize,
                const MAX_BODY: usize,
                const MAX_WAITERS: usize,
            > = $crate::Interface<Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>;

            pub type BusHandle<'a, RM, Node, TxBuf, const DEPTH: usize, const MAX_BODY: usize, const MAX_WAITERS: usize, B = $crate::Unscoped> =
                $crate::BusHandle<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS, B>;
        }
    };

    (@define_from_bundles $vis:vis mod $maplet:ident : $atlas:ident { [ $($bundle:ident),* ] }) => {
        $vis mod $maplet {
            #[derive(Clone, Copy, Debug, Default)]
            pub struct Maplet;

            pub const MESSAGE_COUNT: usize = 0 $(+ super::$bundle::MESSAGE_COUNT)*;

            impl $crate::MapletSpec<{ MESSAGE_COUNT }> for Maplet {
                const MESSAGE_IDS: [u16; MESSAGE_COUNT] = {
                    let mut out = [0u16; MESSAGE_COUNT];
                    let mut at = 0usize;
                    $(
                        let ids = <super::$bundle::Bundle as $crate::BundleSpec<{ super::$bundle::MESSAGE_COUNT }>>::MESSAGE_IDS;
                        let mut i = 0usize;
                        while i < super::$bundle::MESSAGE_COUNT {
                            out[at + i] = ids[i];
                            i += 1;
                        }
                        at += super::$bundle::MESSAGE_COUNT;
                    )*
                    out
                };
            }

            $(
                impl $crate::MapletHasBundle<super::$bundle::Bundle> for Maplet {}
            )*

            const _: () = {
                let ids = <Maplet as $crate::MapletSpec<{ MESSAGE_COUNT }>>::MESSAGE_IDS;
                let mut i = 0usize;
                while i < MESSAGE_COUNT {
                    let mut j = i + 1usize;
                    while j < MESSAGE_COUNT {
                        if ids[i] == ids[j] {
                            panic!("duplicate message id in maplet bundles");
                        }
                        j += 1;
                    }
                    i += 1;
                }
            };

            pub type Interface<
                RM,
                Node,
                TxBuf,
                const DEPTH: usize,
                const MAX_BODY: usize,
                const MAX_WAITERS: usize,
            > = $crate::Interface<Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>;

            pub type BusHandle<'a, RM, Node, TxBuf, const DEPTH: usize, const MAX_BODY: usize, const MAX_WAITERS: usize, B = $crate::Unscoped> =
                $crate::BusHandle<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS, B>;
        }
    };

    (@define_from_bundles_aliases $vis:vis mod $maplet:ident : $atlas:ident { [ $( $alias:ident = $bundle:ident ),* ] }) => {
        $vis mod $maplet {
            #[derive(Clone, Copy, Debug, Default)]
            pub struct Maplet;

            pub const MESSAGE_COUNT: usize = 0 $(+ super::$bundle::MESSAGE_COUNT)*;

            impl $crate::MapletSpec<{ MESSAGE_COUNT }> for Maplet {
                const MESSAGE_IDS: [u16; MESSAGE_COUNT] = {
                    let mut out = [0u16; MESSAGE_COUNT];
                    let mut at = 0usize;
                    $(
                        let ids = <super::$bundle::Bundle as $crate::BundleSpec<{ super::$bundle::MESSAGE_COUNT }>>::MESSAGE_IDS;
                        let mut i = 0usize;
                        while i < super::$bundle::MESSAGE_COUNT {
                            out[at + i] = ids[i];
                            i += 1;
                        }
                        at += super::$bundle::MESSAGE_COUNT;
                    )*
                    out
                };
            }

            $(
                impl $crate::MapletHasBundle<super::$bundle::Bundle> for Maplet {}
            )*

            const _: () = {
                let ids = <Maplet as $crate::MapletSpec<{ MESSAGE_COUNT }>>::MESSAGE_IDS;
                let mut i = 0usize;
                while i < MESSAGE_COUNT {
                    let mut j = i + 1usize;
                    while j < MESSAGE_COUNT {
                        if ids[i] == ids[j] {
                            panic!("duplicate message id in maplet bundles");
                        }
                        j += 1;
                    }
                    i += 1;
                }
            };

            pub type Interface<
                RM,
                Node,
                TxBuf,
                const DEPTH: usize,
                const MAX_BODY: usize,
                const MAX_WAITERS: usize,
            > = $crate::Interface<Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>;

            pub type BusHandle<'a, RM, Node, TxBuf, const DEPTH: usize, const MAX_BODY: usize, const MAX_WAITERS: usize, B = $crate::Unscoped> =
                $crate::BusHandle<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS, B>;

            pub struct Bundles<'a, RM, Node, TxBuf, const DEPTH: usize, const MAX_BODY: usize, const MAX_WAITERS: usize>
            where
                RM: $crate::RawMutex,
                TxBuf: AsMut<[u8]>,
                $(
                    super::$bundle::Bundle: $crate::BundleFactory<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>,
                )*
            {
                $(
                    pub $alias: <super::$bundle::Bundle as $crate::BundleFactory<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>>::Instance,
                )*
            }

            impl<'a, RM, Node, TxBuf, const DEPTH: usize, const MAX_BODY: usize, const MAX_WAITERS: usize>
                Bundles<'a, RM, Node, TxBuf, DEPTH, MAX_BODY, MAX_WAITERS>
            where
                RM: $crate::RawMutex,
                TxBuf: AsMut<[u8]>,
                $(
                    super::$bundle::Bundle: $crate::BundleFactory<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>,
                )*
            {
                pub fn new(iface: &'a Interface<RM, Node, TxBuf, DEPTH, MAX_BODY, MAX_WAITERS>) -> Self {
                    let ingress = iface.bus();
                    Self {
                        $(
                            $alias: <super::$bundle::Bundle as $crate::BundleFactory<'a, Maplet, RM, Node, TxBuf, { MESSAGE_COUNT }, DEPTH, MAX_BODY, MAX_WAITERS>>::make(
                                ingress.scope::<super::$bundle::Bundle>(),
                            ),
                        )*
                    }
                }
            }
        }
    };
}