pub fn B<'a, B: ?Sized + AsRef<[u8]>>(bytes: &'a B) -> &'a [u8] ⓘ
Expand description
A short-hand constructor for building a &[u8]
.
This idiosyncratic constructor is useful for concisely building byte string slices. Its primary utility is in conveniently writing byte string literals in a uniform way. For example, consider this code that does not compile:
let strs = vec![b"a", b"xy"];
The above code doesn’t compile because the type of the byte string literal
b"a"
is &'static [u8; 1]
, and the type of b"xy"
is
&'static [u8; 2]
. Since their types aren’t the same, they can’t be stored
in the same Vec
. (This is dissimilar from normal Unicode string slices,
where both "a"
and "xy"
have the same type of &'static str
.)
One way of getting the above code to compile is to convert byte strings to slices. You might try this:
let strs = vec![&b"a", &b"xy"];
But this just creates values with type & &'static [u8; 1]
and
& &'static [u8; 2]
. Instead, you need to force the issue like so:
let strs = vec![&b"a"[..], &b"xy"[..]];
// or
let strs = vec![b"a".as_ref(), b"xy".as_ref()];
But neither of these are particularly convenient to type, especially when it’s something as common as a string literal. Thus, this constructor permits writing the following instead:
use bstr::B;
let strs = vec![B("a"), B(b"xy")];
Notice that this also lets you mix and match both string literals and byte string literals. This can be quite convenient!