crosstalk 1.0.0

An extremely lightweight, topic-based, cross-thread, in-memory communication library
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
#![doc(html_root_url = "https://docs.rs/crosstalk/1.0")]
#![doc = include_str!("../README.md")]
// --------------------------------------------------
// external
// --------------------------------------------------
use std::sync::Arc;
use tokio::sync::Mutex;
use std::collections::HashMap;
use tokio::sync::broadcast::{
    Sender as TokioSender,
    Receiver as TokioReceiver,
};

// --------------------------------------------------
// local
// --------------------------------------------------
pub use crosstalk_macros::init;
pub use crosstalk_macros::AsTopic;

// --------------------------------------------------
// re-exports
// --------------------------------------------------
pub mod __macro_exports {
    pub use tokio::runtime;
    pub use tokio::sync::broadcast;

    #[inline(always)]
    /// Downcasts a [`Box`] into a type `T`
    /// 
    /// # Arguments
    /// 
    /// * `buf` - the [`Box`] to downcast
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::__macro_exports::downcast;
    /// 
    /// let mut buf = Box::new(5) as Box<dyn std::any::Any + 'static>;
    /// assert_eq!(downcast::<i32>(buf, crosstalk::Error::PublisherMismatch("foo", "bar")).unwrap(), 5);
    /// ```
    pub fn downcast<T>(buf: Box<dyn std::any::Any + 'static>, on_error: crate::Error) -> Result<T, crate::Error>
    where
        T: 'static,
    {
        match buf.downcast::<T>() {
            Ok(t) => Ok(*t),
            Err(_) => Err(on_error),
        }
    }
}

/// A trait bound an enum as a [`CrosstalkTopic`]
pub trait CrosstalkTopic: Eq + Copy + Clone + PartialEq + std::hash::Hash {}

/// A trait to bound a datatype as a [`CrosstalkData`]
pub trait CrosstalkData: Clone + Send + 'static {}
/// [`CrosstalkData`] implementation for all types
impl<T: Clone + Send + 'static> CrosstalkData for T {}

#[derive(Copy, Clone, Debug)]
/// [`crosstalk`](crate) errors
pub enum Error {
    PublisherMismatch(&'static str, &'static str),
    SubscriberMismatch(&'static str, &'static str),
}
/// [`crosstalk::Error`](crate::Error) implementation of [`std::error::Error`]
impl std::error::Error for Error {}
/// [`crosstalk::Error`](crate::Error) implementation of [`std::fmt::Display`]
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::PublisherMismatch(input, output) => write!(f, "Publisher type mismatch: {} (cast) != {} (expected)", input, output),
            Error::SubscriberMismatch(input, output) => write!(f, "Subscriber type mismatch: {} (cast) != {} (expected)", input, output),
        }
    }
}

/// A trait to define a [`CrosstalkPubSub`]
/// 
/// This is used to implement the [`CrosstalkPubSub`] trait
/// using the [`crosstalk_macros::init!`] macro
/// for the [`ImplementedBoundedNode`] struct
/// 
/// This is not meant to be used directly, and is automatically
/// implemented when calling [`crosstalk_macros::init!`]
pub trait CrosstalkPubSub<T> {
    fn publisher<D: CrosstalkData>(&mut self, topic: T) -> Result<Publisher<D, T>, crate::Error>;
    
    fn subscriber<D: CrosstalkData>(&mut self, topic: T) -> Result<Subscriber<D, T>, crate::Error>;
    
    #[allow(clippy::type_complexity)]
    fn pubsub<D: CrosstalkData>(&mut self, topic: T) -> Result<(Publisher<D, T>, Subscriber<D, T>), crate::Error>;
}

