pub struct SyncStream<S> { /* private fields */ }compat and io only.Expand description
A growable buffered stream adapter that bridges async I/O with sync traits.
§Buffer Growth Strategy
- Read buffer: Grows as needed to accommodate incoming data, up to
max_buffer_size - Write buffer: Grows as needed for outgoing data, up to
max_buffer_size - Both buffers shrink back to
base_capacitywhen fully consumed and capacity exceeds 4x base
§Usage Pattern
The sync Read and Write implementations will return WouldBlock errors
when buffers need servicing via the async methods:
- Call
fill_read_buf()whenRead::read()returnsWouldBlock - Call
flush_write_buf()whenWrite::write()returnsWouldBlock
§Note on flush()
The Write::flush() method intentionally returns Ok(()) without checking
if there’s buffered data. This is for compatibility with libraries like
tungstenite that call flush() after every write. Actual flushing happens
via the async flush_write_buf() method.
Implementations§
§impl<S> SyncStream<S>
impl<S> SyncStream<S>
pub fn new(stream: S) -> SyncStream<S> ⓘ
pub fn new(stream: S) -> SyncStream<S> ⓘ
Creates a new SyncStream with default buffer sizes.
- Base capacity: 8KiB
- Max buffer size: 64MiB
pub fn with_capacity(base_capacity: usize, stream: S) -> SyncStream<S> ⓘ
pub fn with_capacity(base_capacity: usize, stream: S) -> SyncStream<S> ⓘ
Creates a new SyncStream with a custom base capacity.
The maximum buffer size defaults to 64MiB.
pub fn with_limits(
base_capacity: usize,
max_buffer_size: usize,
stream: S,
) -> SyncStream<S> ⓘ
pub fn with_limits( base_capacity: usize, max_buffer_size: usize, stream: S, ) -> SyncStream<S> ⓘ
Creates a new SyncStream with custom base capacity and maximum
buffer size.
pub fn into_inner(self) -> S
pub fn into_inner(self) -> S
Consumes the SyncStream, returning the underlying stream.
Any buffered data is discarded. Use into_parts
if you need to preserve unread data.
pub fn into_parts(self) -> (S, Vec<u8>)
pub fn into_parts(self) -> (S, Vec<u8>)
Consumes the SyncStream, returning the underlying stream and any
unread buffered data.
If the read buffer is currently lent to an IO operation, the returned
Vec will be empty.
pub fn read_buf_uninit(
&mut self,
buf: &mut [MaybeUninit<u8>],
) -> Result<usize, Error>
pub fn read_buf_uninit( &mut self, buf: &mut [MaybeUninit<u8>], ) -> Result<usize, Error>
Pull some bytes from this source into the specified buffer.
pub fn has_pending_write(&self) -> bool
pub fn has_pending_write(&self) -> bool
Returns true if there is pending data in the write buffer that needs
to be flushed.
§impl<S> SyncStream<S>where
S: AsyncRead,
impl<S> SyncStream<S>where
S: AsyncRead,
pub async fn fill_read_buf(&mut self) -> Result<usize, Error>
pub async fn fill_read_buf(&mut self) -> Result<usize, Error>
Fills the read buffer by reading from the underlying async stream.
This method:
- Compacts the buffer if there’s unconsumed data
- Ensures there’s space for at least
base_capacitymore bytes - Reads data from the underlying stream
- Returns the number of bytes read (0 indicates EOF)
§Errors
Returns an error if:
- The read buffer has reached
max_buffer_size - The underlying stream returns an error
§impl<S> SyncStream<S>where
S: AsyncWrite,
impl<S> SyncStream<S>where
S: AsyncWrite,
pub async fn flush_write_buf(&mut self) -> Result<usize, Error>
pub async fn flush_write_buf(&mut self) -> Result<usize, Error>
Flushes the write buffer to the underlying async stream.
This method:
- Writes all buffered data to the underlying stream
- Calls
flush()on the underlying stream - Returns the total number of bytes flushed
On error, any unwritten data remains in the buffer and can be retried.
§Errors
Returns an error if the underlying stream returns an error. In this case, the buffer retains any data that wasn’t successfully written.
Trait Implementations§
§impl<S> BufRead for SyncStream<S>
impl<S> BufRead for SyncStream<S>
§fn consume(&mut self, amt: usize)
fn consume(&mut self, amt: usize)
amount of additional bytes from the internal buffer as having been read.
Subsequent calls to read only return bytes that have not been marked as read. Read moreSource§fn has_data_left(&mut self) -> Result<bool, Error>
fn has_data_left(&mut self) -> Result<bool, Error>
buf_read_has_data_left)read. Read more1.83.0 · Source§fn skip_until(&mut self, byte: u8) -> Result<usize, Error>
fn skip_until(&mut self, byte: u8) -> Result<usize, Error>
byte or EOF is reached. Read more§impl<S> Debug for SyncStream<S>where
S: Debug,
impl<S> Debug for SyncStream<S>where
S: Debug,
§impl<S> Read for SyncStream<S>
impl<S> Read for SyncStream<S>
§fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
Reads data from the internal buffer.
Returns WouldBlock if the buffer is empty and not at EOF,
indicating that fill_read_buf() should be called.
§fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<(), Error>
read_buf)1.36.0 · Source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf. Read more1.0.0 · Source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf. Read more1.6.0 · Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf. Read moreSource§fn read_buf_exact(
&mut self,
cursor: BorrowedCursor<'_, u8>,
) -> Result<(), Error>
fn read_buf_exact( &mut self, cursor: BorrowedCursor<'_, u8>, ) -> Result<(), Error>
read_buf)cursor. Read more1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read. Read more1.0.0 · Source§fn chain<R>(self, next: R) -> Chain<Self, R> ⓘ
fn chain<R>(self, next: R) -> Chain<Self, R> ⓘ
1.0.0 · Source§fn take(self, limit: u64) -> Take<Self> ⓘwhere
Self: Sized,
fn take(self, limit: u64) -> Take<Self> ⓘwhere
Self: Sized,
limit bytes from it. Read moreSource§fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>where
Self: Sized,
read_array)§impl<S> Splittable for SyncStream<S>where
S: Splittable,
impl<S> Splittable for SyncStream<S>where
S: Splittable,
§type ReadHalf = SyncStreamReadHalf<<S as Splittable>::ReadHalf>
type ReadHalf = SyncStreamReadHalf<<S as Splittable>::ReadHalf>
AsyncRead or
AsyncReadAt.§type WriteHalf = SyncStreamWriteHalf<<S as Splittable>::WriteHalf>
type WriteHalf = SyncStreamWriteHalf<<S as Splittable>::WriteHalf>
AsyncWrite or
AsyncWriteAt.§fn split(
self,
) -> (<SyncStream<S> as Splittable>::ReadHalf, <SyncStream<S> as Splittable>::WriteHalf)
fn split( self, ) -> (<SyncStream<S> as Splittable>::ReadHalf, <SyncStream<S> as Splittable>::WriteHalf)
self and returns a tuple containing separate read and write
halves. Read more§impl<S> Write for SyncStream<S>
impl<S> Write for SyncStream<S>
§fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
Writes data to the internal buffer.
Returns WouldBlock if the buffer needs flushing or has reached max
capacity. In the latter case, it may write partial data before
returning WouldBlock.
§fn flush(&mut self) -> Result<(), Error>
fn flush(&mut self) -> Result<(), Error>
Returns Ok(()) without checking for buffered data.
Important: This does NOT actually flush data to the underlying
stream. This behavior is intentional for compatibility with
libraries like tungstenite that call flush() after every write
operation. The actual async flush happens when flush_write_buf()
is called.
This prevents spurious errors in sync code that expects flush() to
succeed after successfully buffering data.
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector)1.0.0 · Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored)Auto Trait Implementations§
impl<S> Freeze for SyncStream<S>where
S: Freeze,
impl<S> RefUnwindSafe for SyncStream<S>where
S: RefUnwindSafe,
impl<S> Send for SyncStream<S>where
S: Send,
impl<S> Sync for SyncStream<S>where
S: Sync,
impl<S> Unpin for SyncStream<S>where
S: Unpin,
impl<S> UnsafeUnpin for SyncStream<S>where
S: UnsafeUnpin,
impl<S> UnwindSafe for SyncStream<S>where
S: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> ExecutableCommand for T
impl<T> ExecutableCommand for T
§fn execute(&mut self, command: impl Command) -> Result<&mut T, Error>
fn execute(&mut self, command: impl Command) -> Result<&mut T, Error>
Executes the given command directly.
The given command its ANSI escape code will be written and flushed onto Self.
§Arguments
-
The command that you want to execute directly.
§Example
use std::io;
use crossterm::{ExecutableCommand, style::Print};
fn main() -> io::Result<()> {
// will be executed directly
io::stdout()
.execute(Print("sum:\n".to_string()))?
.execute(Print(format!("1 + 1= {} ", 1 + 1)))?;
Ok(())
// ==== Output ====
// sum:
// 1 + 1 = 2
}Have a look over at the Command API for more details.
§Notes
- In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
- In case of Windows versions lower than 10, a direct WinAPI call will be made.
The reason for this is that Windows versions lower than 10 do not support ANSI codes,
and can therefore not be written to the given
writer. Therefore, there is no difference between execute and queue for those old Windows versions.
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreimpl<T> Message for Twhere
T: Send + 'static,
§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> QueueableCommand for T
impl<T> QueueableCommand for T
§fn queue(&mut self, command: impl Command) -> Result<&mut T, Error>
fn queue(&mut self, command: impl Command) -> Result<&mut T, Error>
Queues the given command for further execution.
Queued commands will be executed in the following cases:
- When
flushis called manually on the given type implementingio::Write. - The terminal will
flushautomatically if the buffer is full. - Each line is flushed in case of
stdout, because it is line buffered.
§Arguments
-
The command that you want to queue for later execution.
§Examples
use std::io::{self, Write};
use crossterm::{QueueableCommand, style::Print};
fn main() -> io::Result<()> {
let mut stdout = io::stdout();
// `Print` will executed executed when `flush` is called.
stdout
.queue(Print("foo 1\n".to_string()))?
.queue(Print("foo 2".to_string()))?;
// some other code (no execution happening here) ...
// when calling `flush` on `stdout`, all commands will be written to the stdout and therefore executed.
stdout.flush()?;
Ok(())
// ==== Output ====
// foo 1
// foo 2
}Have a look over at the Command API for more details.
§Notes
- In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
- In case of Windows versions lower than 10, a direct WinAPI call will be made.
The reason for this is that Windows versions lower than 10 do not support ANSI codes,
and can therefore not be written to the given
writer. Therefore, there is no difference between execute and queue for those old Windows versions.
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<W> SynchronizedUpdate for W
impl<W> SynchronizedUpdate for W
§fn sync_update<T>(
&mut self,
operations: impl FnOnce(&mut W) -> T,
) -> Result<T, Error>
fn sync_update<T>( &mut self, operations: impl FnOnce(&mut W) -> T, ) -> Result<T, Error>
Performs a set of actions within a synchronous update.
Updates will be suspended in the terminal, the function will be executed against self, updates will be resumed, and a flush will be performed.
§Arguments
-
Function
A function that performs the operations that must execute in a synchronized update.
§Examples
use std::io;
use crossterm::{ExecutableCommand, SynchronizedUpdate, style::Print};
fn main() -> io::Result<()> {
let mut stdout = io::stdout();
stdout.sync_update(|stdout| {
stdout.execute(Print("foo 1\n".to_string()))?;
stdout.execute(Print("foo 2".to_string()))?;
// The effects of the print command will not be present in the terminal
// buffer, but not visible in the terminal.
std::io::Result::Ok(())
})?;
// The effects of the commands will be visible.
Ok(())
// ==== Output ====
// foo 1
// foo 2
}§Notes
This command is performed only using ANSI codes, and will do nothing on terminals that do not support ANSI codes, or this specific extension.
When rendering the screen of the terminal, the Emulator usually iterates through each visible grid cell and renders its current state. With applications updating the screen a at higher frequency this can cause tearing.
This mode attempts to mitigate that.
When the synchronization mode is enabled following render calls will keep rendering the last rendered state. The terminal Emulator keeps processing incoming text and sequences. When the synchronized update mode is disabled again the renderer may fetch the latest screen buffer state again, effectively avoiding the tearing effect by unintentionally rendering in the middle a of an application screen update.