| Crates.io | bytestr |
| lib.rs | bytestr |
| version | 0.3.1 |
| created_at | 2023-09-05 12:17:15.930505+00 |
| updated_at | 2025-06-30 18:53:01.611735+00 |
| description | A utility provides a cheaply cloneable and sliceable immutable string. |
| homepage | |
| repository | https://github.com/lexoliu/bytestr |
| max_upload_size | |
| id | 964190 |
| size | 62,311 |
A zero-copy, cheaply cloneable, and sliceable immutable UTF-8 encoded string type built on top of bytes::Bytes. Perfect for high-performance network programming and efficient string manipulation.
bytes crateno_std compatible: Works in embedded and resource-constrained environmentsAdd this to your Cargo.toml:
[dependencies]
bytestr = "0.3"
use bytestr::ByteStr;
// Create from static string (zero-cost)
let s1 = ByteStr::from_static("Hello, world!");
// Create from String (reuses allocation)
let s2 = ByteStr::from("Hello, world!".to_string());
// Create from bytes with validation
let s3 = ByteStr::from_utf8(b"Hello, world!".to_vec())?;
// Clone is cheap (just a reference count increment)
let cloned = s1.clone();
// Slice without copying
let original_str = s1.as_str();
let slice = s1.slice_ref(&original_str[7..12]); // "world"
// Or use convenient indexing syntax (returns &str)
let indexed_slice = &s1[7..12]; // "world"
// All standard string operations work
assert_eq!(s1.len(), 13);
assert!(s1.starts_with("Hello"));
assert!(s1.contains("world"));
assert_eq!(slice.as_str(), indexed_slice);
use bytestr::ByteStr;
use std::collections::HashMap;
// Perfect for network protocols and caching
let mut cache: HashMap<ByteStr, Vec<u8>> = HashMap::new();
// Zero-copy slicing for parsing
fn parse_header(data: &ByteStr) -> (ByteStr, ByteStr) {
let data_str = data.as_str();
let colon_pos = data_str.find(':').unwrap();
let key_slice = &data_str[..colon_pos];
let value_slice = &data_str[colon_pos + 2..]; // Skip ": "
(
data.slice_ref(key_slice),
data.slice_ref(value_slice),
)
}
Enable serialization/deserialization support:
[dependencies]
bytestr = { version = "0.2", features = ["serde"] }
use bytestr::ByteStr;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Message {
content: ByteStr,
}
let msg = Message {
content: ByteStr::from("Hello, serde!"),
};
let json = serde_json::to_string(&msg)?;
let deserialized: Message = serde_json::from_str(&json)?;
This project is licensed under the MIT License.