#[derive(Clone)]
/// A [`BoundedNode`] is a node to spawn publishers and
/// subscribers on, where the size of each buffer is
/// fixed.
/// 
/// # Attributes
/// 
/// * `node` - the node to spawn publishers and subscribers on
/// * `size` - the size of each buffer
/// 
/// # Type Parameters
/// 
/// * `T` - the topic enum name
/// 
/// # Examples
/// 
/// ```
/// use crosstalk::AsTopic;
/// 
/// #[derive(AsTopic)]
/// enum House {
///     Bedroom,
///     LivingRoom,
///     Kitchen,
///     Bathroom,
/// }
/// 
/// crosstalk::init! {
///     House::Bedroom => String,
///     House::LivingRoom => String,
///     House::Kitchen => Vec<f32>,
///     House::Bathroom => u8,
/// }
/// 
/// let mut node = crosstalk::BoundedNode::<House>::new(10);
/// let (pub0, mut sub0) = node.pubsub_blocking(House::Bedroom).unwrap();
/// let (pub1, mut sub1) = node.pubsub_blocking(House::Bedroom).unwrap();
/// 
/// pub0.write("Hello".to_string());
/// pub0.write("World".to_string());
/// pub1.write("Foo".to_string());
/// pub1.write("Bar".to_string());
/// 
/// assert_eq!(sub1.try_read().unwrap(), "Hello");
/// assert_eq!(sub1.try_read().unwrap(), "World");
/// assert_eq!(sub1.try_read().unwrap(), "Foo");
/// assert_eq!(sub1.try_read().unwrap(), "Bar");
/// 
/// assert_eq!(sub0.try_read().unwrap(), "Hello");
/// assert_eq!(sub0.try_read().unwrap(), "World");
/// assert_eq!(sub0.try_read().unwrap(), "Foo");
/// assert_eq!(sub0.try_read().unwrap(), "Bar");
/// ```
pub struct BoundedNode<T> {
    pub node: Arc<Mutex<ImplementedBoundedNode<T>>>,
    pub size: usize,
}
/// [`BoundedNode`] implementation 
/// 
/// This holds an [`Arc<Mutex<ImplementedBoundedNode<T>>>`], which
/// references the true (private) node that implements the [`AsTopic`] trait.
impl<T> BoundedNode<T> 
where
    T: CrosstalkTopic,
    ImplementedBoundedNode<T>: CrosstalkPubSub<T>,
{
    #[inline(always)]
    /// Creates a new [`BoundedNode`]
    /// 
    /// # Arguments
    /// 
    /// * `size` - the size of each buffer
    /// 
    /// # Panics
    /// 
    /// Panics if `size` is 0. This is intentional because of two reasons:
    /// 
    /// 1. No buffer can have a size of 0.
    /// 2. A [`tokio::sync::broadcast::Sender`] cannot be created with a size of 0,
    ///    and therefore, a [`BoundedNode`] could potentially be created without
    ///    error but then calling [`BoundedNode::publisher`] or [`BoundedNode::subscriber`]
    ///    would result in a panic later on.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// fn main() {
    ///     let node = crosstalk::BoundedNode::<House>::new(10);
    ///     let moved_node = node.clone();
    ///     std::thread::spawn(move || another_thread(moved_node));
    ///     assert_eq!(node.size, 10);
    /// }
    /// 
    /// fn another_thread(mut node: crosstalk::BoundedNode<House>) {
    ///     assert_eq!(node.size, 10);
    /// }
    /// ```
    pub fn new(size: usize) -> Self {
        if size == 0 {
            panic!("Size must be greater than 0. Attempting to make `tokio::sync::broadcast::channels` later will result in a panic.");
        }
        Self {
            node: Arc::new(Mutex::new(ImplementedBoundedNode::<T>::new(size))),
            size,
        }
    }

    #[inline(always)]
    /// Creates a new publisher for the given topic `T`
    /// 
    /// # Arguments
    /// 
    /// * `topic` - the topic to create a publisher for
    /// 
    /// # Returns
    /// 
    /// A publisher for the topic `T`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut node = crosstalk::BoundedNode::<House>::new(10);
    ///     assert!(node.publisher::<String>(House::Bedroom).await.is_ok());
    /// }
    /// ```
    pub async fn publisher<D: CrosstalkData>(&mut self, topic: T) -> Result<Publisher<D, T>, crate::Error> {
        self.node.lock().await.publisher(topic)
    }

    #[inline(always)]
    /// Creates a new publisher for the given topic `T`
    /// 
    /// # Arguments
    /// 
    /// * `topic` - the topic to create a publisher for
    /// 
    /// # Returns
    /// 
    /// A publisher for the topic `T`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// assert!(node.publisher_blocking::<String>(House::Bedroom).is_ok());
    /// ```
    pub fn publisher_blocking<D: CrosstalkData>(&mut self, topic: T) -> Result<Publisher<D, T>, crate::Error> {
        self.node.blocking_lock().publisher(topic)
    }

    #[inline(always)]
    /// Creates a new subscriber for the given topic `T`
    /// 
    /// # Arguments
    /// 
    /// * `topic` - the topic to create a subscriber for
    /// 
    /// # Returns
    /// 
    /// A subscriber for the topic `T`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut node = crosstalk::BoundedNode::<House>::new(10);
    ///     assert!(node.subscriber::<String>(House::Bedroom).await.is_ok());
    /// }
    /// ```
    pub async fn subscriber<D: CrosstalkData>(&mut self, topic: T) -> Result<Subscriber<D, T>, crate::Error> {
        self.node.lock().await.subscriber(topic)
    }

    #[inline(always)]
    /// Creates a new subscriber for the given topic `T`
    /// 
    /// # Arguments
    /// 
    /// * `topic` - the topic to create a subscriber for
    /// 
    /// # Returns
    /// 
    /// A subscriber for the topic `T`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// assert!(node.subscriber_blocking::<String>(House::Bedroom).is_ok());
    /// ```
    pub fn subscriber_blocking<D: CrosstalkData>(&mut self, topic: T) -> Result<Subscriber<D, T>, crate::Error> {
        self.node.blocking_lock().subscriber(topic)
    }

    #[inline(always)]
    /// Creates a new publisher and subscriber for the given topic `T`
    /// 
    /// # Arguments
    /// 
    /// * `topic` - the topic to create a publisher and subscriber for
    /// 
    /// # Returns
    /// 
    /// A publisher and subscriber for the topic `T`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut node = crosstalk::BoundedNode::<House>::new(10);
    ///     let (publisher, mut subscriber) = node.pubsub(House::Bedroom).await.unwrap();
    ///     publisher.write("hello".to_string());
    ///     assert_eq!(subscriber.try_read().unwrap(), "hello");
    /// }
    /// ```
    /// 
    pub async fn pubsub<D: CrosstalkData>(&mut self, topic: T) -> Result<(Publisher<D, T>, Subscriber<D, T>), crate::Error> {
        self.node.lock().await.pubsub(topic)
    }

    #[inline(always)]
    #[allow(clippy::type_complexity)]
    /// Creates a new publisher and subscriber for the given topic `T`
    /// 
    /// # Arguments
    /// 
    /// * `topic` - the topic to create a publisher and subscriber for
    /// 
    /// # Returns
    /// 
    /// A publisher and subscriber for the topic `T`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// let (publisher, mut subscriber) = node.pubsub_blocking(House::Bedroom).unwrap();
    /// publisher.write("hello".to_string());
    /// assert_eq!(subscriber.try_read().unwrap(), "hello");
    /// ```
    /// 
    pub fn pubsub_blocking<D: CrosstalkData>(&mut self, topic: T) -> Result<(Publisher<D, T>, Subscriber<D, T>), crate::Error> {
        self.node.blocking_lock().pubsub(topic)
    }
}

