Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid deadlock on data bigger than buffer by chunking #65

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,23 @@ enum State<const N: usize> {
},
}

pub type Write = (Vec<u8>, oneshot::Sender<io::Result<usize>>);
pub type Write = (Chunk, oneshot::Sender<io::Result<usize>>);
pub type Read = (usize, oneshot::Sender<io::Result<Vec<u8>>>);

/// Chunks of a [`Write`] not yet written.
pub struct Chunk {
/// Data pending write.
data: Vec<u8>,
/// The accumulated length of written chunks
acc_len: usize,
}

impl From<Vec<u8>> for Chunk {
fn from(data: Vec<u8>) -> Self {
Self { data, acc_len: 0 }
}
}

#[derive(Clone, Copy, Debug)]
pub struct ConnectionConfig {
pub max_packet_size: u16,
Expand Down Expand Up @@ -455,15 +469,27 @@ impl<const N: usize, P: ConnectionPeer> Connection<N, P> {
}

// Write as much data as possible into send buffer.
while let Some((data, ..)) = self.pending_writes.front() {
if data.len() <= send_buf.available() {
let (data, tx) = self.pending_writes.pop_front().unwrap();
send_buf.write(&data).unwrap();
let _ = tx.send(Ok(data.len()));
self.writable.notify_one();
} else {
while send_buf.available() > 0 {
let Some((Chunk{data, mut acc_len}, tx)) = self.pending_writes.pop_front() else {
break;
};
let written = send_buf.write(&data).unwrap();
acc_len += written;
if written < data.len() {
// not all data fit in the send buffer, chunk data
let mut data = data;
let remaining = data.split_off(data.len() - written);
self.pending_writes.push_front((
Chunk {
data: remaining,
acc_len,
},
tx,
));
} else {
let _ = tx.send(Ok(acc_len));
}
self.writable.notify_one();
}

// Transmit data packets.
Expand Down
2 changes: 1 addition & 1 deletion src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ where

let (tx, rx) = oneshot::channel();
self.writes
.send((buf.to_vec(), tx))
.send((buf.to_vec().into(), tx))
.map_err(|_| io::Error::from(io::ErrorKind::NotConnected))?;

match rx.await {
Expand Down