stringbytes
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.
Implementations are provided for [u8; N], [u8],
Vec<u8>, and Cow<'_, [u8]>; str, String, and
Cow<'_, str>; and &T, &mut T,
Box<T>, Rc<T>, and Arc<T> where T: StringBytes + ?Sized.
The optional bytes feature adds Bytes and BytesMut.
Implementations expose a consistent byte sequence and preserve it when
converting to Vec<u8>, str, 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.
Examples
&[u8]
use StringBytes;
let bytes: & = b"hello";
// Validate UTF-8 and borrow a string slice without copying.
assert_eq!;
Vec<u8>
use 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!;
assert_eq!;
// Convert back to bytes, keeping the same allocation.
let bytes = string.into_bytes;
assert_eq!;
assert_eq!;
Box<[u8]>
use StringBytes;
let bytes = Box::from;
// Borrow the bytes as a string slice without copying.
assert_eq!;
// Copy the bytes, keeping the original value.
assert_eq!;
// Consume the box and reuse its allocation.
assert_eq!;
&str
use StringBytes;
let text: &str = "hello";
// Copy the borrowed string without checking UTF-8 again.
let string = text.try_to_string?;
assert_eq!;
String
use StringBytes;
let string = Stringfrom;
let address = string.as_ptr;
let capacity = string.capacity;
// Copy the bytes, keeping the string available.
let bytes = string.to_bytes;
assert_eq!;
// Consume the string, keeping its allocation and capacity.
let string = string.try_into_string?;
assert_eq!;
assert_eq!;
assert_eq!;