/// The inner implementation of the node,
/// which implements the [`AsTopic`] trait
/// 
/// This is auto-generated by the [`crosstalk_macros::init!`] macro
/// 
/// # Attributes
/// 
/// * `senders` - the senders of the node
/// * `size` - the size of each buffer
pub struct ImplementedBoundedNode<T> {
    pub senders: HashMap<T, Box<dyn std::any::Any + 'static>>,
    pub size: usize,
}

/// [`ImplementedBoundedNode`] implementation of [`Send`]
unsafe impl<T> Send for ImplementedBoundedNode<T> {}
/// [`ImplementedBoundedNode`] implementation of [`Sync`]
unsafe impl<T> Sync for ImplementedBoundedNode<T> {}

/// [`ImplementedBoundedNode`] implementation 
impl<T> ImplementedBoundedNode<T>
where
    T: CrosstalkTopic,
{
    /// See [`BoundedNode::new`]
    /// 
    /// # Arguments
    /// 
    /// * `size` - the size of each buffer
    pub fn new(size: usize) -> Self {
        Self {
            senders: HashMap::new(),
            size,
        }
    }
}

#[derive(Clone)]
/// A `crosstalk` [`Publisher`]
/// 
/// # Attributes
/// 
/// * `topic` - the topic of the publisher
/// * `buf` - the buffer which broadcasts the data
/// 
/// # Type Parameters
/// 
/// * `T` - the topic of the publisher
/// * `D` - the data type of the publisher
/// 
/// This is not meant to be used directly, please
/// use the [`crosstalk_macros::init!`] macro instead
/// and produce a [`Publisher`] with [`BoundedNode::publisher`]
/// or [`BoundedNode::pubsub`]
pub struct Publisher<D, T> {
    pub topic: T,
    buf: TokioSender<D>,
}
/// [`Publisher`] implementation
impl<D, T> Publisher<D, T> {
    #[inline(always)]
    /// See [`BoundedNode::publisher`]
    pub fn new(topic: T, buf: TokioSender<D>) -> Self {
        Self { topic, buf }
    }

