|
1 | 1 | use std::sync::Arc;
|
2 | 2 | use std::{fmt, slice, thread};
|
3 | 3 |
|
4 |
| -use async_channel::{Receiver, Sender}; |
| 4 | +use async_channel::{Receiver, Sender, TryRecvError, TrySendError}; |
5 | 5 | use java_spaghetti::{ByteArray, Global, Local, PrimitiveArray};
|
6 | 6 | use tracing::{debug, warn};
|
7 | 7 |
|
@@ -151,7 +151,27 @@ impl L2capChannelReader {
|
151 | 151 | .stream
|
152 | 152 | .recv()
|
153 | 153 | .await
|
154 |
| - .map_err(|_| Error::new(ErrorKind::ConnectionFailed, None, "L2CAP channel is closed".to_string()))?; |
| 154 | + .map_err(|_| Error::new(ErrorKind::ConnectionFailed, None, "channel is closed".to_string()))?; |
| 155 | + |
| 156 | + if packet.len() > buf.len() { |
| 157 | + return Err(Error::new( |
| 158 | + ErrorKind::InvalidParameter, |
| 159 | + None, |
| 160 | + "Buffer is too small".to_string(), |
| 161 | + )); |
| 162 | + } |
| 163 | + |
| 164 | + buf[..packet.len()].copy_from_slice(&packet); |
| 165 | + |
| 166 | + Ok(packet.len()) |
| 167 | + } |
| 168 | + |
| 169 | + #[inline] |
| 170 | + pub fn try_read(&mut self, buf: &mut [u8]) -> Result<usize> { |
| 171 | + let packet = self.stream.try_recv().map_err(|e| match e { |
| 172 | + TryRecvError::Empty => Error::new(ErrorKind::NotReady, None, "no received packet in queue".to_string()), |
| 173 | + TryRecvError::Closed => Error::new(ErrorKind::ConnectionFailed, None, "channel is closed".to_string()), |
| 174 | + })?; |
155 | 175 |
|
156 | 176 | if packet.len() > buf.len() {
|
157 | 177 | return Err(Error::new(
|
@@ -188,7 +208,14 @@ impl L2capChannelWriter {
|
188 | 208 | self.stream
|
189 | 209 | .send(packet.to_vec())
|
190 | 210 | .await
|
191 |
| - .map_err(|_| Error::new(ErrorKind::ConnectionFailed, None, "L2CAP channel is closed".to_string())) |
| 211 | + .map_err(|_| Error::new(ErrorKind::ConnectionFailed, None, "channel is closed".to_string())) |
| 212 | + } |
| 213 | + |
| 214 | + pub fn try_write(&mut self, packet: &[u8]) -> Result<()> { |
| 215 | + self.stream.try_send(packet.to_vec()).map_err(|e| match e { |
| 216 | + TrySendError::Closed(_) => Error::new(ErrorKind::ConnectionFailed, None, "channel is closed".to_string()), |
| 217 | + TrySendError::Full(_) => Error::new(ErrorKind::NotReady, None, "No buffer space for write".to_string()), |
| 218 | + }) |
192 | 219 | }
|
193 | 220 |
|
194 | 221 | pub async fn close(&mut self) -> Result<()> {
|
|
0 commit comments