Struct binary_util::io::ByteWriter

source ·
pub struct ByteWriter { /* private fields */ }
Expand description

ByteWriter is a panic-free way to write bytes to a BufMut trait.

Example

A generic example of how to use the ByteWriter struct.

use binary_util::io::ByteWriter;
use binary_util::io::ByteReader;

fn main() {
   let mut writer = ByteWriter::new();
   writer.write_string("Hello World!").unwrap();
   writer.write_var_u32(65536).unwrap();
   writer.write_u8(0).unwrap();

   println!("Bytes: {:?}", writer.as_slice());
}

ByteWriter also implements the Into trait to convert the ByteWriter into a BytesMut or Bytes structs.

use binary_util::io::ByteWriter;
use binary_util::io::ByteReader;

fn main() {
    let mut writer = ByteWriter::new();
    writer.write_u8(1);
    writer.write_u8(2);
    writer.write_u8(3);

    let mut reader: ByteReader = writer.into();
    assert_eq!(reader.read_u8().unwrap(), 1);
    assert_eq!(reader.read_u8().unwrap(), 2);
    assert_eq!(reader.read_u8().unwrap(), 3);
}
ByteWriter Implementation Notice

While most of the methods are reversable, some are not. Meaning there is a chance that if you call a method in a edge case, it will corrupt the stream.

For example, write_var_u32 is not reversable because we currently do not allocate a buffer to store the bytes before writing them to the buffer. While you should never encounter this issue, it is possible when you run out of memory. This issue is marked as a todo, but is low priority.

Implementations§

source§

impl ByteWriter

source

pub fn new() -> Self

source

pub fn write_u8(&mut self, num: u8) -> Result<(), Error>

source

pub fn write_i8(&mut self, num: i8) -> Result<(), Error>

source

pub fn write_u16(&mut self, num: u16) -> Result<(), Error>

source

pub fn write_u16_le(&mut self, num: u16) -> Result<(), Error>

source

pub fn write_i16(&mut self, num: i16) -> Result<(), Error>

source

pub fn write_i16_le(&mut self, num: i16) -> Result<(), Error>

source

pub fn write_u24<I: Into<u32>>(&mut self, num: I) -> Result<(), Error>

source

pub fn write_u24_le<I: Into<u32>>(&mut self, num: I) -> Result<(), Error>

source

pub fn write_i24<I: Into<i32>>(&mut self, num: I) -> Result<(), Error>

source

pub fn write_i24_le<I: Into<i32>>(&mut self, num: I) -> Result<(), Error>

source

pub fn write_u32(&mut self, num: u32) -> Result<(), Error>

source

pub fn write_u32_le(&mut self, num: u32) -> Result<(), Error>

source

pub fn write_i32(&mut self, num: i32) -> Result<(), Error>

source

pub fn write_i32_le(&mut self, num: i32) -> Result<(), Error>

source

pub fn write_f32(&mut self, num: f32) -> Result<(), Error>

source

pub fn write_f32_le(&mut self, num: f32) -> Result<(), Error>

source

pub fn write_var_u32(&mut self, num: u32) -> Result<(), Error>

source

pub fn write_var_i32(&mut self, num: i32) -> Result<(), Error>

source

pub fn write_u64(&mut self, num: u64) -> Result<(), Error>

source

pub fn write_u64_le(&mut self, num: u64) -> Result<(), Error>

source

pub fn write_i64(&mut self, num: i64) -> Result<(), Error>

source

pub fn write_i64_le(&mut self, num: i64) -> Result<(), Error>

source

pub fn write_f64(&mut self, num: f64) -> Result<(), Error>

source

pub fn write_f64_le(&mut self, num: f64) -> Result<(), Error>

source

pub fn write_var_u64(&mut self, num: u64) -> Result<(), Error>

source

pub fn write_var_i64(&mut self, num: i64) -> Result<(), Error>

source

pub fn write_u128(&mut self, num: u128) -> Result<(), Error>

source

pub fn write_u128_le(&mut self, num: u128) -> Result<(), Error>

source

pub fn write_i128(&mut self, num: i128) -> Result<(), Error>

source

pub fn write_i128_le(&mut self, num: i128) -> Result<(), Error>

source

pub fn write_uint(&mut self, num: u64, size: usize) -> Result<(), Error>

source

pub fn write_uint_le(&mut self, num: u64, size: usize) -> Result<(), Error>

