Read this in other languages: English, 简体中文.
A Rust crate to read variable length data based on varint format.
- Reading and writing.
- Both synchronous and asynchronous implementations.
- Support bytes and tokio crates.
- Long chunk version for varint implementations. (But not recommended to use because it's stupid.)
- Support signed and unsigned value. (Using zigzag encoding.)
- Support usize/isize directly or convert from/to u128/i128. (with the
ap
suffix.) - Support extra type of
f32
,f64
,vec<u8>
andstring
. - Built-in implementation of
std::io::Read
,std::io::Write
andtokio::io::AsyncRead
,tokio::io::AsyncWrite
. - Chaining
bytes::Buf
support. - no-std support.
Add this to your Cargo.toml
:
[dependencies]
variable-len-reader = "^3.2"
Directly use in tcp stream:
use std::net::{TcpListener, TcpStream};
use anyhow::Result;
use variable_len_reader::{VariableReader, VariableWriter};
fn main() -> Result<()> {
let server = TcpListener::bind("localhost:0")?;
let mut client = TcpStream::connect(server.local_addr()?)?;
let mut server = server.incoming().next().unwrap()?;
// Write
client.write_string(&"Hello world!")?;
// Read
let message = server.read_string()?;
assert_eq!("Hello world!", message);
Ok(())
}
Use with bytes crate:
use bytes::{Buf, BufMut, BytesMut};
use variable_len_reader::{VariableReader, VariableWriter};
fn main() {
let message = "Hello world!";
let mut writer = BytesMut::new().writer();
// Write
writer.write_string(message).unwrap();
let bytes = writer.into_inner();
assert_eq!(message.len() as u8, bytes[0]);
assert_eq!(message.as_bytes(), &bytes[1..]);
let mut reader = bytes.reader();
// Read
let string = reader.read_string().unwrap();
assert_eq!(message, string);
}
Async mode with tokio crate: (Require 'async_default' feature)
use anyhow::Result;
use tokio::net::{TcpListener, TcpStream};
use variable_len_reader::{AsyncVariableReader, AsyncVariableWriter};
use variable_len_reader::helper::{AsyncReaderHelper, AsyncWriterHelper};
#[tokio::main]
async fn main() -> Result<()> {
let server = TcpListener::bind("localhost:0").await?;
let mut client = TcpStream::connect(server.local_addr()?).await?;
let (mut server, _) = server.accept().await?;
// Write
AsyncWriterHelper(&mut client).help_write_string(&"Hello tokio!").await?;
// Read
let message = AsyncReaderHelper(&mut server).help_read_string().await?;
assert_eq!("Hello tokio!", message);
Ok(())
}