    #[inline(always)]
    /// Publishes data to a topic, broadcasting it to all subscribers
    /// 
    /// # Arguments
    /// 
    /// * `sample` - the sample to publish
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// let (publisher, mut subscriber) = node.pubsub_blocking(House::Bedroom).unwrap();
    /// publisher.write("hello".to_string());
    /// std::thread::spawn(move || {
    ///     assert_eq!(subscriber.try_read().unwrap(), "hello");
    /// });
    /// ```
    pub fn write(&self, sample: D) {
        let _ = self.buf.send(sample);
    }
}

/// A `crosstalk` [`Subscriber`]
/// 
/// # Attributes
/// 
/// * `topic` - the topic of the subscriber
/// * `rcvr` - the receiver of the subscriber
/// * `sndr` - the sender for the topic. This is used to spawn multiple receivers upon [`Subscriber::clone`]
/// 
/// # Type Parameters
/// 
/// * `T` - the topic of the subscriber
/// * `D` - the data type of the subscriber
/// 
/// This is not meant to be used directly, please
/// use the [`crosstalk_macros::init!`] macro instead
/// and produce a [`Subscriber`] with [`BoundedNode::subscriber`]
/// or [`BoundedNode::pubsub`]
pub struct Subscriber<D, T> {
    pub topic: T,
    rcvr: Receiver<D>,
    sndr: Arc<TokioSender<D>>,
}
/// [`Subscriber`] implementation 
impl<D: Clone, T: Clone> Subscriber<D, T> {
    #[inline(always)]
    /// See [`BoundedNode::subscriber`]
    pub fn new(
        topic: T,
        rcvr: Option<TokioReceiver<D>>,
        sndr: Arc<TokioSender<D>>,
    ) -> Self {
        Self {
            topic,
            rcvr: Receiver::new(rcvr.unwrap_or(sndr.subscribe())),
            sndr: sndr.clone(),
        }
    }

    #[inline(always)]
    /// Asynchronous blocking read from the [`TokioReceiver`]
    /// 
    /// The sequential equivalent to this function is [`Subscriber::read_blocking`]
    /// which can be used outside of an asynchronous context
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut node = crosstalk::BoundedNode::<House>::new(10);
    ///     let (publisher, mut subscriber) = node.pubsub(House::Bedroom).await.unwrap();
    ///     publisher.write("hello".to_string());
    ///     assert_eq!(subscriber.read().await, Some("hello".to_string()));
    /// }
    /// ```
    pub async fn read(&mut self) -> Option<D> {
        self.rcvr.read().await
    }
    
    #[inline(always)]
    /// Non-blocking read from [`TokioReceiver`]
    /// Upon immediate failure, [`None`] will be returned
    /// 
    /// Difference between this function and [`Subscriber::try_read_raw`]
    /// is that this function continuously loops upon [`tokio`] error of
    /// [`tokio::sync::broadcast::error::TryRecvError::Lagged`], looping
    /// until a valid message is received OR the buffer is determined to be
    /// empty
    /// 
    /// [`Subscriber::try_read_raw`] will return [`None`] upon
    /// [`tokio::sync::broadcast::error::TryRecvError::Lagged`], which
    /// can cause some unexpected behavior
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// let (publisher, mut subscriber) = node.pubsub_blocking(House::Bedroom).unwrap();
    /// publisher.write("hello".to_string());
    /// assert_eq!(subscriber.try_read(), Some(String::from("hello")));
    /// assert_eq!(subscriber.try_read(), None);
    /// ```
    pub fn try_read(&mut self) -> Option<D> {
        self.rcvr.try_read()
    }

    #[inline(always)]
    /// Non-blocking read from [`TokioReceiver`], returning
    /// [`None`] if there are no messages available or if 
    /// [`tokio::sync::broadcast::error::TryRecvError::Lagged`] occurs.
    /// 
    /// This function can cause some unexpected behavior. It is recommended
    /// to use [`Subscriber::try_read`] instead.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// let (publisher, mut subscriber) = node.pubsub_blocking(House::Bedroom).unwrap();
    /// publisher.write("hello".to_string());
    /// assert_eq!(subscriber.try_read_raw(), Some(String::from("hello")));
    /// assert_eq!(subscriber.try_read_raw(), None);
    /// ```
    pub fn try_read_raw(&mut self) -> Option<D> {
        self.rcvr.try_read_raw()
    }
    
