Variable Len Reader

Read this in other languages: English, 简体中文.
Description
A Rust crate to read variable length data based on varint format.
Read and write compressed data. Of each such byte, only 7 bits will be used to describe the actual value
since its most significant bit indicates whether the next byte is part of the same int.
Micro-optimization for int values that are expected to have values below 128.
Usage
Add this to your Cargo.toml
:
[dependencies]
variable-len-reader = "~0.5"
Example
Directly use in tcp stream:
use std::net::{TcpListener, TcpStream};
use variable_len_reader::{VariableReadable, VariableWritable};
fn main() {
let addr = "localhost:25564";
let server = TcpListener::bind(addr).unwrap();
let mut client = TcpStream::connect(addr).unwrap();
let mut server = server.incoming().next().unwrap().unwrap();
client.write_string(&"Hello world!").unwrap();
let message = server.read_string().unwrap();
assert_eq!("Hello world!", message);
}
Use with bytes crate:
use bytes::{Buf, BufMut, BytesMut};
use variable_len_reader::{VariableReadable, VariableWritable};
fn main() {
let message = "Hello world!";
let mut writer = BytesMut::new().writer();
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();
let string = reader.read_string().unwrap();
assert_eq!(message, string);
}
Async mode with tokio crate:
(Require 'async_default' feature)
use tokio::net::{TcpListener, TcpStream};
use variable_len_reader::asynchronous::{AsyncVariableReadable, AsyncVariableWritable};
#[tokio::main]
async fn main() {
let addr = "localhost:25564";
let server = TcpListener::bind(addr).await.unwrap();
let mut client = TcpStream::connect(addr).await.unwrap();
let (mut server, _) = server.accept().await.unwrap();
client.write_string(&"Hello tokio!").await.unwrap();
let message = server.read_string().await.unwrap();
assert_eq!("Hello tokio!", message);
}