1 // Copyright 2022 The Chromium OS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 //! Implements the interface required by `audio_streams` using the cros_async Executor. 6 //! 7 //! It implements the `AudioStreamsExecutor` trait for `Executor`, so it can be passed into 8 //! the audio_streams API. 9 #[cfg(unix)] 10 use std::os::unix::net::UnixStream; 11 12 use std::{io::Result, time::Duration}; 13 14 use super::{AsyncWrapper, IntoAsync, IoSourceExt, TimerAsync}; 15 use async_trait::async_trait; 16 use audio_streams::async_api::{ 17 AsyncStream, AudioStreamsExecutor, ReadAsync, ReadWriteAsync, WriteAsync, 18 }; 19 20 /// A wrapper around IoSourceExt that is compatible with the audio_streams traits. 21 pub struct IoSourceWrapper<T: IntoAsync + Send> { 22 source: Box<dyn IoSourceExt<T> + Send>, 23 } 24 25 #[async_trait(?Send)] 26 impl<T: IntoAsync + Send> ReadAsync for IoSourceWrapper<T> { read_to_vec<'a>( &'a self, file_offset: Option<u64>, vec: Vec<u8>, ) -> Result<(usize, Vec<u8>)>27 async fn read_to_vec<'a>( 28 &'a self, 29 file_offset: Option<u64>, 30 vec: Vec<u8>, 31 ) -> Result<(usize, Vec<u8>)> { 32 self.source 33 .read_to_vec(file_offset, vec) 34 .await 35 .map_err(Into::into) 36 } 37 } 38 39 #[async_trait(?Send)] 40 impl<T: IntoAsync + Send> WriteAsync for IoSourceWrapper<T> { write_from_vec<'a>( &'a self, file_offset: Option<u64>, vec: Vec<u8>, ) -> Result<(usize, Vec<u8>)>41 async fn write_from_vec<'a>( 42 &'a self, 43 file_offset: Option<u64>, 44 vec: Vec<u8>, 45 ) -> Result<(usize, Vec<u8>)> { 46 self.source 47 .write_from_vec(file_offset, vec) 48 .await 49 .map_err(Into::into) 50 } 51 } 52 53 #[async_trait(?Send)] 54 impl<T: IntoAsync + Send> ReadWriteAsync for IoSourceWrapper<T> {} 55 56 #[async_trait(?Send)] 57 impl AudioStreamsExecutor for super::Executor { 58 #[cfg(unix)] async_unix_stream(&self, stream: UnixStream) -> Result<AsyncStream>59 fn async_unix_stream(&self, stream: UnixStream) -> Result<AsyncStream> { 60 return Ok(Box::new(IoSourceWrapper { 61 source: self.async_from(AsyncWrapper::new(stream))?, 62 })); 63 } 64 delay(&self, dur: Duration) -> Result<()>65 async fn delay(&self, dur: Duration) -> Result<()> { 66 TimerAsync::sleep(self, dur).await.map_err(Into::into) 67 } 68 } 69