    #[inline(always)]
    /// Sequential blocking read from [`TokioReceiver`]
    /// 
    /// The asynchronous equivalent to this function is [`Subscriber::read`], 
    /// which must be used in an asynchronous context with `.await`
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// let (publisher, mut subscriber) = node.pubsub_blocking(House::Bedroom).unwrap();
    /// publisher.write("hello".to_string());
    /// assert_eq!(subscriber.read_blocking(), Some("hello".to_string()));
    /// ```
    pub fn read_blocking(&mut self) -> Option<D> {
        self.rcvr.read_blocking()
    }
    
    #[inline(always)]
    /// Asynchronous non-blocking read from [`TokioReceiver`]
    /// with a given timeout. After the timeout if there are no messages,
    /// returns [`None`].
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut node = crosstalk::BoundedNode::<House>::new(10);
    ///     let (publisher, mut subscriber) = node.pubsub(House::Bedroom).await.unwrap();
    ///     publisher.write("hello".to_string());
    ///     assert_eq!(subscriber.read_timeout(std::time::Duration::from_millis(100)).await, Some("hello".to_string()));
    /// }
    /// ```
    pub async fn read_timeout(&mut self, timeout: std::time::Duration) -> Option<D> {
        self.rcvr.read_timeout(timeout).await
    }
}
/// [`Subscriber`] implementation of [`Clone`]
impl<D: Clone, T: Clone> Clone for Subscriber<D, T> {
    #[inline(always)]
    /// Clones a [`Subscriber`]
    /// 
    /// # Examples
    /// 
    /// ```
    /// use crosstalk::AsTopic;
    /// 
    /// #[derive(AsTopic)]
    /// enum House {
    ///     Bedroom,
    ///     LivingRoom,
    ///     Kitchen,
    ///     Bathroom,
    /// }
    /// 
    /// crosstalk::init! {
    ///     House::Bedroom => String,
    ///     House::LivingRoom => String,
    ///     House::Kitchen => Vec<f32>,
    ///     House::Bathroom => u8,
    /// }
    /// 
    /// let mut node = crosstalk::BoundedNode::<House>::new(10);
    /// let (publisher, mut subscriber) = node.pubsub_blocking(House::Bedroom).unwrap();
    /// let mut subscriber_2 = subscriber.clone();
    /// publisher.write("hello".to_string());
    /// assert_eq!(subscriber.try_read().unwrap(), "hello");
    /// assert_eq!(subscriber_2.try_read().unwrap(), "hello");
    /// ```
    fn clone(&self) -> Self {
        Self {
            topic: self.topic.clone(),
            rcvr: Receiver::new(self.sndr.subscribe()),
            sndr: self.sndr.clone(),
        }
    }
}

/// Receiver
/// 
/// Define a receiver for subscribing messages
/// 
/// Reads from [`TokioReceiver`]
struct Receiver<D> {
    buf: TokioReceiver<D>,
}
/// [`Receiver`] implementation
impl<D: Clone> Receiver<D>{
    #[inline(always)]
    /// Constructs a new [`Receiver`]
    pub fn new(
        buf: TokioReceiver<D>,
    ) -> Self {
        Self { buf }
    }

    /// Reads from [`TokioReceiver`]
    /// 
    /// This struct/function is not meant to be used directly,
    /// rather through the [`Subscriber`] struct with [`Subscriber::read`]
    async fn read(&mut self) -> Option<D> {
        loop {
            match self.buf.recv().await {
                Ok(res) => return Some(res),
                Err(e) => match e {
                    tokio::sync::broadcast::error::RecvError::Lagged(_) => { continue; }

                    #[cfg(not(any(feature = "log", feature = "tracing")))]
                    _ => return None,

                    #[cfg(any(feature = "log", feature = "tracing"))]
                    _ => {
                        #[cfg(feature = "log")]
                        log::error!("{}", e);
                        #[cfg(feature = "tracing")]
                        tracing::error!("{}", e);
                        return None
                    }
                }
            }
        }
    }    

    /// Reads from [`TokioReceiver`]
    /// 
    /// This struct/function is not meant to be used directly,
    /// rather through the [`Subscriber`] struct with [`Subscriber::try_read`]
    fn try_read(&mut self) -> Option<D> {
        loop {
            match self.buf.try_recv() {
                Ok(d) => return Some(d),
                Err(e) => {
                    match e {
                        tokio::sync::broadcast::error::TryRecvError::Lagged(_) => { continue; },

                        #[cfg(not(any(feature = "log", feature = "tracing")))]
                        _ => return None,

                        #[cfg(any(feature = "log", feature = "tracing"))]
                        _ => {
                            #[cfg(feature = "log")]
                            log::error!("{}", e);
                            #[cfg(feature = "tracing")]
                            tracing::error!("{}", e);
                            return None
                        },
                    }
                },
            }
        } 
    }