source

pub fn write_int(&mut self, num: i64, size: usize) -> Result<(), Error>

source

pub fn write_int_le(&mut self, num: i64, size: usize) -> Result<(), Error>

source

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

source

pub fn write_bool(&mut self, b: bool) -> Result<(), Error>

source

pub fn write_string(&mut self, string: &str) -> Result<(), Error>

Write a string to the buffer The string is written as a var_u32 length followed by the bytes of the string. Uses https://protobuf.dev/programming-guides/encoding/#length-types for length encoding

source

pub fn write_option( &mut self, option: &Option<impl Writer> ) -> Result<(), Error>

Writes an Option to the buffer. The option must implement the Writer trait.

Example
use binary_util::io::ByteWriter;
use binary_util::interfaces::Writer;

pub struct HelloWorld {
    pub magic: u32
}

impl Writer for HelloWorld {
    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
        buf.write_u32(self.magic)?;
        return Ok(());
    }
}

fn main() {
    let hello = HelloWorld { magic: 0xCAFEBABE };
    let mut buf = hello.write_to_bytes().unwrap();

    println!("Hello World: {:?}", buf);
}
source

pub fn write_slice(&mut self, slice: &[u8]) -> Result<(), Error>

Writes a size-prefixed slice of bytes to the buffer. The slice is prefixed with a var_u32 length.

source

pub fn write(&mut self, buf: &[u8]) -> Result<(), Error>

Writes a slice of bytes to the buffer This is not the same as a size-prefixed slice, this is just a raw slice of bytes.

For automatically size-prefixed slices, use write_slice.

source

pub fn write_type<T: Writer>(&mut self, t: &T) -> Result<(), Error>

Writes T to the buffer. T must implement the Writer trait. This is the same as calling T.write(self).

use binary_util::interfaces::{Reader, Writer};
use binary_util::io::{ByteReader, ByteWriter};

pub struct HelloPacket {
    pub name: String,
    pub age: u8,
    pub is_cool: bool,
    pub friends: Vec<String>,
}

impl Reader<HelloPacket> for HelloPacket {
    fn read(buf: &mut ByteReader) -> std::io::Result<Self> {
        Ok(Self {
            name: buf.read_string()?,
            age: buf.read_u8()?,
            is_cool: buf.read_bool()?,
            friends: Vec::<String>::read(buf)?
        })
    }
}

impl Writer for HelloPacket {
    fn write(&self, buf: &mut ByteWriter) -> std::io::Result<()> {
        buf.write_string(&self.name);
        buf.write_u8(self.age);
        buf.write_bool(self.is_cool);
        self.friends.write(buf)?;
        Ok(())
    }
}

fn main() {
    let mut buf = ByteWriter::new();
    let packet = HelloPacket {
        name: "John".to_string(),
        age: 18,
        is_cool: true,
        friends: vec!["Bob".to_string(), "Joe".to_string()]
    };
    buf.write_type(&packet).unwrap();
}
source

pub fn as_slice(&self) -> &[u8]

source

pub fn clear(&mut self)

Trait Implementations§

source§

impl Clone for ByteWriter

source§

fn clone(&self) -> ByteWriter

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ByteWriter

source§

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

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

impl From<&[u8]> for ByteWriter

source§

fn from(slice: &[u8]) -> Self

Converts to this type from the input type.
source§

impl From<ByteReader> for ByteWriter

source§

fn from(reader: ByteReader) -> Self

Converts to this type from the input type.
source§

impl From<ByteWriter> for ByteReader

source§

fn from(writer: ByteWriter) -> Self

Converts to this type from the input type.
source§

impl From<IoSlice<'_>> for ByteWriter

source§

fn from(slice: IoSlice<'_>) -> Self

Converts to this type from the input type.
source§

impl Into<Bytes> for ByteWriter

source§

fn into(self) -> Bytes

Converts this type into the (usually inferred) input type.
source§

impl Into<BytesMut> for ByteWriter

source§

fn into(self) -> BytesMut

Converts this type into the (usually inferred) input type.
source§

impl Into<Vec<u8, Global>> for ByteWriter

source§

fn into(self) -> Vec<u8>

Converts this type into the (usually inferred) input type.
source§

impl Into<VecDeque<u8, Global>> for ByteWriter

source§

fn into(self) -> VecDeque<u8>

Converts this type into the (usually inferred) input type.

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere 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> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.