Skip to content

Commit

Permalink
api: add BStr::new
Browse files Browse the repository at this point in the history
This adds a convenience constructor for building a BStr slice directly
from anything that impls AsRef<[u8]>. This is analogous to, e.g.,
Path::new from std.

While this constructor is redundant, it is often convenient because of
its concreteness. Alternatives rely on generics via trait impls, which
don't always work seamlessly.

Closes #110
  • Loading branch information
BurntSushi committed Jul 11, 2022
1 parent 8ea9382 commit 9b465d6
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/bstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,31 @@ pub struct BStr {
}

impl BStr {
/// Directly creates a `BStr` slice from anything that can be converted
/// to a byte slice.
///
/// This is very similar to the [`B`](crate::B) function, except this
/// returns a `&BStr` instead of a `&[u8]`.
///
/// This is a cost-free conversion.
///
/// # Example
///
/// You can create `BStr`'s from byte arrays, byte slices or even string
/// slices:
///
/// ```
/// use bstr::BStr;
///
/// let a = BStr::new(b"abc");
/// let b = BStr::new(&b"abc"[..]);
/// let c = BStr::new("abc");
///
/// assert_eq!(a, b);
/// assert_eq!(a, c);
/// ```
#[inline]
pub(crate) fn new<B: ?Sized + AsRef<[u8]>>(bytes: &B) -> &BStr {
pub fn new<'a, B: ?Sized + AsRef<[u8]>>(bytes: &'a B) -> &'a BStr {
BStr::from_bytes(bytes.as_ref())
}

Expand Down

0 comments on commit 9b465d6

Please sign in to comment.