    /// Reads from [`TokioReceiver`]
    /// 
    /// This struct/function is not meant to be used directly,
    /// rather through the [`Subscriber`] struct with [`Subscriber::try_read_raw`]
    fn try_read_raw(&mut self) -> Option<D> {
        match self.buf.try_recv() {
            Ok(d) => Some(d),

            #[cfg(not(any(feature = "log", feature = "tracing")))]
            Err(_) => None,
            
            #[cfg(any(feature = "log", feature = "tracing"))]
            Err(e) => {
                #[cfg(feature = "log")]
                log::error!("{}", e);
                #[cfg(feature = "tracing")]
                tracing::error!("{}", e);
                None
            },
        }
    }
    
    /// Reads from [`TokioReceiver`]
    /// 
    /// This struct/function is not meant to be used directly,
    /// rather through the [`Subscriber`] struct with [`Subscriber::read_blocking`]
    fn read_blocking(&mut self) -> Option<D> {
        loop {
            match self.buf.blocking_recv() {
                Ok(res) => return Some(res),
                Err(e) => match e {
                    tokio::sync::broadcast::error::RecvError::Lagged(_) => { continue; }
                    
                    #[cfg(not(any(feature = "log", feature = "tracing")))]
                    _ => return None,

                    #[cfg(any(feature = "log", feature = "tracing"))]
                    _ => {
                        #[cfg(feature = "log")]
                        log::error!("{}", e);
                        #[cfg(feature = "tracing")]
                        tracing::error!("{}", e);
                        return None
                    },
                }
            }
        }
    }
    
    /// Reads from [`TokioReceiver`]
    /// 
    /// This struct/function is not meant to be used directly,
    /// rather through the [`Subscriber`] struct with [`Subscriber::read_timeout`]
    async fn read_timeout(&mut self, timeout: std::time::Duration) -> Option<D> {
        match tokio::runtime::Handle::try_current() {
            Ok(_) => {
                match tokio::time::timeout(timeout, self.buf.recv()).await {
                    Ok(res) => {
                        match res {
                            Ok(res) => Some(res),

                            #[cfg(not(any(feature = "log", feature = "tracing")))]
                            Err(_) => None,
                            
                            #[cfg(any(feature = "log", feature = "tracing"))]
                            Err(e) => {
                                #[cfg(feature = "log")]
                                log::error!("{}", e);
                                #[cfg(feature = "tracing")]
                                tracing::error!("{}", e);
                                None
                            },
                        }
                    },

                    #[cfg(not(any(feature = "log", feature = "tracing")))]
                    Err(_) => None,
                    
                    #[cfg(any(feature = "log", feature = "tracing"))]
                    Err(e) => {
                        #[cfg(feature = "log")]
                        log::error!("{}", e);
                        #[cfg(feature = "tracing")]
                        tracing::error!("{}", e);
                        None
                    },
                }
            },

            #[cfg(not(any(feature = "log", feature = "tracing")))]
            Err(_) => None,
            
            #[cfg(any(feature = "log", feature = "tracing"))]
            Err(e) => {
                #[cfg(feature = "log")]
                log::error!("{}", e);
                #[cfg(feature = "tracing")]
                tracing::error!("{}", e);
                None
            },
        }
    }
}

