1use fidl::endpoints::{ClientEnd, Proxy};
6use fidl_fuchsia_bluetooth as fidl_bt;
7use fidl_fuchsia_bluetooth_bredr as bredr;
8use fuchsia_async as fasync;
9use fuchsia_sync::Mutex;
10use futures::sink::Sink;
11use futures::stream::{FusedStream, Stream};
12use futures::{Future, TryFutureExt, ready};
13use log::{error, warn};
14use std::collections::VecDeque;
15use std::fmt;
16use std::pin::Pin;
17use std::sync::Arc;
18use std::task::{Context, Poll};
19
20use crate::error::Error;
21
22#[derive(PartialEq, Debug, Clone)]
24pub enum ChannelMode {
25 Basic,
26 EnhancedRetransmissionMode,
27 LeCreditBasedFlowControl,
28 EnhancedCreditBasedFlowControl,
29}
30
31impl fmt::Display for ChannelMode {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 match self {
34 ChannelMode::Basic => write!(f, "Basic"),
35 ChannelMode::EnhancedRetransmissionMode => write!(f, "ERTM"),
36 ChannelMode::LeCreditBasedFlowControl => write!(f, "LE_Credit"),
37 ChannelMode::EnhancedCreditBasedFlowControl => write!(f, "Credit"),
38 }
39 }
40}
41
42pub enum A2dpDirection {
43 Normal,
44 Source,
45 Sink,
46}
47
48impl From<A2dpDirection> for bredr::A2dpDirectionPriority {
49 fn from(pri: A2dpDirection) -> Self {
50 match pri {
51 A2dpDirection::Normal => bredr::A2dpDirectionPriority::Normal,
52 A2dpDirection::Source => bredr::A2dpDirectionPriority::Source,
53 A2dpDirection::Sink => bredr::A2dpDirectionPriority::Sink,
54 }
55 }
56}
57
58impl TryFrom<fidl_bt::ChannelMode> for ChannelMode {
59 type Error = Error;
60 fn try_from(fidl: fidl_bt::ChannelMode) -> Result<Self, Error> {
61 match fidl {
62 fidl_bt::ChannelMode::Basic => Ok(ChannelMode::Basic),
63 fidl_bt::ChannelMode::EnhancedRetransmission => {
64 Ok(ChannelMode::EnhancedRetransmissionMode)
65 }
66 fidl_bt::ChannelMode::LeCreditBasedFlowControl => {
67 Ok(ChannelMode::LeCreditBasedFlowControl)
68 }
69 fidl_bt::ChannelMode::EnhancedCreditBasedFlowControl => {
70 Ok(ChannelMode::EnhancedCreditBasedFlowControl)
71 }
72 x => Err(Error::FailedConversion(format!("Unsupported channel mode type: {x:?}"))),
73 }
74 }
75}
76
77impl From<ChannelMode> for fidl_bt::ChannelMode {
78 fn from(x: ChannelMode) -> Self {
79 match x {
80 ChannelMode::Basic => fidl_bt::ChannelMode::Basic,
81 ChannelMode::EnhancedRetransmissionMode => fidl_bt::ChannelMode::EnhancedRetransmission,
82 ChannelMode::LeCreditBasedFlowControl => fidl_bt::ChannelMode::LeCreditBasedFlowControl,
83 ChannelMode::EnhancedCreditBasedFlowControl => {
84 fidl_bt::ChannelMode::EnhancedCreditBasedFlowControl
85 }
86 }
87 }
88}
89
90#[derive(Debug)]
95pub struct Channel {
96 socket: fasync::Socket,
97 mode: ChannelMode,
98 max_tx_size: usize,
99 flush_timeout: Arc<Mutex<Option<zx::MonotonicDuration>>>,
100 audio_direction_ext: Option<bredr::AudioDirectionExtProxy>,
101 l2cap_parameters_ext: Option<bredr::L2capParametersExtProxy>,
102 audio_offload_ext: Option<bredr::AudioOffloadExtProxy>,
103 terminated: bool,
104 send_buffer: VecDeque<Vec<u8>>,
105}
106
107impl Channel {
108 const MAX_QUEUED_PACKETS: usize = 32;
109 pub fn from_socket(socket: zx::Socket, max_tx_size: usize) -> Result<Self, zx::Status> {
112 Ok(Self::from_socket_infallible(socket, max_tx_size))
113 }
114
115 pub fn from_socket_infallible(socket: zx::Socket, max_tx_size: usize) -> Self {
117 Channel {
118 socket: fasync::Socket::from_socket(socket),
119 mode: ChannelMode::Basic,
120 max_tx_size,
121 flush_timeout: Arc::new(Mutex::new(None)),
122 audio_direction_ext: None,
123 l2cap_parameters_ext: None,
124 audio_offload_ext: None,
125 terminated: false,
126 send_buffer: VecDeque::with_capacity(Self::MAX_QUEUED_PACKETS),
127 }
128 }
129
130 pub const DEFAULT_MAX_TX: usize = 672;
133
134 pub fn create() -> (Self, Self) {
137 Self::create_with_max_tx(Self::DEFAULT_MAX_TX)
138 }
139
140 pub fn create_with_max_tx(max_tx_size: usize) -> (Self, Self) {
143 let (remote, local) = zx::Socket::create_datagram();
144 (
145 Channel::from_socket(remote, max_tx_size).unwrap(),
146 Channel::from_socket(local, max_tx_size).unwrap(),
147 )
148 }
149
150 pub fn max_tx_size(&self) -> usize {
153 self.max_tx_size
154 }
155
156 pub fn channel_mode(&self) -> &ChannelMode {
157 &self.mode
158 }
159
160 pub fn flush_timeout(&self) -> Option<zx::MonotonicDuration> {
161 self.flush_timeout.lock().clone()
162 }
163
164 pub fn set_audio_priority(
167 &self,
168 dir: A2dpDirection,
169 ) -> impl Future<Output = Result<(), Error>> + use<> {
170 let proxy = self.audio_direction_ext.clone();
171 async move {
172 match proxy {
173 None => return Err(Error::profile("audio priority not supported")),
174 Some(proxy) => proxy
175 .set_priority(dir.into())
176 .await?
177 .map_err(|e| Error::profile(format!("setting priority failed: {e:?}"))),
178 }
179 }
180 }
181
182 pub fn set_flush_timeout(
189 &self,
190 duration: Option<zx::MonotonicDuration>,
191 ) -> impl Future<Output = Result<Option<zx::MonotonicDuration>, Error>> + use<> {
192 let flush_timeout = self.flush_timeout.clone();
193 let current = self.flush_timeout.lock().clone();
194 let proxy = self.l2cap_parameters_ext.clone();
195 async move {
196 match (current, duration) {
197 (None, None) => return Ok(None),
198 (Some(old), Some(new)) if (old - new).into_millis().abs() < 2 => {
199 return Ok(current);
200 }
201 _ => {}
202 };
203 let proxy =
204 proxy.ok_or_else(|| Error::profile("l2cap parameter changing not supported"))?;
205 let parameters = fidl_bt::ChannelParameters {
206 flush_timeout: duration.clone().map(zx::MonotonicDuration::into_nanos),
207 ..Default::default()
208 };
209 let new_params = proxy.request_parameters(¶meters).await?;
210 let new_timeout = new_params.flush_timeout.map(zx::MonotonicDuration::from_nanos);
211 *(flush_timeout.lock()) = new_timeout.clone();
212 Ok(new_timeout)
213 }
214 }
215
216 pub fn audio_offload(&self) -> Option<bredr::AudioOffloadExtProxy> {
218 self.audio_offload_ext.clone()
219 }
220
221 pub fn closed<'a>(&'a self) -> impl Future<Output = Result<(), zx::Status>> + 'a {
222 let close_signals = zx::Signals::SOCKET_PEER_CLOSED;
223 let close_wait = fasync::OnSignals::new(&self.socket, close_signals);
224 close_wait.map_ok(|_o| ())
225 }
226
227 pub fn is_closed<'a>(&'a self) -> bool {
228 self.socket.is_closed()
229 }
230
231 pub fn write(&self, bytes: &[u8]) -> Result<usize, zx::Status> {
236 self.socket.as_ref().write(bytes)
237 }
238}
239
240impl TryFrom<fidl_fuchsia_bluetooth_bredr::Channel> for Channel {
241 type Error = zx::Status;
242
243 fn try_from(fidl: bredr::Channel) -> Result<Self, Self::Error> {
244 let channel = match fidl.channel_mode.unwrap_or(fidl_bt::ChannelMode::Basic).try_into() {
245 Err(e) => {
246 warn!("Unsupported channel mode type: {e:?}");
247 return Err(zx::Status::INTERNAL);
248 }
249 Ok(c) => c,
250 };
251
252 Ok(Self {
253 socket: fasync::Socket::from_socket(fidl.socket.ok_or(zx::Status::INVALID_ARGS)?),
254 mode: channel,
255 max_tx_size: fidl.max_tx_sdu_size.ok_or(zx::Status::INVALID_ARGS)? as usize,
256 flush_timeout: Arc::new(Mutex::new(
257 fidl.flush_timeout.map(zx::MonotonicDuration::from_nanos),
258 )),
259 audio_direction_ext: fidl.ext_direction.map(|e| e.into_proxy()),
260 l2cap_parameters_ext: fidl.ext_l2cap.map(|e| e.into_proxy()),
261 audio_offload_ext: fidl.ext_audio_offload.map(|c| c.into_proxy()),
262 terminated: false,
263 send_buffer: VecDeque::with_capacity(Self::MAX_QUEUED_PACKETS),
264 })
265 }
266}
267
268impl TryFrom<Channel> for bredr::Channel {
269 type Error = Error;
270
271 fn try_from(channel: Channel) -> Result<Self, Self::Error> {
272 let socket = channel.socket.into_zx_socket();
273 let ext_direction = channel
274 .audio_direction_ext
275 .map(|proxy| {
276 let chan = proxy.into_channel()?;
277 Ok(ClientEnd::new(chan.into()))
278 })
279 .transpose()
280 .map_err(|_: bredr::AudioDirectionExtProxy| {
281 Error::profile("AudioDirection proxy in use")
282 })?;
283 let ext_l2cap = channel
284 .l2cap_parameters_ext
285 .map(|proxy| {
286 let chan = proxy.into_channel()?;
287 Ok(ClientEnd::new(chan.into()))
288 })
289 .transpose()
290 .map_err(|_: bredr::L2capParametersExtProxy| {
291 Error::profile("l2cap parameters proxy in use")
292 })?;
293 let ext_audio_offload = channel
294 .audio_offload_ext
295 .map(|proxy| {
296 let chan = proxy.into_channel()?;
297 Ok(ClientEnd::new(chan.into()))
298 })
299 .transpose()
300 .map_err(|_: bredr::AudioOffloadExtProxy| {
301 Error::profile("audio offload proxy in use")
302 })?;
303 let flush_timeout = channel.flush_timeout.lock().map(zx::MonotonicDuration::into_nanos);
304 Ok(bredr::Channel {
305 socket: Some(socket),
306 channel_mode: Some(channel.mode.into()),
307 max_tx_sdu_size: Some(channel.max_tx_size as u16),
308 ext_direction,
309 flush_timeout,
310 ext_l2cap,
311 ext_audio_offload,
312 ..Default::default()
313 })
314 }
315}
316
317impl Stream for Channel {
318 type Item = Result<Vec<u8>, zx::Status>;
319
320 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
321 if self.terminated {
322 panic!("Channel polled after terminated");
323 }
324
325 let mut res = Vec::<u8>::new();
326 loop {
327 break match self.socket.poll_datagram(cx, &mut res) {
328 Poll::Ready(Ok(0)) => continue,
331 Poll::Ready(Ok(_size)) => Poll::Ready(Some(Ok(res))),
332 Poll::Ready(Err(zx::Status::PEER_CLOSED)) => {
333 self.terminated = true;
334 Poll::Ready(None)
335 }
336 Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))),
337 Poll::Pending => Poll::Pending,
338 };
339 }
340 }
341}
342
343impl FusedStream for Channel {
344 fn is_terminated(&self) -> bool {
345 self.terminated
346 }
347}
348
349impl Sink<Vec<u8>> for Channel {
352 type Error = zx::Status;
353
354 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
355 let _ = Sink::poll_flush(self.as_mut(), cx)?;
357
358 if self.send_buffer.len() >= Channel::MAX_QUEUED_PACKETS {
359 return Poll::Pending;
360 }
361 Poll::Ready(Ok(()))
362 }
363
364 fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> {
365 self.get_mut().send_buffer.push_back(item);
366 Ok(())
367 }
368
369 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
370 let this = self.get_mut();
371 use futures::io::AsyncWrite;
372 while let Some(item) = this.send_buffer.front() {
373 let res = Pin::new(&mut this.socket).poll_write(cx, item).map_err(zx::Status::from);
374 match res {
375 Poll::Ready(Ok(size)) => {
376 if size == item.len() {
377 let _ = this.send_buffer.pop_front();
378 } else {
379 error!(
380 "Partial write in Channel::Sink::poll_flush: wrote {} bytes of {} byte packet.",
381 size,
382 item.len()
383 );
384 let item = this.send_buffer.front_mut().unwrap();
385 *item = item.split_off(size);
386 }
387 }
388 Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
389 Poll::Pending => return Poll::Pending,
390 }
391 }
392 Pin::new(&mut this.socket).poll_flush(cx).map_err(zx::Status::from)
393 }
394
395 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
396 ready!(Sink::poll_flush(self.as_mut(), cx))?;
397 let this = self.get_mut();
398 use futures::io::AsyncWrite as _;
399 Pin::new(&mut this.socket).poll_close(cx).map_err(zx::Status::from)
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use fidl::endpoints::create_request_stream;
407 use futures::{SinkExt, StreamExt};
408 use std::pin::pin;
409
410 #[test]
411 fn test_channel_create_and_write() {
412 let mut exec = fasync::TestExecutor::new();
413 let (mut recv, mut send) = Channel::create();
414
415 let heart: &[u8] = &[0xF0, 0x9F, 0x92, 0x96];
416 let mut send_fut = send.send(heart.to_vec());
417 assert!(exec.run_until_stalled(&mut send_fut).is_ready());
418
419 let mut recv_fut = recv.next();
420 match exec.run_until_stalled(&mut recv_fut) {
421 Poll::Ready(Some(Ok(bytes))) => {
422 assert_eq!(heart, &bytes);
423 }
424 x => panic!("Expected Some(Ok(bytes)) from the stream, got {x:?}"),
425 };
426 }
427
428 #[test]
429 fn test_channel_from_fidl() {
430 let _exec = fasync::TestExecutor::new();
431 let empty = bredr::Channel::default();
432 assert!(Channel::try_from(empty).is_err());
433
434 let (remote, _local) = zx::Socket::create_datagram();
435
436 let okay = bredr::Channel {
437 socket: Some(remote),
438 channel_mode: Some(fidl_bt::ChannelMode::Basic),
439 max_tx_sdu_size: Some(1004),
440 ..Default::default()
441 };
442
443 let chan = Channel::try_from(okay).expect("okay channel to be converted");
444
445 assert_eq!(1004, chan.max_tx_size());
446 assert_eq!(&ChannelMode::Basic, chan.channel_mode());
447 }
448
449 #[test]
450 fn test_channel_closed() {
451 let mut exec = fasync::TestExecutor::new();
452
453 let (recv, send) = Channel::create();
454
455 let closed_fut = recv.closed();
456 let mut closed_fut = pin!(closed_fut);
457
458 assert!(exec.run_until_stalled(&mut closed_fut).is_pending());
459 assert!(!recv.is_closed());
460
461 drop(send);
462
463 assert!(exec.run_until_stalled(&mut closed_fut).is_ready());
464 assert!(recv.is_closed());
465 }
466
467 #[test]
468 fn test_direction_ext() {
469 let mut exec = fasync::TestExecutor::new();
470
471 let (remote, _local) = zx::Socket::create_datagram();
472 let no_ext = bredr::Channel {
473 socket: Some(remote),
474 channel_mode: Some(fidl_bt::ChannelMode::Basic),
475 max_tx_sdu_size: Some(1004),
476 ..Default::default()
477 };
478 let channel = Channel::try_from(no_ext).unwrap();
479
480 assert!(
481 exec.run_singlethreaded(channel.set_audio_priority(A2dpDirection::Normal)).is_err()
482 );
483 assert!(exec.run_singlethreaded(channel.set_audio_priority(A2dpDirection::Sink)).is_err());
484
485 let (remote, _local) = zx::Socket::create_datagram();
486 let (client_end, mut direction_request_stream) =
487 create_request_stream::<bredr::AudioDirectionExtMarker>();
488 let ext = bredr::Channel {
489 socket: Some(remote),
490 channel_mode: Some(fidl_bt::ChannelMode::Basic),
491 max_tx_sdu_size: Some(1004),
492 ext_direction: Some(client_end),
493 ..Default::default()
494 };
495
496 let channel = Channel::try_from(ext).unwrap();
497
498 let audio_direction_fut = channel.set_audio_priority(A2dpDirection::Normal);
499 let mut audio_direction_fut = pin!(audio_direction_fut);
500
501 assert!(exec.run_until_stalled(&mut audio_direction_fut).is_pending());
502
503 match exec.run_until_stalled(&mut direction_request_stream.next()) {
504 Poll::Ready(Some(Ok(bredr::AudioDirectionExtRequest::SetPriority {
505 priority,
506 responder,
507 }))) => {
508 assert_eq!(bredr::A2dpDirectionPriority::Normal, priority);
509 responder.send(Ok(())).expect("response to send cleanly");
510 }
511 x => panic!("Expected a item to be ready on the request stream, got {:?}", x),
512 };
513
514 match exec.run_until_stalled(&mut audio_direction_fut) {
515 Poll::Ready(Ok(())) => {}
516 _x => panic!("Expected ok result from audio direction response"),
517 };
518
519 let audio_direction_fut = channel.set_audio_priority(A2dpDirection::Sink);
520 let mut audio_direction_fut = pin!(audio_direction_fut);
521
522 assert!(exec.run_until_stalled(&mut audio_direction_fut).is_pending());
523
524 match exec.run_until_stalled(&mut direction_request_stream.next()) {
525 Poll::Ready(Some(Ok(bredr::AudioDirectionExtRequest::SetPriority {
526 priority,
527 responder,
528 }))) => {
529 assert_eq!(bredr::A2dpDirectionPriority::Sink, priority);
530 responder
531 .send(Err(fidl_fuchsia_bluetooth::ErrorCode::Failed))
532 .expect("response to send cleanly");
533 }
534 x => panic!("Expected a item to be ready on the request stream, got {:?}", x),
535 };
536
537 match exec.run_until_stalled(&mut audio_direction_fut) {
538 Poll::Ready(Err(_)) => {}
539 _x => panic!("Expected error result from audio direction response"),
540 };
541 }
542
543 #[test]
544 fn test_flush_timeout() {
545 let mut exec = fasync::TestExecutor::new();
546
547 let (remote, _local) = zx::Socket::create_datagram();
548 let no_ext = bredr::Channel {
549 socket: Some(remote),
550 channel_mode: Some(fidl_bt::ChannelMode::Basic),
551 max_tx_sdu_size: Some(1004),
552 flush_timeout: Some(50_000_000), ..Default::default()
554 };
555 let channel = Channel::try_from(no_ext).unwrap();
556
557 assert_eq!(Some(zx::MonotonicDuration::from_millis(50)), channel.flush_timeout());
558
559 let res = exec.run_singlethreaded(
561 channel.set_flush_timeout(Some(zx::MonotonicDuration::from_millis(49))),
562 );
563 assert_eq!(Some(zx::MonotonicDuration::from_millis(50)), res.expect("shouldn't error"));
564 let res = exec.run_singlethreaded(
565 channel.set_flush_timeout(Some(zx::MonotonicDuration::from_millis(51))),
566 );
567 assert_eq!(Some(zx::MonotonicDuration::from_millis(50)), res.expect("shouldn't error"));
568
569 assert!(
570 exec.run_singlethreaded(
571 channel.set_flush_timeout(Some(zx::MonotonicDuration::from_millis(200)))
572 )
573 .is_err()
574 );
575 assert!(exec.run_singlethreaded(channel.set_flush_timeout(None)).is_err());
576
577 let (remote, _local) = zx::Socket::create_datagram();
578 let (client_end, mut l2cap_request_stream) =
579 create_request_stream::<bredr::L2capParametersExtMarker>();
580 let ext = bredr::Channel {
581 socket: Some(remote),
582 channel_mode: Some(fidl_bt::ChannelMode::Basic),
583 max_tx_sdu_size: Some(1004),
584 flush_timeout: None,
585 ext_l2cap: Some(client_end),
586 ..Default::default()
587 };
588
589 let channel = Channel::try_from(ext).unwrap();
590
591 {
592 let flush_timeout_fut = channel.set_flush_timeout(None);
593 let mut flush_timeout_fut = pin!(flush_timeout_fut);
594
595 match exec.run_until_stalled(&mut flush_timeout_fut) {
597 Poll::Ready(Ok(None)) => {}
598 x => panic!("Expected no flush timeout to not stall, got {:?}", x),
599 }
600 }
601
602 let req_duration = zx::MonotonicDuration::from_millis(42);
603
604 {
605 let flush_timeout_fut = channel.set_flush_timeout(Some(req_duration));
606 let mut flush_timeout_fut = pin!(flush_timeout_fut);
607
608 assert!(exec.run_until_stalled(&mut flush_timeout_fut).is_pending());
609
610 match exec.run_until_stalled(&mut l2cap_request_stream.next()) {
611 Poll::Ready(Some(Ok(bredr::L2capParametersExtRequest::RequestParameters {
612 request,
613 responder,
614 }))) => {
615 assert_eq!(Some(req_duration.into_nanos()), request.flush_timeout);
616 let params = fidl_bt::ChannelParameters {
618 flush_timeout: Some(50_000_000), ..Default::default()
620 };
621 responder.send(¶ms).expect("response to send cleanly");
622 }
623 x => panic!("Expected a item to be ready on the request stream, got {:?}", x),
624 };
625
626 match exec.run_until_stalled(&mut flush_timeout_fut) {
627 Poll::Ready(Ok(Some(duration))) => {
628 assert_eq!(zx::MonotonicDuration::from_millis(50), duration)
629 }
630 x => panic!("Expected ready result from params response, got {:?}", x),
631 };
632 }
633
634 assert_eq!(Some(zx::MonotonicDuration::from_millis(50)), channel.flush_timeout());
636 }
637
638 #[test]
639 fn test_audio_offload() {
640 let _exec = fasync::TestExecutor::new();
641
642 let (remote, _local) = zx::Socket::create_datagram();
643 let no_ext = bredr::Channel {
644 socket: Some(remote),
645 channel_mode: Some(fidl_bt::ChannelMode::Basic),
646 max_tx_sdu_size: Some(1004),
647 ..Default::default()
648 };
649 let channel = Channel::try_from(no_ext).unwrap();
650
651 assert!(channel.audio_offload().is_none());
652
653 let (remote, _local) = zx::Socket::create_datagram();
654 let (client_end, mut _audio_offload_ext_req_stream) =
655 create_request_stream::<bredr::AudioOffloadExtMarker>();
656 let ext = bredr::Channel {
657 socket: Some(remote),
658 channel_mode: Some(fidl_bt::ChannelMode::Basic),
659 max_tx_sdu_size: Some(1004),
660 ext_audio_offload: Some(client_end),
661 ..Default::default()
662 };
663
664 let channel = Channel::try_from(ext).unwrap();
665
666 let offload_ext = channel.audio_offload();
667 assert!(offload_ext.is_some());
668 assert!(channel.audio_offload().is_some());
670 drop(offload_ext);
672 assert!(channel.audio_offload().is_some());
673 }
674
675 #[test]
676 fn channel_sink() {
677 let mut exec = fasync::TestExecutor::new();
678 let (mut recv, mut send) = Channel::create();
679
680 let data = vec![0x01, 0x02, 0x03, 0x04];
681 let mut send_fut = send.send(data.clone());
682
683 match exec.run_until_stalled(&mut send_fut) {
685 Poll::Ready(Ok(())) => {}
686 x => panic!("Expected Ready(Ok(())), got {:?}", x),
687 }
688
689 let mut recv_fut = recv.next();
690 match exec.run_until_stalled(&mut recv_fut) {
691 Poll::Ready(Some(Ok(bytes))) => assert_eq!(data, bytes),
692 x => panic!("Expected successful read, got {x:?}"),
693 }
694 }
695
696 #[test]
697 fn channel_stream() {
698 let mut exec = fasync::TestExecutor::new();
699 let (mut recv, send) = Channel::create();
700
701 let mut stream_fut = recv.next();
702
703 assert!(exec.run_until_stalled(&mut stream_fut).is_pending());
704
705 let heart: &[u8] = &[0xF0, 0x9F, 0x92, 0x96];
706 assert_eq!(heart.len(), send.write(heart).expect("should write successfully"));
707
708 match exec.run_until_stalled(&mut stream_fut) {
709 Poll::Ready(Some(Ok(bytes))) => {
710 assert_eq!(heart.to_vec(), bytes);
711 }
712 x => panic!("Expected Some(Ok(bytes)) from the stream, got {x:?}"),
713 };
714
715 drop(send);
717
718 let mut stream_fut = recv.next();
719 match exec.run_until_stalled(&mut stream_fut) {
720 Poll::Ready(None) => {}
721 x => panic!("Expected None from the stream after close, got {x:?}"),
722 }
723
724 assert!(recv.is_terminated());
726 }
727}