Crate bytestr

Crate bytestr 

Source
Expand description

§ByteStr

A zero-copy, cheaply cloneable, and sliceable immutable UTF-8 encoded string type.

ByteStr is built on top of bytes::Bytes and provides a UTF-8 guaranteed string that can be cloned and sliced without additional allocations. This makes it perfect for high-performance network programming, parsing, and any scenario where you need efficient string manipulation.

§Examples

§Basic Usage

use bytestr::ByteStr;

// Create from static string (zero-cost)
let static_str = ByteStr::from_static("Hello, world!");

// Create from String (reuses allocation)
let from_string = ByteStr::from("Hello, world!".to_string());

// Create from bytes with validation
let from_bytes = ByteStr::from_utf8(b"Hello, world!".to_vec()).unwrap();

// All are equal
assert_eq!(static_str, from_string);
assert_eq!(from_string, from_bytes);

§Zero-Copy Operations

use bytestr::ByteStr;

let original = ByteStr::from_static("Hello, world!");

// Cloning is O(1) - just increments reference count
let cloned = original.clone();

// Slicing is O(1) - creates a new view without copying
let original_str = original.as_str();
let slice = original.slice_ref(&original_str[7..12]); // "world"

// Or use convenient indexing syntax
let slice_by_index = &original[7..12]; // "world" (returns &str)

assert_eq!(slice.as_str(), "world");
assert_eq!(slice_by_index, "world");

§String Operations

use bytestr::ByteStr;

let s = ByteStr::from("Hello, 世界! 🦀");

// All standard string operations work
assert_eq!(s.len(), 19); // Byte length (not character count)
assert!(s.starts_with("Hello"));
assert!(s.contains("世界"));
assert!(s.contains("🦀"));
assert!(s.ends_with("🦀"));

§Zero-Copy Parsing

ByteStr provides powerful parsing utilities that maintain zero-copy semantics:

use bytestr::ByteStr;

// HTTP request parsing
let request = ByteStr::from("GET /api/users HTTP/1.1\r\nHost: example.com\r\n");
let (request_line, headers) = request.split_once("\r\n").unwrap();

let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap();     // "GET"
let path = parts.next().unwrap();       // "/api/users"
let version = parts.next().unwrap();    // "HTTP/1.1"

// Configuration parsing
let config = ByteStr::from("port=8080\nhost=localhost\n");
for line in config.lines() {
    if let Some((key, value)) = line.split_once("=") {
        println!("{}={}", key.as_str(), value.as_str());
    }
}

// Lexical analysis
let code = ByteStr::from("let x = 42;");
let (identifier, rest) = code.skip_while(|c| c.is_whitespace())
                             .take_while(|c| c.is_alphabetic());
assert_eq!(identifier.as_str(), "let");

§Optional Features

§Serde Support

Enable the serde feature for serialization support:

[dependencies]
bytestr = { version = "0.2", features = ["serde"] }

Structs§

ByteStr
A cheaply cloneable and sliceable immutable UTF-8 encoded string.