// --------------------------------------------------
// for testing
// --------------------------------------------------
#[allow(unused_imports)]
use crosstalk_macros::init_test;
#[allow(unused_imports)]
use crosstalk_macros::AsTopicTest;

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(AsTopicTest)]
    enum TestTopic {
        A,
        B,
        C,
    }
    super::init_test! {
        TestTopic::A => String,
        TestTopic::B => bool,
        TestTopic::C => i32,
    }

    #[derive(AsTopicTest)]
    enum AnotherTestTopic {
        Foo,
        Bar,
    }
    super::init_test! {
        AnotherTestTopic::Foo => Vec<String>,
        AnotherTestTopic::Bar => Vec<bool>,
    }

    #[test]
    fn test_single_pubsub_blocking() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::A).unwrap();
        publisher.write("test".to_string());
        assert_eq!(subscriber.try_read().unwrap(), "test");
    }

    #[test]
    fn test_multiple_subscribers_blocking() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut sub1) = node.pubsub_blocking(TestTopic::A).unwrap();
        let mut sub2 = node.subscriber_blocking::<String>(TestTopic::A).unwrap();

        publisher.write("hello".to_string());
        assert_eq!(sub1.try_read().unwrap(), "hello");
        assert_eq!(sub2.try_read().unwrap(), "hello");
    }

    #[test]
    fn test_cross_topic_isolation() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (pub_a, mut sub_a) = node.pubsub_blocking(TestTopic::A).unwrap();
        let (pub_b, mut sub_b) = node.pubsub_blocking(TestTopic::B).unwrap();

        pub_a.write("string".to_string());
        pub_b.write(true);

        assert_eq!(sub_a.try_read().unwrap(), "string");
        assert!(sub_b.try_read().unwrap());
        assert!(sub_a.try_read().is_none());
        assert!(sub_b.try_read().is_none());
    }

    #[test]
    fn test_multiple_threads_blocking() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::A).unwrap();

        let handle = std::thread::spawn(move || {
            publisher.write("threaded".to_string());
        });

        handle.join().unwrap();
        assert_eq!(subscriber.try_read().unwrap(), "threaded");
    }

    #[tokio::test]
    async fn test_async_pubsub_single_runtime() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub(TestTopic::A).await.unwrap();
        publisher.write("async".to_string());
        assert_eq!(subscriber.read().await.unwrap(), "async");
    }

    #[test]
    fn test_high_volume_blocking() {
        let mut node = BoundedNode::<TestTopic>::new(100);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::C).unwrap();

        for i in 0..100 {
            publisher.write(i);
        }

        for i in 0..100 {
            assert_eq!(subscriber.try_read().unwrap(), i);
        }
        assert!(subscriber.try_read().is_none());
    }

    #[test]
    fn test_cloned_subscribers() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut sub1) = node.pubsub_blocking(TestTopic::A).unwrap();
        let mut sub2 = sub1.clone();

        publisher.write("clone".to_string());
        assert_eq!(sub1.try_read().unwrap(), "clone");
        assert_eq!(sub2.try_read().unwrap(), "clone");
    }

    #[test]
    fn test_buffer_overflow_handling() {
        let mut node = BoundedNode::<TestTopic>::new(2);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::A).unwrap();

        publisher.write("msg1".to_string());
        publisher.write("msg2".to_string());
        publisher.write("msg3".to_string());

        assert_eq!(subscriber.try_read().unwrap(), "msg2");
        assert_eq!(subscriber.try_read().unwrap(), "msg3");
        assert!(subscriber.try_read().is_none());
    }

    #[test]
    fn test_type_mismatch_errors() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        
        let publisher_res = node.publisher_blocking::<i32>(TestTopic::A);
        assert!(matches!(publisher_res, Err(Error::PublisherMismatch(_, _))));
        
        let subscriber_res = node.subscriber_blocking::<i32>(TestTopic::A);
        assert!(matches!(subscriber_res, Err(Error::SubscriberMismatch(_, _))));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_multiple_async_runtimes() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub(TestTopic::A).await.unwrap();

        let handle = tokio::spawn(async move {
            publisher.write("async".to_string());
        });

        handle.await.unwrap();
        assert_eq!(subscriber.read().await.unwrap(), "async");
    }

    #[test]
    fn test_mixed_async_blocking() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::A).unwrap();

        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            publisher.write("mixed".to_string());
        });

        assert_eq!(subscriber.try_read().unwrap(), "mixed");
    }

    #[test]
    fn test_complex_data_types() {
        let mut node = BoundedNode::<AnotherTestTopic>::new(10);
        let (pub_foo, mut sub_foo) = node.pubsub_blocking(AnotherTestTopic::Foo).unwrap();
        let (pub_bar, mut sub_bar) = node.pubsub_blocking(AnotherTestTopic::Bar).unwrap();

        pub_foo.write(vec!["a".to_string(), "b".to_string()]);
        pub_bar.write(vec![true, false]);

        assert_eq!(sub_foo.try_read().unwrap(), vec!["a", "b"]);
        assert_eq!(sub_bar.try_read().unwrap(), vec![true, false]);
    }

    #[test]
    fn test_concurrent_publishers() {
        let mut node = BoundedNode::<TestTopic>::new(100);
        let (pub1, mut sub) = node.pubsub_blocking(TestTopic::C).unwrap();
        let pub2 = node.publisher_blocking::<i32>(TestTopic::C).unwrap();

        let handle1 = std::thread::spawn(move || {
            for i in 0..50 {
                pub1.write(i);
            }
        });

        let handle2 = std::thread::spawn(move || {
            for i in 50..100 {
                pub2.write(i);
            }
        });

        handle1.join().unwrap();
        handle2.join().unwrap();

        let mut received = Vec::new();
        while let Some(msg) = sub.try_read() {
            received.push(msg);
        }
        assert_eq!(received.len(), 100);
    }

    #[tokio::test]
    async fn test_async_subscriber_cloning() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut sub1) = node.pubsub(TestTopic::A).await.unwrap();
        let mut sub2 = sub1.clone();

        publisher.write("async_clone".to_string());
        assert_eq!(sub1.read().await.unwrap(), "async_clone");
        assert_eq!(sub2.read().await.unwrap(), "async_clone");
    }

    #[test]
    fn test_dropped_publisher_behavior() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub_blocking::<String>(TestTopic::A).unwrap();
        drop(publisher);
        assert!(subscriber.try_read().is_none());
    }

    #[tokio::test]
    async fn test_multiple_async_publishers() {
        const LOOP_COUNT: usize = 10;
        const BUFFER_SIZE: usize = 10;
        let mut node = BoundedNode::<TestTopic>::new(BUFFER_SIZE);
        let (publisher, mut subscriber) = node.pubsub(TestTopic::A).await.unwrap();
        let publisher_1 = publisher.clone();
        let publisher_2 = publisher.clone();

        let task1 = tokio::spawn({
            async move {
                for _ in 0..LOOP_COUNT {
                    publisher_1.write("task1".to_string());
                }
            }
        });

        let task2 = tokio::spawn({
            async move {
                for _ in 0..LOOP_COUNT {
                    publisher_2.write("task2".to_string());
                }
            }
        });

        let _ = tokio::join!(task1, task2);

        let mut task1_count = 0;
        let mut task2_count = 0;
        for _ in 0..BUFFER_SIZE {
            let msg = subscriber.read().await.unwrap();
            if msg == "task1" { task1_count += 1; }
            if msg == "task2" { task2_count += 1; }
        }
        assert_eq!(task1_count + task2_count, BUFFER_SIZE);
    }

    #[test]
    fn test_blocking_read_with_delay() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::A).unwrap();

        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(500));
            publisher.write("delayed".to_string());
        });

        assert_eq!(subscriber.read_blocking().unwrap(), "delayed");
    }

    #[tokio::test]
    async fn test_read_timeout_behavior() {
        let mut node = BoundedNode::<TestTopic>::new(10);
        let (publisher, mut subscriber) = node.pubsub(TestTopic::A).await.unwrap();

        let timeout = std::time::Duration::from_millis(100);
        assert!(subscriber.read_timeout(timeout).await.is_none());

        publisher.write("timeout_test".to_string());
        assert_eq!(subscriber.read_timeout(timeout).await.unwrap(), "timeout_test");
    }

    #[test]
    fn test_multiple_topics_concurrently() {
        let mut node = BoundedNode::<AnotherTestTopic>::new(10);
        let (pub_foo, mut sub_foo) = node.pubsub_blocking(AnotherTestTopic::Foo).unwrap();
        let (pub_bar, mut sub_bar) = node.pubsub_blocking(AnotherTestTopic::Bar).unwrap();

        let handle1 = std::thread::spawn(move || {
            pub_foo.write(vec!["thread".to_string()]);
        });

        let handle2 = std::thread::spawn(move || {
            pub_bar.write(vec![true]);
        });

        handle1.join().unwrap();
        handle2.join().unwrap();

        assert_eq!(sub_foo.try_read().unwrap(), vec!["thread"]);
        assert_eq!(sub_bar.try_read().unwrap(), vec![true]);
    }

    #[test]
    #[should_panic]
    fn test_zero_capacity_node() {
        let _ = BoundedNode::<TestTopic>::new(0);
    }

    #[tokio::test]
    async fn test_async_unbounded_messaging() {
        let mut node = BoundedNode::<TestTopic>::new(1000);
        let (publisher, mut subscriber) = node.pubsub(TestTopic::A).await.unwrap();

        let messages = vec!["msg1", "msg2", "msg3", "msg4", "msg5"];
        for msg in &messages {
            publisher.write(msg.to_string());
        }

        for expected in messages {
            assert_eq!(subscriber.read().await.unwrap(), expected);
        }
    }

    #[test]
    fn test_error_handling_lagged_messages() {
        let mut node = BoundedNode::<TestTopic>::new(2);
        let (publisher, mut subscriber) = node.pubsub_blocking(TestTopic::A).unwrap();

        for i in 0..5 {
            publisher.write(format!("msg{}", i));
        }

        let mut received = Vec::new();
        while let Some(msg) = subscriber.try_read() {
            received.push(msg);
        }
        assert_eq!(received, vec!["msg3", "msg4"]);
    }
}