Skip to content

About

A trait for byte sequences and UTF-8 strings

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

10 Commits

Folders and files

Repository files navigation

stringbytes

github crates.io docs.rs build status

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.

Examples

&[u8]

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");

Vec<u8>

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);

Box<[u8]>

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");

&str

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);

String

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);

About

A trait for byte sequences and UTF-8 strings

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages