1use crate::session::events::{report, SessionEvent};
20
21use alloc::boxed::Box;
22use alloc::string::String;
23use alloc::vec::Vec;
24use core::future::Future;
25
26use super::{BoxFut, Connection, Dialer, Listener, PeerInfo, TransportError, TransportResult};
27
28pub type IoError = TransportError;
33
34pub trait ByteRead {
40 fn read<'a>(
42 &'a mut self,
43 buf: &'a mut [u8],
44 ) -> impl Future<Output = TransportResult<usize>> + Send + 'a;
45}
46
47pub trait ByteWrite {
49 fn write_all<'a>(
51 &'a mut self,
52 buf: &'a [u8],
53 ) -> impl Future<Output = TransportResult<()>> + Send + 'a;
54
55 fn flush(&mut self) -> impl Future<Output = TransportResult<()>> + Send + '_;
57}
58
59pub trait ByteStream {
76 fn read<'a>(
78 &'a mut self,
79 buf: &'a mut [u8],
80 ) -> impl Future<Output = TransportResult<usize>> + Send + 'a;
81
82 fn write_all<'a>(
84 &'a mut self,
85 buf: &'a [u8],
86 ) -> impl Future<Output = TransportResult<()>> + Send + 'a;
87
88 fn flush(&mut self) -> impl Future<Output = TransportResult<()>> + Send + '_;
90
91 fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_);
97}
98
99pub trait StreamDialer {
104 type Stream: ByteStream + Send;
106
107 fn connect<'a>(
110 &'a self,
111 host: &'a str,
112 port: u16,
113 ) -> impl Future<Output = TransportResult<Self::Stream>> + Send + 'a;
114}
115
116pub trait StreamListener {
124 type Stream: ByteStream + Send;
126
127 fn accept(
130 &mut self,
131 ) -> impl Future<Output = TransportResult<(Self::Stream, PeerInfo)>> + Send + '_;
132}
133
134pub trait Datagram {
140 fn send_to<'a>(
142 &'a mut self,
143 buf: &'a [u8],
144 to: core::net::SocketAddr,
145 ) -> impl Future<Output = TransportResult<()>> + Send + 'a;
146
147 fn recv_from<'a>(
149 &'a mut self,
150 buf: &'a mut [u8],
151 ) -> impl Future<Output = TransportResult<(usize, core::net::SocketAddr)>> + Send + 'a;
152
153 fn local_addr(&self) -> Option<core::net::SocketAddr>;
157}
158
159pub trait DatagramBinder {
166 type Socket: Datagram + Send;
168
169 fn bind(&self, port: u16) -> impl Future<Output = TransportResult<Self::Socket>> + Send + '_;
171}
172
173pub trait Delay {
187 fn sleep(&self, d: core::time::Duration) -> impl Future<Output = ()> + Send;
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201#[cfg_attr(feature = "defmt", derive(defmt::Format))]
202pub enum FrameFault {
203 Recoverable,
205 Fatal,
207}
208
209pub trait Framer {
211 fn encode(&self, frame: &[u8], out: &mut Vec<u8>) -> Result<(), FrameFault>;
216 fn push_bytes(&mut self, bytes: &[u8]);
218 fn next_frame(&mut self) -> Option<Result<Vec<u8>, FrameFault>>;
221}
222
223pub trait FramerFactory {
227 type Framer: Framer + Send;
229 fn framer(&self) -> Self::Framer;
231}
232
233impl<F, T> FramerFactory for F
234where
235 F: Fn() -> T,
236 T: Framer + Send,
237{
238 type Framer = T;
239 fn framer(&self) -> T {
240 self()
241 }
242}
243
244pub struct FramedConnection<S, F, const RC: usize = 256, const WC: usize = 256> {
254 stream: S,
255 framer: F,
256 peer: PeerInfo,
257}
258
259impl<S, F, const RC: usize, const WC: usize> FramedConnection<S, F, RC, WC> {
260 pub fn new(stream: S, framer: F) -> Self {
262 Self {
263 stream,
264 framer,
265 peer: PeerInfo::default(),
266 }
267 }
268
269 pub fn with_peer(stream: S, framer: F, peer: PeerInfo) -> Self {
271 Self {
272 stream,
273 framer,
274 peer,
275 }
276 }
277}
278
279impl<S, F, const RC: usize, const WC: usize> Connection for FramedConnection<S, F, RC, WC>
280where
281 S: ByteStream + Send,
282 F: Framer + Send,
283{
284 fn recv(&mut self) -> BoxFut<'_, TransportResult<Option<Vec<u8>>>> {
285 Box::pin(async move {
286 loop {
287 match self.framer.next_frame() {
288 Some(Ok(frame)) => return Ok(Some(frame)),
289 Some(Err(FrameFault::Recoverable)) => continue,
292 Some(Err(FrameFault::Fatal)) => {
295 report(SessionEvent::ReceiveFramingFailed);
296 return Err(TransportError::Framing);
297 }
298 None => {}
299 }
300 let mut chunk = [0u8; RC];
301 match self.stream.read(&mut chunk).await {
302 Ok(0) => return Ok(None), Ok(n) => self.framer.push_bytes(&chunk[..n]),
304 Err(e) => return Err(e),
305 }
306 }
307 })
308 }
309
310 fn send<'a>(&'a mut self, frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>> {
311 Box::pin(async move {
312 let mut out = Vec::new();
313 if let Err(_fault) = self.framer.encode(frame, &mut out) {
314 report(SessionEvent::SendFrameRejected {
315 bytes: frame.len(),
316 fault: _fault,
317 });
318 return Err(TransportError::Framing);
319 }
320 for chunk in out.chunks(WC) {
321 self.stream.write_all(chunk).await?;
322 }
323 self.stream.flush().await
324 })
325 }
326
327 fn peer(&self) -> &PeerInfo {
328 &self.peer
329 }
330}
331
332#[derive(Clone)]
337pub struct FramingDialer<D, FF, const RC: usize = 256, const WC: usize = 256> {
338 dialer: D,
339 framers: FF,
340 host: String,
341 port: u16,
342}
343
344impl<D, FF, const RC: usize, const WC: usize> FramingDialer<D, FF, RC, WC> {
345 pub fn new(dialer: D, framers: FF, host: impl Into<String>, port: u16) -> Self {
348 Self {
349 dialer,
350 framers,
351 host: host.into(),
352 port,
353 }
354 }
355}
356
357impl<D, FF, const RC: usize, const WC: usize> Dialer for FramingDialer<D, FF, RC, WC>
358where
359 D: StreamDialer + Send + Sync,
360 FF: FramerFactory + Send + Sync,
361 D::Stream: 'static,
362 FF::Framer: 'static,
363{
364 fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
365 Box::pin(async move {
366 let stream = self.dialer.connect(&self.host, self.port).await?;
367 let conn: FramedConnection<D::Stream, FF::Framer, RC, WC> =
368 FramedConnection::new(stream, self.framers.framer());
369 Ok(Box::new(conn) as Box<dyn Connection>)
370 })
371 }
372}
373
374pub struct FramingListener<L, FF, const RC: usize = 256, const WC: usize = 256> {
377 listener: L,
378 framers: FF,
379}
380
381impl<L, FF, const RC: usize, const WC: usize> FramingListener<L, FF, RC, WC> {
382 pub fn new(listener: L, framers: FF) -> Self {
385 Self { listener, framers }
386 }
387}
388
389impl<L, FF, const RC: usize, const WC: usize> Listener for FramingListener<L, FF, RC, WC>
390where
391 L: StreamListener + Send,
392 FF: FramerFactory + Send,
393 L::Stream: 'static,
394 FF::Framer: 'static,
395{
396 fn accept(&mut self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
397 Box::pin(async move {
398 let (stream, peer) = self.listener.accept().await?;
399 let conn: FramedConnection<L::Stream, FF::Framer, RC, WC> =
400 FramedConnection::with_peer(stream, self.framers.framer(), peer);
401 Ok(Box::new(conn) as Box<dyn Connection>)
402 })
403 }
404}
405
406pub struct OneShot<T> {
421 inner: spin::Mutex<Option<T>>,
422}
423
424impl<T> OneShot<T> {
425 pub fn new(value: T) -> Self {
427 Self {
428 inner: spin::Mutex::new(Some(value)),
429 }
430 }
431
432 pub fn take(&self) -> Option<T> {
434 self.inner.lock().take()
435 }
436}
437
438impl<T> Default for OneShot<T> {
439 fn default() -> Self {
441 Self {
442 inner: spin::Mutex::new(None),
443 }
444 }
445}
446
447impl<T> From<T> for OneShot<T> {
448 fn from(value: T) -> Self {
449 Self::new(value)
450 }
451}
452
453pub struct OneShotDialer<C> {
460 conn: OneShot<C>,
461}
462
463impl<C> OneShotDialer<C> {
464 pub fn new(conn: C) -> Self {
466 Self {
467 conn: OneShot::new(conn),
468 }
469 }
470}
471
472impl<C: Connection + 'static> Dialer for OneShotDialer<C> {
473 fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
474 Box::pin(async move {
475 self.conn
476 .take()
477 .map(|c| Box::new(c) as Box<dyn Connection>)
478 .ok_or(TransportError::Closed)
479 })
480 }
481}
482
483pub struct OneShotListener<C> {
489 conn: OneShot<C>,
490}
491
492impl<C> OneShotListener<C> {
493 pub fn new(conn: C) -> Self {
495 Self {
496 conn: OneShot::new(conn),
497 }
498 }
499}
500
501impl<C: Connection + 'static> Listener for OneShotListener<C> {
502 fn accept(&mut self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
503 Box::pin(async move {
504 match self.conn.take() {
505 Some(c) => Ok(Box::new(c) as Box<dyn Connection>),
506 None => core::future::pending().await,
507 }
508 })
509 }
510}
511
512#[allow(dead_code)]
520fn _generic_code_over_the_traits_is_send<D, L, B, T>(
521 dialer: D,
522 mut listener: L,
523 binder: B,
524 delay: T,
525) -> BoxFut<'static, ()>
526where
527 D: StreamDialer + Send + 'static,
528 L: StreamListener + Send + 'static,
529 B: DatagramBinder + Send + 'static,
530 T: Delay + Send + 'static,
531{
532 Box::pin(async move {
533 let mut buf = [0u8; 16];
534
535 if let Ok(mut stream) = dialer.connect("example.test", 1883).await {
536 let _ = stream.read(&mut buf).await;
537 let _ = stream.write_all(&buf).await;
538 let _ = stream.flush().await;
539 }
540 if let Ok((mut stream, _peer)) = listener.accept().await {
541 let _ = stream.read(&mut buf).await;
542 }
543 if let Ok(mut socket) = binder.bind(0).await {
544 let _ = socket.recv_from(&mut buf).await;
545 let _ = socket.local_addr();
546 }
547 delay.sleep(core::time::Duration::from_millis(1)).await;
548 })
549}
550
551#[allow(dead_code)]
553fn _one_shot_is_send_sync_without_unsafe() {
554 fn assert_send_sync<T: Send + Sync>() {}
555 assert_send_sync::<OneShot<Vec<u8>>>();
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561 use alloc::sync::Arc;
562 use alloc::vec;
563
564 #[derive(Default)]
571 struct LenFramer {
572 buf: Vec<u8>,
573 }
574
575 impl Framer for LenFramer {
576 fn encode(&self, frame: &[u8], out: &mut Vec<u8>) -> Result<(), FrameFault> {
577 if frame.len() >= 0xFE {
578 return Err(FrameFault::Recoverable);
579 }
580 out.push(frame.len() as u8);
581 out.extend_from_slice(frame);
582 Ok(())
583 }
584 fn push_bytes(&mut self, bytes: &[u8]) {
585 self.buf.extend_from_slice(bytes);
586 }
587 fn next_frame(&mut self) -> Option<Result<Vec<u8>, FrameFault>> {
588 let len = *self.buf.first()? as usize;
589 if len == 0xFF {
590 self.buf.remove(0);
591 return Some(Err(FrameFault::Recoverable));
592 }
593 if len == 0xFE {
594 self.buf.clear();
595 return Some(Err(FrameFault::Fatal));
596 }
597 if self.buf.len() < len + 1 {
598 return None;
599 }
600 let frame = self.buf[1..len + 1].to_vec();
601 self.buf.drain(..len + 1);
602 Some(Ok(frame))
603 }
604 }
605
606 #[derive(Default)]
609 struct StreamState {
610 reads: Vec<Vec<u8>>,
612 written: Vec<u8>,
614 write_sizes: Vec<usize>,
616 flushes: usize,
617 }
618
619 #[derive(Clone, Default)]
620 struct MockStream(Arc<spin::Mutex<StreamState>>);
621
622 impl MockStream {
623 fn with_reads(reads: Vec<Vec<u8>>) -> Self {
624 Self(Arc::new(spin::Mutex::new(StreamState {
625 reads,
626 ..Default::default()
627 })))
628 }
629 }
630
631 impl ByteStream for MockStream {
635 async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
636 let mut st = self.0.lock();
637 if st.reads.is_empty() {
638 return Ok(0);
639 }
640 let chunk = st.reads.remove(0);
641 let n = chunk.len().min(buf.len());
642 buf[..n].copy_from_slice(&chunk[..n]);
643 Ok(n)
644 }
645
646 async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
647 let mut st = self.0.lock();
648 st.written.extend_from_slice(buf);
649 st.write_sizes.push(buf.len());
650 Ok(())
651 }
652
653 async fn flush(&mut self) -> TransportResult<()> {
654 self.0.lock().flushes += 1;
655 Ok(())
656 }
657
658 fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_) {
659 (MockHalf(self.clone()), MockHalf(self.clone()))
660 }
661 }
662
663 struct MockHalf(MockStream);
666
667 impl ByteRead for MockHalf {
668 async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
669 ByteStream::read(&mut self.0, buf).await
670 }
671 }
672
673 impl ByteWrite for MockHalf {
674 async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
675 ByteStream::write_all(&mut self.0, buf).await
676 }
677
678 async fn flush(&mut self) -> TransportResult<()> {
679 ByteStream::flush(&mut self.0).await
680 }
681 }
682
683 struct FailingStream;
686
687 impl ByteStream for FailingStream {
688 async fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> TransportResult<usize> {
689 Err(TransportError::Closed)
690 }
691 async fn write_all<'a>(&'a mut self, _buf: &'a [u8]) -> TransportResult<()> {
692 Err(TransportError::Closed)
693 }
694 async fn flush(&mut self) -> TransportResult<()> {
695 Ok(())
696 }
697 fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_) {
698 (FailingHalf, FailingHalf)
699 }
700 }
701
702 struct FailingHalf;
704
705 impl ByteRead for FailingHalf {
706 async fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> TransportResult<usize> {
707 Err(TransportError::Closed)
708 }
709 }
710
711 impl ByteWrite for FailingHalf {
712 async fn write_all<'a>(&'a mut self, _buf: &'a [u8]) -> TransportResult<()> {
713 Err(TransportError::Closed)
714 }
715
716 async fn flush(&mut self) -> TransportResult<()> {
717 Ok(())
718 }
719 }
720
721 #[derive(Clone, Default)]
724 struct DuplexMock {
725 written: Arc<spin::Mutex<Vec<u8>>>,
726 wrote: Arc<tokio::sync::Notify>,
727 }
728
729 impl ByteStream for DuplexMock {
730 async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
731 self.wrote.notified().await;
732 let written = self.written.lock();
733 let n = written.len().min(buf.len());
734 buf[..n].copy_from_slice(&written[..n]);
735 Ok(n)
736 }
737
738 async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
739 self.written.lock().extend_from_slice(buf);
740 self.wrote.notify_one();
741 Ok(())
742 }
743
744 async fn flush(&mut self) -> TransportResult<()> {
745 Ok(())
746 }
747
748 fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_) {
749 (DuplexHalf(self.clone()), DuplexHalf(self.clone()))
750 }
751 }
752
753 struct DuplexHalf(DuplexMock);
755
756 impl ByteRead for DuplexHalf {
757 async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
758 ByteStream::read(&mut self.0, buf).await
759 }
760 }
761
762 impl ByteWrite for DuplexHalf {
763 async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
764 ByteStream::write_all(&mut self.0, buf).await
765 }
766
767 async fn flush(&mut self) -> TransportResult<()> {
768 ByteStream::flush(&mut self.0).await
769 }
770 }
771
772 struct MockDialer(MockStream);
773
774 impl StreamDialer for MockDialer {
775 type Stream = MockStream;
776 async fn connect<'a>(&'a self, _host: &'a str, _port: u16) -> TransportResult<MockStream> {
777 Ok(self.0.clone())
778 }
779 }
780
781 struct MockListener(Option<MockStream>);
782
783 impl StreamListener for MockListener {
784 type Stream = MockStream;
785 async fn accept(&mut self) -> TransportResult<(MockStream, PeerInfo)> {
786 let s = self.0.take().ok_or(TransportError::Closed)?;
787 let peer = PeerInfo {
788 peer_addr: Some("10.0.0.1:5555".into()),
789 ..Default::default()
790 };
791 Ok((s, peer))
792 }
793 }
794
795 fn framed(stream: MockStream) -> FramedConnection<MockStream, LenFramer, 256, 256> {
796 FramedConnection::new(stream, LenFramer::default())
797 }
798
799 #[tokio::test]
802 async fn recv_yields_each_frame_then_eof() {
803 let mut conn = framed(MockStream::with_reads(vec![vec![
804 2, b'h', b'i', 3, b'y', b'e', b's',
805 ]]));
806 assert_eq!(conn.recv().await.unwrap(), Some(b"hi".to_vec()));
807 assert_eq!(conn.recv().await.unwrap(), Some(b"yes".to_vec()));
808 assert_eq!(conn.recv().await.unwrap(), None, "closed peer is Ok(None)");
809 }
810
811 #[tokio::test]
812 async fn recv_reassembles_a_frame_split_across_reads() {
813 let mut conn = framed(MockStream::with_reads(vec![
814 vec![3, b'a'],
815 vec![b'b'],
816 vec![b'c'],
817 ]));
818 assert_eq!(conn.recv().await.unwrap(), Some(b"abc".to_vec()));
819 }
820
821 #[tokio::test]
822 async fn recv_skips_a_corrupt_run_and_resyncs() {
823 let mut conn = framed(MockStream::with_reads(vec![vec![
824 0xFF, 0xFF, 2, b'o', b'k',
825 ]]));
826 assert_eq!(
827 conn.recv().await.unwrap(),
828 Some(b"ok".to_vec()),
829 "a run that fails to decode is skipped, not fatal"
830 );
831 }
832
833 #[tokio::test]
834 async fn recv_closes_on_an_unrecoverable_framing_error() {
835 let mut conn = framed(MockStream::with_reads(vec![vec![0xFE, 2, b'o', b'k']]));
838 #[cfg(feature = "std")]
839 let received = Arc::new(core::sync::atomic::AtomicBool::new(false));
840 #[cfg(feature = "std")]
841 let result = crate::session::events::capture::future(
842 {
843 let received = received.clone();
844 Arc::new(move |event| {
845 assert!(matches!(event, SessionEvent::ReceiveFramingFailed));
846 received.store(true, core::sync::atomic::Ordering::Relaxed);
847 })
848 },
849 conn.recv(),
850 )
851 .await;
852 #[cfg(not(feature = "std"))]
853 let result = conn.recv().await;
854 #[cfg(feature = "std")]
855 assert!(received.load(core::sync::atomic::Ordering::Relaxed));
856 assert_eq!(
857 result,
858 Err(TransportError::Framing),
859 "a fatal fault ends the connection, it is not skipped"
860 );
861 }
862
863 #[tokio::test]
864 async fn send_reports_a_frame_the_framer_rejects() {
865 let stream = MockStream::default();
866 let mut conn = framed(stream.clone());
867 let oversized = vec![b'x'; 0xFE];
868
869 #[cfg(feature = "std")]
870 let received = Arc::new(core::sync::atomic::AtomicBool::new(false));
871 #[cfg(feature = "std")]
872 let result = crate::session::events::capture::future(
873 {
874 let received = received.clone();
875 Arc::new(move |event| {
876 assert!(matches!(
877 event,
878 SessionEvent::SendFrameRejected {
879 bytes: 0xFE,
880 fault: FrameFault::Recoverable
881 }
882 ));
883 received.store(true, core::sync::atomic::Ordering::Relaxed);
884 })
885 },
886 conn.send(&oversized),
887 )
888 .await;
889 #[cfg(not(feature = "std"))]
890 let result = conn.send(&oversized).await;
891 #[cfg(feature = "std")]
892 assert!(received.load(core::sync::atomic::Ordering::Relaxed));
893 assert_eq!(
894 result,
895 Err(TransportError::Framing),
896 "a dropped frame is an error, never a silent Ok"
897 );
898 let st = stream.0.lock();
899 assert!(
900 st.written.is_empty(),
901 "nothing half-encoded reaches the wire"
902 );
903 assert_eq!(st.flushes, 0);
904 }
905
906 #[tokio::test]
907 async fn recv_propagates_the_streams_own_error() {
908 let mut conn = FramedConnection::<_, _, 256, 256>::new(FailingStream, LenFramer::default());
909 assert_eq!(
910 conn.recv().await,
911 Err(TransportError::Closed),
912 "the stream classifies the failure; framing must not flatten it"
913 );
914 }
915
916 #[tokio::test]
917 async fn send_encodes_then_flushes() {
918 let stream = MockStream::default();
919 let mut conn = framed(stream.clone());
920 conn.send(b"hi").await.unwrap();
921
922 let st = stream.0.lock();
923 assert_eq!(st.written, vec![2, b'h', b'i']);
924 assert_eq!(st.flushes, 1);
925 }
926
927 #[tokio::test]
928 async fn send_splits_a_frame_larger_than_the_write_chunk() {
929 let stream = MockStream::default();
930 let mut conn: FramedConnection<MockStream, LenFramer, 256, 4> =
931 FramedConnection::new(stream.clone(), LenFramer::default());
932 conn.send(b"0123456789").await.unwrap();
933
934 let st = stream.0.lock();
935 assert_eq!(st.write_sizes, vec![4, 4, 3], "11 encoded bytes at WC = 4");
936 assert_eq!(st.written.len(), 11);
937 }
938
939 #[tokio::test]
942 async fn framing_dialer_produces_a_working_connection() {
943 let stream = MockStream::with_reads(vec![vec![2, b'h', b'i']]);
944 let dialer: FramingDialer<_, _, 256, 256> =
945 FramingDialer::new(MockDialer(stream), LenFramer::default, "host.test", 1883);
946
947 let mut conn = dialer.connect().await.unwrap();
948 assert_eq!(conn.recv().await.unwrap(), Some(b"hi".to_vec()));
949 }
950
951 #[tokio::test]
952 async fn framing_listener_carries_peer_metadata_through() {
953 let stream = MockStream::with_reads(vec![vec![2, b'h', b'i']]);
954 let mut listener: FramingListener<_, _, 256, 256> =
955 FramingListener::new(MockListener(Some(stream)), LenFramer::default);
956
957 let mut conn = listener.accept().await.unwrap();
958 assert_eq!(conn.peer().peer_addr.as_deref(), Some("10.0.0.1:5555"));
959 assert_eq!(conn.recv().await.unwrap(), Some(b"hi".to_vec()));
960 }
961
962 #[test]
963 fn a_framed_connection_is_boxable_as_dyn_connection() {
964 let conn = framed(MockStream::default());
965 let _boxed: Box<dyn Connection> = Box::new(conn);
966 }
967
968 #[tokio::test]
971 async fn split_halves_run_concurrently() {
972 let mut stream = DuplexMock::default();
973 let (mut rx, mut tx) = stream.split();
974
975 let mut buf = [0u8; 4];
978 let (read, write) = tokio::join!(rx.read(&mut buf), tx.write_all(b"ping"));
979
980 write.expect("write half");
981 assert_eq!(read.expect("read half"), 4);
982 assert_eq!(&buf, b"ping");
983 }
984
985 #[tokio::test]
986 async fn split_halves_address_the_same_stream() {
987 let stream = MockStream::with_reads(vec![b"hi".to_vec()]);
988 let mut split_me = stream.clone();
989 let (mut rx, mut tx) = split_me.split();
990
991 tx.write_all(b"out").await.expect("write half");
992 let mut buf = [0u8; 8];
993 let n = rx.read(&mut buf).await.expect("read half");
994
995 assert_eq!(&buf[..n], b"hi", "the read half drains the stream's reads");
996 assert_eq!(
997 stream.0.lock().written,
998 b"out",
999 "the write half reaches the stream the halves came from"
1000 );
1001 }
1002
1003 #[test]
1006 fn one_shot_yields_its_value_once() {
1007 let cell = OneShot::new(7u32);
1008 assert_eq!(cell.take(), Some(7));
1009 assert_eq!(cell.take(), None, "a second take must not get the resource");
1010 }
1011
1012 #[test]
1013 fn default_one_shot_is_empty() {
1014 assert_eq!(OneShot::<u32>::default().take(), None);
1015 }
1016
1017 #[test]
1018 fn framer_factory_is_implemented_for_closures() {
1019 struct Noop;
1020 impl Framer for Noop {
1021 fn encode(&self, _frame: &[u8], _out: &mut Vec<u8>) -> Result<(), FrameFault> {
1022 Ok(())
1023 }
1024 fn push_bytes(&mut self, _bytes: &[u8]) {}
1025 fn next_frame(&mut self) -> Option<Result<Vec<u8>, FrameFault>> {
1026 None
1027 }
1028 }
1029
1030 fn takes_factory<FF: FramerFactory>(ff: FF) -> FF::Framer {
1031 ff.framer()
1032 }
1033 let _framer = takes_factory(|| Noop);
1034 }
1035}