stringbytes provides a common interface for string and byte-buffer storage.
The StringBytes trait can be used as a bound on the storage parameter of
generic string and byte-buffer types.
Both borrowed and owned storage are supported, including shared buffers.
Implementations expose a consistent byte sequence and preserve it when
borrowing as &str or converting into Vec<u8> or String.
The bytes need not be valid UTF-8; validation is performed when needed to
borrow them as &str or convert them into a String.
use stringbytes::StringBytes;
let bytes: &[u8] = b"hello";
// Validate UTF-8 and borrow a string slice without copying.
assert_eq!(bytes.try_borrow_str()?, "hello");use stringbytes::StringBytes;
let bytes = b"hello".to_vec();
let address = bytes.as_ptr();
// Validate UTF-8 and transfer the vector's allocation to the string.
let string = bytes.try_into_string()?;
assert_eq!(string, "hello");
assert_eq!(string.as_ptr(), address);
// Convert back to bytes, keeping the same allocation.
let bytes = string.into_bytes();
assert_eq!(bytes, b"hello");
assert_eq!(bytes.as_ptr(), address);use stringbytes::StringBytes;
let bytes = Box::<[u8]>::from("hello".as_bytes());
// Borrow the bytes as a string slice without copying.
assert_eq!(bytes.try_borrow_str()?, "hello");
// Copy the bytes, keeping the original value.
assert_eq!(bytes.try_to_string()?, "hello");
// Consume the box and reuse its allocation.
assert_eq!(bytes.try_into_string()?, "hello");use stringbytes::StringBytes;
let text: &str = "hello";
// Copy the borrowed string without checking UTF-8 again.
let string = text.try_to_string()?;
assert_eq!(string, text);use stringbytes::StringBytes;
let string = String::from("hello");
let address = string.as_ptr();
let capacity = string.capacity();
// Copy the bytes, keeping the string available.
let bytes = string.to_bytes();
assert_eq!(bytes, b"hello");
// Consume the string, keeping its allocation and capacity.
let string = string.try_into_string()?;
assert_eq!(string, "hello");
assert_eq!(string.as_ptr(), address);
assert_eq!(string.capacity(), capacity);