Skip to main content

BufSink

Struct BufSink 

Source
pub struct BufSink<'a> { /* private fields */ }
Expand description

A fixed-capacity output sink wrapping a borrowed &mut [u8].

Writes are UTF-8 bytes; on overflow the excess is dropped and BufSink::overflowed returns true (the buffer is never written past its end). BufSink::as_str returns the bytes written so far.

Implementations§

Source§

impl<'a> BufSink<'a>

Source

pub fn new(buf: &'a mut [u8]) -> BufSink<'a>

Wrap a byte buffer as an output sink.

Examples found in repository?
examples/disasm.rs (line 55)
31fn emit_word<W: Write>(token: &str, out: &mut W) -> io::Result<()> {
32    let token = token.trim();
33    if token.is_empty() {
34        return Ok(());
35    }
36    // Accept an optional `0x` prefix and surrounding whitespace.
37    let hex = token.trim_start_matches("0x").trim_start_matches("0X");
38    let word = match u32::from_str_radix(hex, 16) {
39        Ok(w) => w,
40        Err(_) => {
41            writeln!(out, "{token}\t<invalid hex>")?;
42            return Ok(());
43        }
44    };
45
46    // Keep the manual diagnostic resilient if an unexpected decoder panic is
47    // introduced: one bad word should not abort a stream of spot checks.
48    let rendered = std::panic::catch_unwind(|| {
49        let bytes = word.to_le_bytes();
50        let mut dec = Decoder::new(&bytes, ADDRESS, DecoderOptions::default());
51        let insn = dec.decode();
52
53        // Zero-alloc format into a fixed stack buffer.
54        let mut buf = [0u8; 256];
55        let mut sink = BufSink::new(&mut buf);
56        FmtFormatter::new().format(&insn, &mut sink);
57        sink.as_str().to_string()
58    })
59    .unwrap_or_else(|_| String::from("<unimplemented>"));
60
61    writeln!(out, "{word:08X}\t{rendered}")?;
62    Ok(())
63}
Source

pub fn as_str(&self) -> &str

The bytes written so far, as &str (always valid UTF-8 because only whole &str chunks are appended, truncated only at chunk granularity).

Examples found in repository?
examples/disasm.rs (line 57)
31fn emit_word<W: Write>(token: &str, out: &mut W) -> io::Result<()> {
32    let token = token.trim();
33    if token.is_empty() {
34        return Ok(());
35    }
36    // Accept an optional `0x` prefix and surrounding whitespace.
37    let hex = token.trim_start_matches("0x").trim_start_matches("0X");
38    let word = match u32::from_str_radix(hex, 16) {
39        Ok(w) => w,
40        Err(_) => {
41            writeln!(out, "{token}\t<invalid hex>")?;
42            return Ok(());
43        }
44    };
45
46    // Keep the manual diagnostic resilient if an unexpected decoder panic is
47    // introduced: one bad word should not abort a stream of spot checks.
48    let rendered = std::panic::catch_unwind(|| {
49        let bytes = word.to_le_bytes();
50        let mut dec = Decoder::new(&bytes, ADDRESS, DecoderOptions::default());
51        let insn = dec.decode();
52
53        // Zero-alloc format into a fixed stack buffer.
54        let mut buf = [0u8; 256];
55        let mut sink = BufSink::new(&mut buf);
56        FmtFormatter::new().format(&insn, &mut sink);
57        sink.as_str().to_string()
58    })
59    .unwrap_or_else(|_| String::from("<unimplemented>"));
60
61    writeln!(out, "{word:08X}\t{rendered}")?;
62    Ok(())
63}
Source

pub fn len(&self) -> usize

Number of bytes written.

Source

pub fn is_empty(&self) -> bool

true if nothing has been written.

Source

pub fn overflowed(&self) -> bool

true if any write was truncated due to insufficient capacity.

Trait Implementations§

Source§

impl<'a> Debug for BufSink<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Write for BufSink<'_>

Source§

fn write_str(&mut self, s: &str) -> Result

Writes a string slice into this writer, returning whether the write succeeded. Read more
1.1.0 · Source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a char into this writer, returning whether the write succeeded. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the write! macro with implementors of this trait. Read more

Auto Trait Implementations§

§

impl<'a> !UnwindSafe for BufSink<'a>

§

impl<'a> Freeze for BufSink<'a>

§

impl<'a> RefUnwindSafe for BufSink<'a>

§

impl<'a> Send for BufSink<'a>

§

impl<'a> Sync for BufSink<'a>

§

impl<'a> Unpin for BufSink<'a>

§

impl<'a> UnsafeUnpin for BufSink<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<W> FormatterOutput for W
where W: Write,

Source§

fn write(&mut self, text: &str, _kind: TokenKind)

Append text, classified as kind.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.