diff --git a/Cargo.lock b/Cargo.lock index ef9a54c..827f35a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -100,7 +100,7 @@ checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "bytes-str" -version = "0.2.5" +version = "0.2.6" dependencies = [ "bytes", "rkyv", diff --git a/crates/bytes-str/Cargo.toml b/crates/bytes-str/Cargo.toml index 85548d0..fdfe186 100644 --- a/crates/bytes-str/Cargo.toml +++ b/crates/bytes-str/Cargo.toml @@ -6,7 +6,7 @@ include = ["Cargo.toml", "src/**/*.rs"] license = { workspace = true } name = "bytes-str" repository = { workspace = true } -version = "0.2.5" +version = "0.2.6" [features] rkyv = ["dep:rkyv", "rkyv/bytes-1"] diff --git a/crates/bytes-str/src/byte_string.rs b/crates/bytes-str/src/byte_string.rs index 91f1aeb..202d459 100644 --- a/crates/bytes-str/src/byte_string.rs +++ b/crates/bytes-str/src/byte_string.rs @@ -366,6 +366,24 @@ impl BytesString { bytes: BytesMut::from(bytes), }) } + + /// Converts a [BytesString] into a [String]. + /// + /// # Examples + /// + /// ``` + /// use bytes_str::BytesString; + /// ``` + /// use bytes_str::BytesString; + /// + /// let s = BytesString::from("hello"); + /// + /// let string = s.into_string(); + /// + /// assert_eq!(string, "hello"); + pub fn into_string(self) -> String { + self.into() + } } impl Deref for BytesString { @@ -402,6 +420,17 @@ impl From for BytesString { } } +impl From for String { + fn from(s: BytesString) -> Self { + let vec: Vec<_> = s.bytes.freeze().into(); + + unsafe { + // SAFETY: We know the bytes are valid UTF-8 because we created them + String::from_utf8_unchecked(vec) + } + } +} + impl From<&str> for BytesString { fn from(s: &str) -> Self { Self { @@ -727,6 +756,18 @@ impl Hash for BytesString { } } +impl fmt::Write for BytesString { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.push_str(s); + Ok(()) + } + + fn write_char(&mut self, c: char) -> fmt::Result { + self.push(c); + Ok(()) + } +} + #[cfg(feature = "serde")] mod serde_impl { use serde::{Deserialize, Deserializer, Serialize, Serializer};