Skip to content

Commit

Permalink
Add [try_]copy_from_str to Str<_>. (#56)
Browse files Browse the repository at this point in the history
This PR adds two functions, try_copy_from_str and copy_from_str to Str<_> that
create a new octets sequence with the content of a str.
  • Loading branch information
partim authored Apr 24, 2024
1 parent 86d80d2 commit a892b7c
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
use core::{borrow, cmp, fmt, hash, ops, str};
use core::convert::Infallible;
use crate::builder::{
EmptyBuilder, FreezeBuilder, OctetsBuilder, Truncate, infallible
BuilderAppendError, EmptyBuilder, FreezeBuilder, FromBuilder,
OctetsBuilder, Truncate, infallible
};
use crate::octets::OctetsFrom;

Expand Down Expand Up @@ -40,6 +41,34 @@ impl<Octets> Str<Octets> {
pub unsafe fn from_utf8_unchecked(octets: Octets) -> Self {
Self(octets)
}

/// Creates a value by copying the content of a `str`.
pub fn try_copy_from_str(
s: &str
) -> Result<Self, BuilderAppendError<Octets>>
where
Octets: FromBuilder,
<Octets as FromBuilder>::Builder: EmptyBuilder,
{
let mut res = <Octets as FromBuilder>::Builder::with_capacity(s.len());
res.append_slice(s.as_bytes())?;
Ok(unsafe { Self::from_utf8_unchecked(res.freeze()) })
}

/// Creates a value by copying the content of a `str`.
///
/// This function is identical to
/// [`try_copy_from_str`][Self::try_copy_from_str] for octets types
/// of unlimited capacity.
pub fn copy_from_str(s: &str) -> Self
where
Octets: FromBuilder,
<Octets as FromBuilder>::Builder: EmptyBuilder,
<<Octets as FromBuilder>::Builder as OctetsBuilder>::AppendError:
Into<Infallible>,
{
infallible(Self::try_copy_from_str(s))
}
}

impl Str<[u8]> {
Expand Down

0 comments on commit a892b7c

Please sign in to comment.