Struct BString

Source
pub struct BString { /* private fields */ }
Expand description

A growable byte string that is conventionally UTF-8.

A BString has ownership over its contents and corresponds to a growable or shrinkable buffer. Its borrowed counterpart is a BStr, called a byte string slice.

§Examples

You can create a new BString from a literal Unicode string or a literal byte string with BString::from:

use bstr::BString;

let s = BString::from("Hello, world!");

You can append bytes, characters or other strings to a BString:

use bstr::BString;

let mut s = BString::from("Hello, ");
s.push_byte(b'w');
s.push_char('o');
s.push("rl");
s.push(b"d!");
assert_eq!(s, "Hello, world!");

If you have a String or a Vec<u8>, then you can create a BString from it with zero cost:

use bstr::BString;

let s = BString::from(vec![b'f', b'o', b'o']);
let s = BString::from("foo".to_string());

A BString can be freely converted back to a Vec<u8>:

use bstr::BString;

let s = BString::from("foo");
let vector = s.into_vec();
assert_eq!(vector, vec![b'f', b'o', b'o']);

However, converting from a BString to a String requires UTF-8 validation:

use bstr::BString;

let bytes = BString::from("hello");
let string = bytes.into_string()?;

assert_eq!("hello", string);

§UTF-8

Like byte string slices (BStr), a BString is only conventionally UTF-8. This is in constrast to the standard library’s String type, which is guaranteed to be valid UTF-8.

Because of this relaxation, types such as Vec<u8>, &[u8], String and &str can all be converted to a BString (or BStr) at zero cost without any validation step.

Moreover, this relaxation implies that many of the restrictions around mutating a String do not apply to BString. Namely, if your BString is valid UTF-8, then the various methods that mutate the BString do not necessarily prevent you from causing the bytes to become invalid UTF-8. For example:

use bstr::{B, BString};

let mut s = BString::from("hello");
s[1] = b'\xFF';
// `s` was valid UTF-8, but now it's now.
assert_eq!(s, B(b"h\xFFllo"));

§Deref

The BString type implements Deref and DerefMut, where the target types are &BStr and &mut BStr, respectively. Deref permits all of the methods defined on BStr to be implicitly callable on any BString. For example, the contains method is defined on BStr and not BString, but values of type BString can still use it directly:

use bstr::BString;

let s = BString::from("foobarbaz");
assert!(s.contains("bar"));

For more information about how deref works, see the documentation for the std::ops::Deref trait.

§Representation

A BString has the same representation as a Vec<u8> and a String. That is, it is made up of three word sized components: a pointer to a region of memory containing the bytes, a length and a capacity.

Implementations§

Source§

impl BString

Source

pub fn new() -> BString

Creates a new empty BString.

Given that the BString is empty, this will not allocate any initial buffer. While that means that this initial operation is very inexpensive, it may cause excessive allocation later when you add data. If you have an idea of how much data the String will hold, consider the with_capacity method to prevent excessive re-allocation.

§Examples

Basic usage:

use bstr::BString;

let s = BString::new();
Source

pub fn with_capacity(capacity: usize) -> BString

Creates a new empty BString with a particular capacity.

BStrings have an internal buffer to hold their data. The capacity is the length of that buffer, and can be queried with the capacity method. This method creates an empty BString, but one with an initial buffer that can hold capacity bytes. This is useful when you may be appending a bunch of data to the BString, reducing the number of reallocations it needs to do.

If the given capacity is 0, no allocation will occur, and this method is identical to the new method.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::with_capacity(10);

// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);

// These are all done without reallocating...
let cap = s.capacity();
for i in 0..10 {
    s.push_char('a');
}

assert_eq!(s.capacity(), cap);

// ...but this may make the vector reallocate
s.push_char('a');
Source

pub fn from_vec(bytes: Vec<u8>) -> BString

Create a new byte string from the given bytes.

§Examples

Basic usage:

use bstr::BString;

let bytes = vec![b'a', b'b', b'c'];
let s = BString::from_vec(bytes);
assert_eq!("abc", s);
Source

pub fn from_slice<B: AsRef<[u8]>>(slice: B) -> BString

Create a new byte string by copying the given slice.

§Examples

Basic usage:

use bstr::BString;

let s = BString::from_slice(b"abc");
assert_eq!("abc", s);
Source

pub fn from_os_string(os_str: OsString) -> Result<BString, OsString>

Create a new byte string from an owned OS string.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this returns the original OS string if it is not valid UTF-8.

§Examples

Basic usage:

use std::ffi::OsString;

use bstr::BString;

let os_str = OsString::from("foo");
let bs = BString::from_os_string(os_str).expect("must be valid UTF-8");
assert_eq!(bs, "foo");
Source

pub fn from_os_str_lossy<'a>(os_str: &'a OsStr) -> Cow<'a, BStr>

Lossily create a new byte string from an OS string slice.

On Unix, this always succeeds, is zero cost and always returns a slice. On non-Unix systems, this does a UTF-8 check. If the given OS string slice is not valid UTF-8, then it is lossily decoded into valid UTF-8 (with invalid bytes replaced by the Unicode replacement codepoint).

§Examples

Basic usage:

use std::ffi::OsStr;

use bstr::{B, BString};

let os_str = OsStr::new("foo");
let bs = BString::from_os_str_lossy(os_str);
assert_eq!(bs, B("foo"));
Source

pub fn from_path_buf(path: PathBuf) -> Result<BString, PathBuf>

Create a new byte string from an owned file path.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this returns the original path if it is not valid UTF-8.

§Examples

Basic usage:

use std::path::PathBuf;

use bstr::BString;

let path = PathBuf::from("foo");
let bs = BString::from_path_buf(path).expect("must be valid UTF-8");
assert_eq!(bs, "foo");
Source

pub fn from_path_lossy<'a>(path: &'a Path) -> Cow<'a, BStr>

Lossily create a new byte string from a file path.

On Unix, this always succeeds, is zero cost and always returns a slice. On non-Unix systems, this does a UTF-8 check. If the given path is not valid UTF-8, then it is lossily decoded into valid UTF-8 (with invalid bytes replaced by the Unicode replacement codepoint).

§Examples

Basic usage:

use std::path::Path;

use bstr::{B, BString};

let path = Path::new("foo");
let bs = BString::from_path_lossy(path);
assert_eq!(bs, B("foo"));
Source

pub fn push_byte(&mut self, byte: u8)

Appends the given byte to the end of this byte string.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("abc");
s.push_byte(b'\xE2');
s.push_byte(b'\x98');
s.push_byte(b'\x83');
assert_eq!("abc☃", s);
Source

pub fn push_char(&mut self, ch: char)

Appends the given char to the end of this byte string.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("abc");
s.push_char('1');
s.push_char('2');
s.push_char('3');
assert_eq!("abc123", s);
Source

pub fn push<B: AsRef<[u8]>>(&mut self, bytes: B)

Appends the given slice to the end of this byte string. This accepts any type that be converted to a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("abc");
s.push(b"123");
assert_eq!("abc123", s);
Source

pub fn as_bstr(&self) -> &BStr

Extracts a byte string slice containing the entire BString.

§Examples

Basic usage:

use bstr::{BStr, BString};

let s = BString::from("foo");

assert_eq!(BStr::new("foo"), s.as_bstr());
Source

pub fn as_vec(&self) -> &Vec<u8>

Returns this BString as a borrowed byte vector.

§Examples

Basic usage:

use bstr::BString;

let bs = BString::from("ab");
assert!(bs.as_vec().capacity() >= 2);
Source

pub fn as_mut_bstr(&mut self) -> &mut BStr

Converts a BString into a mutable string slice.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
let s_mut_str = s.as_mut_bstr();

s_mut_str[0] = b'F';

assert_eq!("Foobar", s_mut_str);
Source

pub fn as_mut_vec(&mut self) -> &mut Vec<u8>

Returns this BString as a mutable byte vector.

§Examples

Basic usage:

use bstr::BString;

let mut bs = BString::from("ab");
bs.as_mut_vec().push(b'c');
assert_eq!("abc", bs);
Source

pub fn into_vec(self) -> Vec<u8>

Converts a BString into a byte vector.

This consumes the BString, and thus the contents are not copied.

§Examples

Basic usage:

use bstr::BString;

let s = BString::from("hello");
let bytes = s.into_vec();

assert_eq!(vec![104, 101, 108, 108, 111], &bytes[..]);
Source

pub fn into_string(self) -> Result<String, FromUtf8Error>

Converts a BString into a String if and only if this byte string is valid UTF-8.

If it is not valid UTF-8, then the error std::string::FromUtf8Error is returned. (This error can be used to examine why UTF-8 validation failed, or to regain the original byte string.)

§Examples

Basic usage:

use bstr::BString;

let bytes = BString::from("hello");
let string = bytes.into_string()?;

assert_eq!("hello", string);

If this byte string is not valid UTF-8, then an error will be returned. That error can then be used to inspect the location at which invalid UTF-8 was found, or to regain the original byte string:

use bstr::{B, BString};

let bytes = BString::from_slice(b"foo\xFFbar");
let err = bytes.into_string().unwrap_err();

assert_eq!(err.utf8_error().valid_up_to(), 3);
assert_eq!(err.utf8_error().error_len(), Some(1));

// At no point in this example is an allocation performed.
let bytes = BString::from(err.into_bstring());
assert_eq!(bytes, B(b"foo\xFFbar"));
Source

pub fn into_string_lossy(self) -> String

Lossily converts a BString into a String. If this byte string contains invalid UTF-8, then the invalid bytes are replaced with the Unicode replacement codepoint.

§Examples

Basic usage:

use bstr::BString;

let bytes = BString::from_slice(b"foo\xFFbar");
let string = bytes.into_string_lossy();
assert_eq!(string, "foo\u{FFFD}bar");
Source

pub unsafe fn into_string_unchecked(self) -> String

Unsafely convert this byte string into a String, without checking for valid UTF-8.

§Safety

Callers must ensure that this byte string is valid UTF-8 before calling this method. Converting a byte string into a String that is not valid UTF-8 is considered undefined behavior.

This routine is useful in performance sensitive contexts where the UTF-8 validity of the byte string is already known and it is undesirable to pay the cost of an additional UTF-8 validation check that into_string performs.

§Examples

Basic usage:

use bstr::BString;

// SAFETY: This is safe because string literals are guaranteed to be
// valid UTF-8 by the Rust compiler.
let s = unsafe { BString::from("☃βツ").into_string_unchecked() };
assert_eq!("☃βツ", s);
Source

pub fn into_os_string(self) -> Result<OsString, BString>

Converts this byte string into an OS string, in place.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this returns the original byte string if it is not valid UTF-8.

§Examples

Basic usage:

use std::ffi::OsStr;

use bstr::BString;

let bs = BString::from("foo");
let os_str = bs.into_os_string().expect("should be valid UTF-8");
assert_eq!(os_str, OsStr::new("foo"));
Source

pub fn into_os_string_lossy(self) -> OsString

Lossily converts this byte string into an OS string, in place.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this will perform a UTF-8 check and lossily convert this byte string into valid UTF-8 using the Unicode replacement codepoint.

Note that this can prevent the correct roundtripping of file paths on non-Unix systems such as Windows, where file paths are an arbitrary sequence of 16-bit integers.

§Examples

Basic usage:

use bstr::BString;

let bs = BString::from_slice(b"foo\xFFbar");
let os_str = bs.into_os_string_lossy();
assert_eq!(os_str.to_string_lossy(), "foo\u{FFFD}bar");
Source

pub fn into_path_buf(self) -> Result<PathBuf, BString>

Converts this byte string into an owned file path, in place.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this returns the original byte string if it is not valid UTF-8.

§Examples

Basic usage:

use bstr::BString;

let bs = BString::from("foo");
let path = bs.into_path_buf().expect("should be valid UTF-8");
assert_eq!(path.as_os_str(), "foo");
Source

pub fn into_path_buf_lossy(self) -> PathBuf

Lossily converts this byte string into an owned file path, in place.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this will perform a UTF-8 check and lossily convert this byte string into valid UTF-8 using the Unicode replacement codepoint.

Note that this can prevent the correct roundtripping of file paths on non-Unix systems such as Windows, where file paths are an arbitrary sequence of 16-bit integers.

§Examples

Basic usage:

use bstr::BString;

let bs = BString::from_slice(b"foo\xFFbar");
let path = bs.into_path_buf_lossy();
assert_eq!(path.to_string_lossy(), "foo\u{FFFD}bar");
Source

pub fn into_boxed_bstr(self) -> Box<BStr>

Converts this BString into a Box<BStr>.

This will drop any excess capacity.

§Examples

Basic usage:

use bstr::BString;

let s = BString::from("foobar");
let b = s.into_boxed_bstr();
assert_eq!(6, b.len());
Source

pub fn capacity(&self) -> usize

Returns this byte string’s capacity, in bytes.

§Examples

Basic usage:

use bstr::BString;

let s = BString::with_capacity(10);
assert_eq!(10, s.capacity());
Source

pub fn clear(&mut self)

Truncates this byte string, removing all contents.

The resulting byte string will always have length 0, but its capacity remains unchanged.

Source

pub fn reserve(&mut self, additional: usize)

Ensures that this BString’s capacity is at least additional bytes larger than its length.

The capacity may be increased by more than additional bytes if it chooses, to prevent frequent reallocations.

If you do not want this “at least” behavior, use the reserve_exact method instead.

§Panics

Panics if the new capacity overflows usize.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::new();
s.reserve(10);
assert!(s.capacity() >= 10);
Source

pub fn reserve_exact(&mut self, additional: usize)

Ensures that this BString’s capacity is exactly additional bytes larger than its length.

Consider using the reserve method unless you absolutely know better than the allocator.

§Panics

Panics if the new capacity overflows usize.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::new();
s.reserve_exact(10);
assert!(s.capacity() >= 10);
Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of this BString to match its length.

Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foo");
s.reserve(10);
assert!(s.capacity() >= 10);
s.shrink_to_fit();
assert_eq!(3, s.capacity());
Source

pub fn truncate(&mut self, new_len: usize)

Shortens this BString to the specified length, in bytes.

If new_len is greater than or equal to this byte string’s current length, then this has no effect.

Note that this does not panic if the result is not on a valid char boundary.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
s.truncate(3);
assert_eq!("foo", s);
Source

pub fn resize(&mut self, new_len: usize, value: u8)

Resizes this byte string in place so that the length of this byte string is equivalent to new_len.

If new_len is greater than the length of this byte string, then the byte string is extended by the difference, which each additional byte filled with the given value. If new_len is less than the length of this byte string, then it is simply truncated.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("f");
s.resize(3, b'o');
assert_eq!(s, "foo");
s.resize(1, b'o');
assert_eq!(s, "f");
Source

pub fn pop_char(&mut self) -> Option<char>

Removes the last codepoint from this BString and returns it.

If this byte string is empty, then None is returned. If the last bytes of this byte string do not correspond to a valid UTF-8 code unit sequence, then the Unicode replacement codepoint is yielded instead in accordance with the replacement codepoint substitution policy.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foo");
assert_eq!(s.pop_char(), Some('o'));
assert_eq!(s.pop_char(), Some('o'));
assert_eq!(s.pop_char(), Some('f'));
assert_eq!(s.pop_char(), None);

This shows the replacement codepoint substitution policy. Note that the first pop yields a replacement codepoint but actually removes two bytes. This is in contrast with subsequent pops when encountering \xFF since \xFF is never a valid prefix for any valid UTF-8 code unit sequence.

use bstr::BString;

let mut s = BString::from_slice(b"f\xFF\xFF\xFFoo\xE2\x98");
assert_eq!(s.pop_char(), Some('\u{FFFD}'));
assert_eq!(s.pop_char(), Some('o'));
assert_eq!(s.pop_char(), Some('o'));
assert_eq!(s.pop_char(), Some('\u{FFFD}'));
assert_eq!(s.pop_char(), Some('\u{FFFD}'));
assert_eq!(s.pop_char(), Some('\u{FFFD}'));
assert_eq!(s.pop_char(), Some('f'));
assert_eq!(s.pop_char(), None);
Source

pub fn pop_byte(&mut self) -> Option<u8>

Removes the last byte from this BString and returns it.

If this byte string is empty, then None is returned.

Note that if the last codepoint in this byte string is not ASCII, then removing the last byte could make this byte string contain invalid UTF-8.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foo");
assert_eq!(s.pop_byte(), Some(b'o'));
assert_eq!(s.pop_byte(), Some(b'o'));
assert_eq!(s.pop_byte(), Some(b'f'));
assert_eq!(s.pop_byte(), None);
Source

pub fn pop(&mut self) -> Option<char>

👎Deprecated since 0.1.1: use pop_char or pop_byte instead

DEPRECATED: Use pop_char or pop_byte instead.

Removes the last codepoint from this BString and returns it.

If this byte string is empty, then None is returned. If the last bytes of this byte string do not correspond to a valid UTF-8 code unit sequence, then the Unicode replacement codepoint is yielded instead in accordance with the replacement codepoint substitution policy.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foo");
assert_eq!(s.pop(), Some('o'));
assert_eq!(s.pop(), Some('o'));
assert_eq!(s.pop(), Some('f'));
assert_eq!(s.pop(), None);

This shows the replacement codepoint substitution policy. Note that the first pop yields a replacement codepoint but actually removes two bytes. This is in contrast with subsequent pops when encountering \xFF since \xFF is never a valid prefix for any valid UTF-8 code unit sequence.

use bstr::BString;

let mut s = BString::from_slice(b"f\xFF\xFF\xFFoo\xE2\x98");
assert_eq!(s.pop(), Some('\u{FFFD}'));
assert_eq!(s.pop(), Some('o'));
assert_eq!(s.pop(), Some('o'));
assert_eq!(s.pop(), Some('\u{FFFD}'));
assert_eq!(s.pop(), Some('\u{FFFD}'));
assert_eq!(s.pop(), Some('\u{FFFD}'));
assert_eq!(s.pop(), Some('f'));
assert_eq!(s.pop(), None);
Source

pub fn remove(&mut self, at: usize) -> char

Removes a char from this BString at the given byte position and returns it.

If the bytes at the given position do not lead to a valid UTF-8 code unit sequence, then a replacement codepoint is returned instead.

§Panics

Panics if at is larger than or equal to this byte string’s length.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foo☃bar");
assert_eq!('☃', s.remove(3));
assert_eq!("foobar", s);

This example shows how the Unicode replacement codepoint policy is used:

use bstr::BString;

let mut s = BString::from_slice(b"foo\xFFbar");
assert_eq!('\u{FFFD}', s.remove(3));
assert_eq!("foobar", s);
Source

pub fn insert_char(&mut self, at: usize, ch: char)

Inserts the given codepoint into this BString at a particular byte position.

This is an O(n) operation as it may copy a number of elements in this byte string proportional to its length.

§Panics

Panics if at is larger than the byte string’s length.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
s.insert_char(3, '☃');
assert_eq!("foo☃bar", s);
Source

pub fn insert<B: AsRef<[u8]>>(&mut self, at: usize, bytes: B)

Inserts the given byte string into this byte string at a particular byte position.

This is an O(n) operation as it may copy a number of elements in this byte string proportional to its length.

Note that the type parameter B on this method means that it can accept anything that can be cheaply converted to a &[u8]. This includes, but is not limited to, &str, &BStr and &[u8] itself.

§Panics

Panics if at is larger than the byte string’s length.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
s.insert(3, "☃☃☃");
assert_eq!("foo☃☃☃bar", s);
Source

pub fn split_off(&mut self, at: usize) -> BString

Splits this BString into two separate byte strings at the given index.

This returns a newly allocated BString, while self retans bytes [0, at) and the returned BString contains bytes [at, len).

The capacity of self does not change.

§Panics

Panics if at is beyond the end of this byte string.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
let bar = s.split_off(3);
assert_eq!(s, "foo");
assert_eq!(bar, "bar");
Source

pub fn replace_range<R, B>(&mut self, range: R, replace_with: B)
where R: RangeBounds<usize>, B: AsRef<[u8]>,

Removes the specified range in this byte string and replaces it with the given bytes. The given bytes do not need to have the same length as the range provided.

§Panics

Panics if the given range is invalid.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
s.replace_range(2..4, "xxxxx");
assert_eq!(s, "foxxxxxar");
Source

pub fn drain_bytes<R>(&mut self, range: R) -> DrainBytes<'_>
where R: RangeBounds<usize>,

Creates a draining iterator that removes the specified range in this BString and yields each of the removed bytes.

Note that the elements specified by the given range are removed regardless of whether the returned iterator is fully exhausted.

Also note that is is unspecified how many bytes are removed from the BString if the DrainBytes iterator is leaked.

§Panics

Panics if the given range is not valid.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foobar");
{
    let mut drainer = s.drain_bytes(2..4);
    assert_eq!(drainer.next(), Some(b'o'));
    assert_eq!(drainer.next(), Some(b'b'));
    assert_eq!(drainer.next(), None);
}
assert_eq!(s, "foar");

Methods from Deref<Target = BStr>§

Source

pub fn len(&self) -> usize

Returns the length, in bytes, of this byte string.

§Examples

Basic usage:

use bstr::BStr;

assert_eq!(0, BStr::new("").len());
assert_eq!(3, BStr::new("abc").len());
assert_eq!(8, BStr::new("☃βツ").len());
Source

pub fn is_empty(&self) -> bool

Returns true if and only if the length of this byte string is zero.

§Examples

Basic usage:

use bstr::BStr;

assert!(BStr::new("").is_empty());
assert!(!BStr::new("abc").is_empty());
Source

pub fn as_bytes(&self) -> &[u8]

Returns an immutable byte slice of this BStr’s contents.

§Examples

Basic usage:

use bstr::B;

let s = B("hello");

assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
Source

pub fn as_bytes_mut(&mut self) -> &mut [u8]

Returns a mutable byte slice of this BStr’s contents.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("hello");
s.as_bytes_mut()[1] = b'a';

assert_eq!(&[104, 97, 108, 108, 111], s.as_bytes());
Source

pub fn to_bstring(&self) -> BString

Create a new owned byte string from this byte string slice.

§Examples

Basic usage:

use bstr::BStr;

let s = BStr::new("abc");
let mut owned = s.to_bstring();
owned.push_char('d');
assert_eq!("abcd", owned);
Source

pub fn to_str(&self) -> Result<&str, Utf8Error>

Safely convert this byte string into a &str if it’s valid UTF-8.

If this byte string is not valid UTF-8, then an error is returned. The error returned indicates the first invalid byte found and the length of the error.

In cases where a lossy conversion to &str is acceptable, then use one of the to_str_lossy or to_str_lossy_into methods.

§Examples

Basic usage:

use bstr::{B, BString};

let s = B("☃βツ").to_str()?;
assert_eq!("☃βツ", s);

let mut bstring = BString::from("☃βツ");
bstring.push_byte(b'\xFF');
let err = bstring.to_str().unwrap_err();
assert_eq!(8, err.valid_up_to());
Source

pub unsafe fn to_str_unchecked(&self) -> &str

Unsafely convert this byte string into a &str, without checking for valid UTF-8.

§Safety

Callers must ensure that this byte string is valid UTF-8 before calling this method. Converting a byte string into a &str that is not valid UTF-8 is considered undefined behavior.

This routine is useful in performance sensitive contexts where the UTF-8 validity of the byte string is already known and it is undesirable to pay the cost of an additional UTF-8 validation check that to_str performs.

§Examples

Basic usage:

use bstr::{B, BString};

// SAFETY: This is safe because string literals are guaranteed to be
// valid UTF-8 by the Rust compiler.
let s = unsafe { B("☃βツ").to_str_unchecked() };
assert_eq!("☃βツ", s);
Source

pub fn to_str_lossy(&self) -> Cow<'_, str>

Convert this byte string to a valid UTF-8 string by replacing invalid UTF-8 bytes with the Unicode replacement codepoint (U+FFFD).

If the byte string is already valid UTF-8, then no copying or allocation is performed and a borrrowed string slice is returned. If the byte string is not valid UTF-8, then an owned string buffer is returned with invalid bytes replaced by the replacement codepoint.

This method uses the “substitution of maximal subparts” (Unicode Standard, Chapter 3, Section 9) strategy for inserting the replacement codepoint. Specifically, a replacement codepoint is inserted whenever a byte is found that cannot possibly lead to a valid code unit sequence. If there were previous bytes that represented a prefix of a well-formed code unit sequence, then all of those bytes are substituted with a single replacement codepoint. The “substitution of maximal subparts” strategy is the same strategy used by W3C’s Encoding standard. For a more precise description of the maximal subpart strategy, see the Unicode Standard, Chapter 3, Section 9. See also Public Review Issue #121.

N.B. Rust’s standard library also appears to use the same strategy, but it does not appear to be an API guarantee.

§Examples

Basic usage:

use std::borrow::Cow;
use bstr::BString;

let mut bstring = BString::from("☃βツ");
assert_eq!(Cow::Borrowed("☃βツ"), bstring.to_str_lossy());

// Add a byte that makes the sequence invalid.
bstring.push_byte(b'\xFF');
assert_eq!(Cow::Borrowed("☃βツ\u{FFFD}"), bstring.to_str_lossy());

This demonstrates the “maximal subpart” substitution logic.

use bstr::B;

// \x61 is the ASCII codepoint for 'a'.
// \xF1\x80\x80 is a valid 3-byte code unit prefix.
// \xE1\x80 is a valid 2-byte code unit prefix.
// \xC2 is a valid 1-byte code unit prefix.
// \x62 is the ASCII codepoint for 'b'.
//
// In sum, each of the prefixes is replaced by a single replacement
// codepoint since none of the prefixes are properly completed. This
// is in contrast to other strategies that might insert a replacement
// codepoint for every single byte.
let bs = B(b"\x61\xF1\x80\x80\xE1\x80\xC2\x62");
assert_eq!("a\u{FFFD}\u{FFFD}\u{FFFD}b", bs.to_str_lossy());
Source

pub fn to_str_lossy_into(&self, dest: &mut String)

Copy the contents of this byte string into the given owned string buffer, while replacing invalid UTF-8 code unit sequences with the Unicode replacement codepoint (U+FFFD).

This method uses the same “substitution of maximal subparts” strategy for inserting the replacement codepoint as the to_str_lossy method.

This routine is useful for amortizing allocation. However, unlike to_str_lossy, this routine will always copy the contents of this byte string into the destination buffer, even if this byte string is valid UTF-8.

§Examples

Basic usage:

use std::borrow::Cow;
use bstr::BString;

let mut bstring = BString::from("☃βツ");
// Add a byte that makes the sequence invalid.
bstring.push_byte(b'\xFF');

let mut dest = String::new();
bstring.to_str_lossy_into(&mut dest);
assert_eq!("☃βツ\u{FFFD}", dest);
Source

pub fn to_os_str(&self) -> Result<&OsStr, Utf8Error>

Create an OS string slice from this byte string.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this returns a UTF-8 decoding error if this byte string is not valid UTF-8. (For example, on Windows, file paths are allowed to be a sequence of arbitrary 16-bit integers. There is no obvious mapping from an arbitrary sequence of 8-bit integers to an arbitrary sequence of 16-bit integers.)

§Examples

Basic usage:

use bstr::B;

let bs = B("foo");
let os_str = bs.to_os_str().expect("should be valid UTF-8");
assert_eq!(os_str, "foo");
Source

pub fn to_os_str_lossy(&self) -> Cow<'_, OsStr>

Lossily create an OS string slice from this byte string.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this will perform a UTF-8 check and lossily convert this byte string into valid UTF-8 using the Unicode replacement codepoint.

Note that this can prevent the correct roundtripping of file paths on non-Unix systems such as Windows, where file paths are an arbitrary sequence of 16-bit integers.

§Examples

Basic usage:

use bstr::B;

let bs = B(b"foo\xFFbar");
let os_str = bs.to_os_str_lossy();
assert_eq!(os_str.to_string_lossy(), "foo\u{FFFD}bar");
Source

pub fn to_path(&self) -> Result<&Path, Utf8Error>

Create a path slice from this byte string.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this returns a UTF-8 decoding error if this byte string is not valid UTF-8. (For example, on Windows, file paths are allowed to be a sequence of arbitrary 16-bit integers. There is no obvious mapping from an arbitrary sequence of 8-bit integers to an arbitrary sequence of 16-bit integers.)

§Examples

Basic usage:

use bstr::B;

let bs = B("foo");
let path = bs.to_path().expect("should be valid UTF-8");
assert_eq!(path.as_os_str(), "foo");
Source

pub fn to_path_lossy(&self) -> Cow<'_, Path>

Lossily create a path slice from this byte string.

On Unix, this always succeeds and is zero cost. On non-Unix systems, this will perform a UTF-8 check and lossily convert this byte string into valid UTF-8 using the Unicode replacement codepoint.

Note that this can prevent the correct roundtripping of file paths on non-Unix systems such as Windows, where file paths are an arbitrary sequence of 16-bit integers.

§Examples

Basic usage:

use bstr::B;

let bs = B(b"foo\xFFbar");
let path = bs.to_path_lossy();
assert_eq!(path.to_string_lossy(), "foo\u{FFFD}bar");
Source

pub fn repeat(&self, n: usize) -> BString

Create a new BString by repeating this byte string n times.

§Panics

This function panics if the capacity of the new BString would overflow.

§Examples

Basic usage:

use bstr::B;

assert_eq!("foofoofoofoo", B("foo").repeat(4));
assert_eq!("", B("foo").repeat(0));
Source

pub fn contains<B: AsRef<[u8]>>(&self, needle: B) -> bool

Returns true if and only if this byte string contains the given needle.

§Examples

Basic usage:

use bstr::B;

assert!(B("foo bar").contains("foo"));
assert!(B("foo bar").contains("bar"));
assert!(!B("foo").contains("foobar"));
Source

pub fn starts_with<B: AsRef<[u8]>>(&self, prefix: B) -> bool

Returns true if and only if this byte string has the given prefix.

§Examples

Basic usage:

use bstr::B;

assert!(B("foo bar").starts_with("foo"));
assert!(!B("foo bar").starts_with("bar"));
assert!(!B("foo").starts_with("foobar"));
Source

pub fn ends_with<B: AsRef<[u8]>>(&self, suffix: B) -> bool

Returns true if and only if this byte string has the given suffix.

§Examples

Basic usage:

use bstr::B;

assert!(B("foo bar").ends_with("bar"));
assert!(!B("foo bar").ends_with("foo"));
assert!(!B("bar").ends_with("foobar"));
Source

pub fn find<B: AsRef<[u8]>>(&self, needle: B) -> Option<usize>

Returns the index of the first occurrence of the given needle.

The needle may be any type that can be cheaply converted into a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

Note that if you’re are searching for the same needle in many different small haystacks, it may be faster to initialize a Finder once, and reuse it for each search.

§Complexity

This routine is guaranteed to have worst case linear time complexity with respect to both the needle and the haystack. That is, this runs in O(needle.len() + haystack.len()) time.

This routine is also guaranteed to have worst case constant space complexity.

§Examples

Basic usage:

use bstr::B;

let s = B("foo bar baz");
assert_eq!(Some(0), s.find("foo"));
assert_eq!(Some(4), s.find("bar"));
assert_eq!(None, s.find("quux"));
Source

pub fn rfind<B: AsRef<[u8]>>(&self, needle: B) -> Option<usize>

Returns the index of the last occurrence of the given needle.

The needle may be any type that can be cheaply converted into a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

Note that if you’re are searching for the same needle in many different small haystacks, it may be faster to initialize a FinderReverse once, and reuse it for each search.

§Complexity

This routine is guaranteed to have worst case linear time complexity with respect to both the needle and the haystack. That is, this runs in O(needle.len() + haystack.len()) time.

This routine is also guaranteed to have worst case constant space complexity.

§Examples

Basic usage:

use bstr::B;

let s = B("foo bar baz");
assert_eq!(Some(0), s.rfind("foo"));
assert_eq!(Some(4), s.rfind("bar"));
assert_eq!(Some(8), s.rfind("ba"));
assert_eq!(None, s.rfind("quux"));
Source

pub fn find_iter<'a, B: ?Sized + AsRef<[u8]>>( &'a self, needle: &'a B, ) -> Find<'a>

Returns an iterator of the non-overlapping occurrences of the given needle. The iterator yields byte offset positions indicating the start of each match.

§Complexity

This routine is guaranteed to have worst case linear time complexity with respect to both the needle and the haystack. That is, this runs in O(needle.len() + haystack.len()) time.

This routine is also guaranteed to have worst case constant space complexity.

§Examples

Basic usage:

use bstr::B;

let s = B("foo bar foo foo quux foo");
let matches: Vec<usize> = s.find_iter("foo").collect();
assert_eq!(matches, vec![0, 8, 12, 21]);

An empty string matches at every position, including the position immediately following the last byte:

use bstr::B;

let matches: Vec<usize> = B("foo").find_iter("").collect();
assert_eq!(matches, vec![0, 1, 2, 3]);

let matches: Vec<usize> = B("").find_iter("").collect();
assert_eq!(matches, vec![0]);
Source

pub fn rfind_iter<'a, B: ?Sized + AsRef<[u8]>>( &'a self, needle: &'a B, ) -> FindReverse<'a>

Returns an iterator of the non-overlapping occurrences of the given needle in reverse. The iterator yields byte offset positions indicating the start of each match.

§Complexity

This routine is guaranteed to have worst case linear time complexity with respect to both the needle and the haystack. That is, this runs in O(needle.len() + haystack.len()) time.

This routine is also guaranteed to have worst case constant space complexity.

§Examples

Basic usage:

use bstr::B;

let s = B("foo bar foo foo quux foo");
let matches: Vec<usize> = s.rfind_iter("foo").collect();
assert_eq!(matches, vec![21, 12, 8, 0]);

An empty string matches at every position, including the position immediately following the last byte:

use bstr::B;

let matches: Vec<usize> = B("foo").rfind_iter("").collect();
assert_eq!(matches, vec![3, 2, 1, 0]);

let matches: Vec<usize> = B("").rfind_iter("").collect();
assert_eq!(matches, vec![0]);
Source

pub fn find_byte(&self, byte: u8) -> Option<usize>

Returns the index of the first occurrence of the given byte. If the byte does not occur in this byte string, then None is returned.

§Examples

Basic usage:

use bstr::B;

assert_eq!(Some(10), B("foo bar baz").find_byte(b'z'));
assert_eq!(None, B("foo bar baz").find_byte(b'y'));
Source

pub fn rfind_byte(&self, byte: u8) -> Option<usize>

Returns the index of the last occurrence of the given byte. If the byte does not occur in this byte string, then None is returned.

§Examples

Basic usage:

use bstr::B;

assert_eq!(Some(10), B("foo bar baz").rfind_byte(b'z'));
assert_eq!(None, B("foo bar baz").rfind_byte(b'y'));
Source

pub fn find_char(&self, ch: char) -> Option<usize>

Returns the index of the first occurrence of the given codepoint. If the codepoint does not occur in this byte string, then None is returned.

Note that if one searches for the replacement codepoint, \u{FFFD}, then only explicit occurrences of that encoding will be found. Invalid UTF-8 sequences will not be matched.

§Examples

Basic usage:

use bstr::B;

assert_eq!(Some(10), B("foo bar baz").find_char('z'));
assert_eq!(Some(4), B("αβγγδ").find_char('γ'));
assert_eq!(None, B("foo bar baz").find_char('y'));
Source

pub fn rfind_char(&self, ch: char) -> Option<usize>

Returns the index of the last occurrence of the given codepoint. If the codepoint does not occur in this byte string, then None is returned.

Note that if one searches for the replacement codepoint, \u{FFFD}, then only explicit occurrences of that encoding will be found. Invalid UTF-8 sequences will not be matched.

§Examples

Basic usage:

use bstr::B;

assert_eq!(Some(10), B("foo bar baz").rfind_char('z'));
assert_eq!(Some(6), B("αβγγδ").rfind_char('γ'));
assert_eq!(None, B("foo bar baz").rfind_char('y'));
Source

pub fn fields(&self) -> Fields<'_>

Returns an iterator over the fields in a byte string, separated by contiguous whitespace.

§Example

Basic usage:

use bstr::{B, BStr};

let s = B("  foo\tbar\t\u{2003}\nquux   \n");
let fields: Vec<&BStr> = s.fields().collect();
assert_eq!(fields, vec!["foo", "bar", "quux"]);

A byte string consisting of just whitespace yields no elements:

use bstr::B;

assert_eq!(0, B("  \n\t\u{2003}\n  \t").fields().count());
Source

pub fn fields_with<F: FnMut(char) -> bool>(&self, f: F) -> FieldsWith<'_, F>

Returns an iterator over the fields in a byte string, separated by contiguous codepoints satisfying the given predicate.

If this byte

§Example

Basic usage:

use bstr::{B, BStr};

let s = B("123foo999999bar1quux123456");
let fields: Vec<&BStr> = s.fields_with(|c| c.is_numeric()).collect();
assert_eq!(fields, vec!["foo", "bar", "quux"]);

A byte string consisting of all codepoints satisfying the predicate yields no elements:

use bstr::B;

assert_eq!(0, B("1911354563").fields_with(|c| c.is_numeric()).count());
Source

pub fn split<'a, B: ?Sized + AsRef<[u8]>>( &'a self, splitter: &'a B, ) -> Split<'a>

Returns an iterator over substrings of this byte string, separated by the given byte string. Each element yielded is guaranteed not to include the splitter substring.

The splitter may be any type that can be cheaply converted into a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

§Examples

Basic usage:

use bstr::{B, BStr};

let x: Vec<&BStr> = B("Mary had a little lamb").split(" ").collect();
assert_eq!(x, vec!["Mary", "had", "a", "little", "lamb"]);

let x: Vec<&BStr> = B("").split("X").collect();
assert_eq!(x, vec![""]);

let x: Vec<&BStr> = B("lionXXtigerXleopard").split("X").collect();
assert_eq!(x, vec!["lion", "", "tiger", "leopard"]);

let x: Vec<&BStr> = B("lion::tiger::leopard").split("::").collect();
assert_eq!(x, vec!["lion", "tiger", "leopard"]);

If a string contains multiple contiguous separators, you will end up with empty strings yielded by the iterator:

use bstr::{B, BStr};

let x: Vec<&BStr> = B("||||a||b|c").split("|").collect();
assert_eq!(x, vec!["", "", "", "", "a", "", "b", "c"]);

let x: Vec<&BStr> = B("(///)").split("/").collect();
assert_eq!(x, vec!["(", "", "", ")"]);

Separators at the start or end of a string are neighbored by empty strings.

use bstr::{B, BStr};

let x: Vec<&BStr> = B("010").split("0").collect();
assert_eq!(x, vec!["", "1", ""]);

When the empty string is used as a separator, it splits every byte in the byte string, along with the beginning and end of the byte string.

use bstr::{B, BStr};

let x: Vec<&BStr> = B("rust").split("").collect();
assert_eq!(x, vec!["", "r", "u", "s", "t", ""]);

// Splitting by an empty string is not UTF-8 aware. Elements yielded
// may not be valid UTF-8!
let x: Vec<&BStr> = B("☃").split("").collect();
assert_eq!(x, vec![B(""), B(b"\xE2"), B(b"\x98"), B(b"\x83"), B("")]);

Contiguous separators, especially whitespace, can lead to possibly surprising behavior. For example, this code is correct:

use bstr::{B, BStr};

let x: Vec<&BStr> = B("    a  b c").split(" ").collect();
assert_eq!(x, vec!["", "", "", "", "a", "", "b", "c"]);

It does not give you ["a", "b", "c"]. For that behavior, use fields instead.

Source

pub fn rsplit<'a, B: ?Sized + AsRef<[u8]>>( &'a self, splitter: &'a B, ) -> SplitReverse<'a>

Returns an iterator over substrings of this byte string, separated by the given byte string, in reverse. Each element yielded is guaranteed not to include the splitter substring.

The splitter may be any type that can be cheaply converted into a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

§Examples

Basic usage:

use bstr::{B, BStr};

let x: Vec<&BStr> = B("Mary had a little lamb").rsplit(" ").collect();
assert_eq!(x, vec!["lamb", "little", "a", "had", "Mary"]);

let x: Vec<&BStr> = B("").rsplit("X").collect();
assert_eq!(x, vec![""]);

let x: Vec<&BStr> = B("lionXXtigerXleopard").rsplit("X").collect();
assert_eq!(x, vec!["leopard", "tiger", "", "lion"]);

let x: Vec<&BStr> = B("lion::tiger::leopard").rsplit("::").collect();
assert_eq!(x, vec!["leopard", "tiger", "lion"]);

If a string contains multiple contiguous separators, you will end up with empty strings yielded by the iterator:

use bstr::{B, BStr};

let x: Vec<&BStr> = B("||||a||b|c").rsplit("|").collect();
assert_eq!(x, vec!["c", "b", "", "a", "", "", "", ""]);

let x: Vec<&BStr> = B("(///)").rsplit("/").collect();
assert_eq!(x, vec![")", "", "", "("]);

Separators at the start or end of a string are neighbored by empty strings.

use bstr::{B, BStr};

let x: Vec<&BStr> = B("010").rsplit("0").collect();
assert_eq!(x, vec!["", "1", ""]);

When the empty string is used as a separator, it splits every byte in the byte string, along with the beginning and end of the byte string.

use bstr::{B, BStr};

let x: Vec<&BStr> = B("rust").rsplit("").collect();
assert_eq!(x, vec!["", "t", "s", "u", "r", ""]);

// Splitting by an empty string is not UTF-8 aware. Elements yielded
// may not be valid UTF-8!
let x: Vec<&BStr> = B("☃").rsplit("").collect();
assert_eq!(x, vec![B(""), B(b"\x83"), B(b"\x98"), B(b"\xE2"), B("")]);

Contiguous separators, especially whitespace, can lead to possibly surprising behavior. For example, this code is correct:

use bstr::{B, BStr};

let x: Vec<&BStr> = B("    a  b c").rsplit(" ").collect();
assert_eq!(x, vec!["c", "b", "", "a", "", "", "", ""]);

It does not give you ["a", "b", "c"].

Source

pub fn splitn<'a, B: ?Sized + AsRef<[u8]>>( &'a self, limit: usize, splitter: &'a B, ) -> SplitN<'a>

Returns an iterator of at most limit substrings of this byte string, separated by the given byte string. If limit substrings are yielded, then the last substring will contain the remainder of this byte string.

The splitter may be any type that can be cheaply converted into a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

§Examples

Basic usage:

use bstr::{B, BStr};

let x: Vec<_> = B("Mary had a little lamb").splitn(3, " ").collect();
assert_eq!(x, vec!["Mary", "had", "a little lamb"]);

let x: Vec<_> = B("").splitn(3, "X").collect();
assert_eq!(x, vec![""]);

let x: Vec<_> = B("lionXXtigerXleopard").splitn(3, "X").collect();
assert_eq!(x, vec!["lion", "", "tigerXleopard"]);

let x: Vec<_> = B("lion::tiger::leopard").splitn(2, "::").collect();
assert_eq!(x, vec!["lion", "tiger::leopard"]);

let x: Vec<_> = B("abcXdef").splitn(1, "X").collect();
assert_eq!(x, vec!["abcXdef"]);

let x: Vec<_> = B("abcXdef").splitn(0, "X").collect();
assert!(x.is_empty());
Source

pub fn rsplitn<'a, B: ?Sized + AsRef<[u8]>>( &'a self, limit: usize, splitter: &'a B, ) -> SplitNReverse<'a>

Returns an iterator of at most limit substrings of this byte string, separated by the given byte string, in reverse. If limit substrings are yielded, then the last substring will contain the remainder of this byte string.

The splitter may be any type that can be cheaply converted into a &[u8]. This includes, but is not limited to, &str, &BStr, and of course, &[u8] itself.

§Examples

Basic usage:

use bstr::{B, BStr};

let x: Vec<_> = B("Mary had a little lamb").rsplitn(3, " ").collect();
assert_eq!(x, vec!["lamb", "little", "Mary had a"]);

let x: Vec<_> = B("").rsplitn(3, "X").collect();
assert_eq!(x, vec![""]);

let x: Vec<_> = B("lionXXtigerXleopard").rsplitn(3, "X").collect();
assert_eq!(x, vec!["leopard", "tiger", "lionX"]);

let x: Vec<_> = B("lion::tiger::leopard").rsplitn(2, "::").collect();
assert_eq!(x, vec!["leopard", "lion::tiger"]);

let x: Vec<_> = B("abcXdef").rsplitn(1, "X").collect();
assert_eq!(x, vec!["abcXdef"]);

let x: Vec<_> = B("abcXdef").rsplitn(0, "X").collect();
assert!(x.is_empty());
Source

pub fn replace<N: AsRef<[u8]>, R: AsRef<[u8]>>( &self, needle: N, replacement: R, ) -> BString

Replace all matches of the given needle with the given replacement, and the result as a new BString.

This routine is useful as a convenience. If you need to reuse an allocation, use replace_into instead.

§Examples

Basic usage:

use bstr::B;

let s = B("this is old").replace("old", "new");
assert_eq!(s, "this is new");

When the pattern doesn’t match:

use bstr::B;

let s = B("this is old").replace("nada nada", "limonada");
assert_eq!(s, "this is old");

When the needle is an empty string:

use bstr::B;

let s = B("foo").replace("", "Z");
assert_eq!(s, "ZfZoZoZ");
Source

pub fn replacen<N: AsRef<[u8]>, R: AsRef<[u8]>>( &self, needle: N, replacement: R, limit: usize, ) -> BString

Replace up to limit matches of the given needle with the given replacement, and the result as a new BString.

This routine is useful as a convenience. If you need to reuse an allocation, use replacen_into instead.

§Examples

Basic usage:

use bstr::B;

let s = B("foofoo").replacen("o", "z", 2);
assert_eq!(s, "fzzfoo");

When the pattern doesn’t match:

use bstr::B;

let s = B("foofoo").replacen("a", "z", 2);
assert_eq!(s, "foofoo");

When the needle is an empty string:

use bstr::B;

let s = B("foo").replacen("", "Z", 2);
assert_eq!(s, "ZfZoo");
Source

pub fn replace_into<N: AsRef<[u8]>, R: AsRef<[u8]>>( &self, needle: N, replacement: R, dest: &mut BString, )

Replace all matches of the given needle with the given replacement, and write the result into the provided BString.

This does not clear dest before writing to it.

This routine is useful for reusing allocation. For a more convenient API, use replace instead.

§Examples

Basic usage:

use bstr::{B, BString};

let s = B("this is old");

let mut dest = BString::new();
s.replace_into("old", "new", &mut dest);
assert_eq!(dest, "this is new");

When the pattern doesn’t match:

use bstr::{B, BString};

let s = B("this is old");

let mut dest = BString::new();
s.replace_into("nada nada", "limonada", &mut dest);
assert_eq!(dest, "this is old");

When the needle is an empty string:

use bstr::{B, BString};

let s = B("foo");

let mut dest = BString::new();
s.replace_into("", "Z", &mut dest);
assert_eq!(dest, "ZfZoZoZ");
Source

pub fn replacen_into<N: AsRef<[u8]>, R: AsRef<[u8]>>( &self, needle: N, replacement: R, limit: usize, dest: &mut BString, )

Replace up to limit matches of the given needle with the given replacement, and write the result into the provided BString.

This does not clear dest before writing to it.

This routine is useful for reusing allocation. For a more convenient API, use replace instead.

§Examples

Basic usage:

use bstr::{B, BString};

let s = B("foofoo");

let mut dest = BString::new();
s.replacen_into("o", "z", 2, &mut dest);
assert_eq!(dest, "fzzfoo");

When the pattern doesn’t match:

use bstr::{B, BString};

let s = B("foofoo");

let mut dest = BString::new();
s.replacen_into("a", "z", 2, &mut dest);
assert_eq!(dest, "foofoo");

When the needle is an empty string:

use bstr::{B, BString};

let s = B("foo");

let mut dest = BString::new();
s.replacen_into("", "Z", 2, &mut dest);
assert_eq!(dest, "ZfZoo");
Source

pub fn bytes(&self) -> Bytes<'_>

Returns an iterator over the bytes in this byte string.

§Examples

Basic usage:

use bstr::B;

let bs = B("foobar");
let bytes: Vec<u8> = bs.bytes().collect();
assert_eq!(bytes, bs);
Source

pub fn chars(&self) -> Chars<'_>

Returns an iterator over the Unicode scalar values in this byte string. If invalid UTF-8 is encountered, then the Unicode replacement codepoint is yielded instead.

§Examples

Basic usage:

use bstr::B;

let bs = B(b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61");
let chars: Vec<char> = bs.chars().collect();
assert_eq!(vec!['☃', '\u{FFFD}', '𝞃', '\u{FFFD}', 'a'], chars);

Codepoints can also be iterated over in reverse:

use bstr::B;

let bs = B(b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61");
let chars: Vec<char> = bs.chars().rev().collect();
assert_eq!(vec!['a', '\u{FFFD}', '𝞃', '\u{FFFD}', '☃'], chars);
Source

pub fn char_indices(&self) -> CharIndices<'_>

Returns an iterator over the Unicode scalar values in this byte string along with their starting and ending byte index positions. If invalid UTF-8 is encountered, then the Unicode replacement codepoint is yielded instead.

Note that this is slightly different from the CharIndices iterator provided by the standard library. Aside from working on possibly invalid UTF-8, this iterator provides both the corresponding starting and ending byte indices of each codepoint yielded. The ending position is necessary to slice the original byte string when invalid UTF-8 bytes are converted into a Unicode replacement codepoint, since a single replacement codepoint can substitute anywhere from 1 to 3 invalid bytes (inclusive).

§Examples

Basic usage:

use bstr::B;

let bs = B(b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61");
let chars: Vec<(usize, usize, char)> = bs.char_indices().collect();
assert_eq!(chars, vec![
    (0, 3, '☃'),
    (3, 4, '\u{FFFD}'),
    (4, 8, '𝞃'),
    (8, 10, '\u{FFFD}'),
    (10, 11, 'a'),
]);

Codepoints can also be iterated over in reverse:

use bstr::B;

let bs = B(b"\xE2\x98\x83\xFF\xF0\x9D\x9E\x83\xE2\x98\x61");
let chars: Vec<(usize, usize, char)> = bs
    .char_indices()
    .rev()
    .collect();
assert_eq!(chars, vec![
    (10, 11, 'a'),
    (8, 10, '\u{FFFD}'),
    (4, 8, '𝞃'),
    (3, 4, '\u{FFFD}'),
    (0, 3, '☃'),
]);
Source

pub fn lines(&self) -> Lines<'_>

An iterator over all lines in a byte string, without their terminators.

For this iterator, the only line terminators recognized are \r\n and \n.

§Examples

Basic usage:

use bstr::{B, BStr};

let s = B("\
foo

bar\r
baz


quux");
let lines: Vec<&BStr> = s.lines().collect();
assert_eq!(lines, vec![
    "foo", "", "bar", "baz", "", "", "quux",
]);
Source

pub fn lines_with_terminator(&self) -> LinesWithTerminator<'_>

An iterator over all lines in a byte string, including their terminators.

For this iterator, the only line terminator recognized is \n. (Since line terminators are included, this also handles \r\n line endings.)

Line terminators are only included if they are present in the original byte string. For example, the last line in a byte string may not end with a line terminator.

Concatenating all elements yielded by this iterator is guaranteed to yield the original byte string.

§Examples

Basic usage:

use bstr::{B, BStr};

let s = B("\
foo

bar\r
baz


quux");
let lines: Vec<&BStr> = s.lines_with_terminator().collect();
assert_eq!(lines, vec![
    "foo\n", "\n", "bar\r\n", "baz\n", "\n", "\n", "quux",
]);
Source

pub fn trim_start(&self) -> &BStr

Return a byte string slice with leading whitespace removed.

Whitespace is defined according to the terms of the White_Space Unicode property.

§Examples

Basic usage:

use bstr::B;

let s = B(" foo\tbar\t\u{2003}\n");
assert_eq!(s.trim_start(), "foo\tbar\t\u{2003}\n");
Source

pub fn trim_end(&self) -> &BStr

Return a byte string slice with trailing whitespace removed.

Whitespace is defined according to the terms of the White_Space Unicode property.

§Examples

Basic usage:

use bstr::B;

let s = B(" foo\tbar\t\u{2003}\n");
assert_eq!(s.trim_end(), " foo\tbar");
Source

pub fn trim_with<F: FnMut(char) -> bool>(&self, trim: F) -> &BStr

Return a byte string slice with leading and trailing characters satisfying the given predicate removed.

§Examples

Basic usage:

use bstr::B;

let s = B("123foo5bar789");
assert_eq!(s.trim_with(|c| c.is_numeric()), "foo5bar");
Source

pub fn trim_start_with<F: FnMut(char) -> bool>(&self, trim: F) -> &BStr

Return a byte string slice with leading characters satisfying the given predicate removed.

§Examples

Basic usage:

use bstr::B;

let s = B("123foo5bar789");
assert_eq!(s.trim_start_with(|c| c.is_numeric()), "foo5bar789");
Source

pub fn trim_end_with<F: FnMut(char) -> bool>(&self, trim: F) -> &BStr

Return a byte string slice with trailing characters satisfying the given predicate removed.

§Examples

Basic usage:

use bstr::B;

let s = B("123foo5bar");
assert_eq!(s.trim_end_with(|c| c.is_numeric()), "123foo5bar");
Source

pub fn to_ascii_lowercase(&self) -> BString

Returns a new BString containing the ASCII lowercase equivalent of this byte string.

In this case, lowercase is only defined in ASCII letters. Namely, the letters A-Z are converted to a-z. All other bytes remain unchanged. In particular, the length of the byte string returned is always equivalent to the length of this byte string.

If you’d like to reuse an allocation for performance reasons, then use make_ascii_lowercase to perform the conversion in place.

§Examples

Basic usage:

use bstr::{B, BString};

let s = B("HELLO Β");
assert_eq!("hello Β", s.to_ascii_lowercase());

Invalid UTF-8 remains as is:

use bstr::{B, BString};

let s = B(b"FOO\xFFBAR\xE2\x98BAZ");
assert_eq!(B(b"foo\xFFbar\xE2\x98baz"), s.to_ascii_lowercase());
Source

pub fn make_ascii_lowercase(&mut self)

Convert this byte string to its lowercase ASCII equivalent in place.

In this case, lowercase is only defined in ASCII letters. Namely, the letters A-Z are converted to a-z. All other bytes remain unchanged.

If you don’t need to do the conversion in place and instead prefer convenience, then use to_ascii_lowercase instead.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("HELLO Β");
s.make_ascii_lowercase();
assert_eq!("hello Β", s);

Invalid UTF-8 remains as is:

use bstr::{B, BString};

let mut s = BString::from_slice(b"FOO\xFFBAR\xE2\x98BAZ");
s.make_ascii_lowercase();
assert_eq!(B(b"foo\xFFbar\xE2\x98baz"), s);
Source

pub fn to_ascii_uppercase(&self) -> BString

Returns a new BString containing the ASCII uppercase equivalent of this byte string.

In this case, uppercase is only defined in ASCII letters. Namely, the letters a-z are converted to A-Z. All other bytes remain unchanged. In particular, the length of the byte string returned is always equivalent to the length of this byte string.

If you’d like to reuse an allocation for performance reasons, then use make_ascii_uppercase to perform the conversion in place.

§Examples

Basic usage:

use bstr::{B, BString};

let s = B("hello β");
assert_eq!("HELLO β", s.to_ascii_uppercase());

Invalid UTF-8 remains as is:

use bstr::{B, BString};

let s = B(b"foo\xFFbar\xE2\x98baz");
assert_eq!(B(b"FOO\xFFBAR\xE2\x98BAZ"), s.to_ascii_uppercase());
Source

pub fn make_ascii_uppercase(&mut self)

Convert this byte string to its uppercase ASCII equivalent in place.

In this case, uppercase is only defined in ASCII letters. Namely, the letters a-z are converted to A-Z. All other bytes remain unchanged.

If you don’t need to do the conversion in place and instead prefer convenience, then use to_ascii_uppercase instead.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("hello β");
s.make_ascii_uppercase();
assert_eq!("HELLO β", s);

Invalid UTF-8 remains as is:

use bstr::{B, BString};

let mut s = BString::from_slice(b"foo\xFFbar\xE2\x98baz");
s.make_ascii_uppercase();
assert_eq!(B(b"FOO\xFFBAR\xE2\x98BAZ"), s);
Source

pub fn reverse_bytes(&mut self)

Reverse the bytes in this string, in place.

Note that this is not necessarily a well formed operation. For example, if this byte string contains valid UTF-8 that isn’t ASCII, then reversing the string will likely result in invalid UTF-8 and otherwise non-sensical content.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("hello");
s.reverse_bytes();
assert_eq!(s, "olleh");
Source

pub fn reverse_chars(&mut self)

Reverse the codepoints in this string, in place.

If this byte string is valid UTF-8, then its reversal by codepoint is also guaranteed to be valid UTF-8.

This operation is equivalent to the following, but without allocating:

use bstr::BString;

let mut s = BString::from("foo☃bar");

let mut chars: Vec<char> = s.chars().collect();
chars.reverse();

let reversed: String = chars.into_iter().collect();
assert_eq!(reversed, "rab☃oof");

Note that this is not necessarily a well formed operation. For example, if this byte string contains grapheme clusters with more than one codepoint, then those grapheme clusters will not necessarily be preserved. If you’d like to preserve grapheme clusters, then use reverse_graphemes instead.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("foo☃bar");
s.reverse_chars();
assert_eq!(s, "rab☃oof");

This example shows that not all reversals lead to a well formed string. For example, in this case, combining marks are used to put accents over some letters, and those accent marks must appear after the codepoints they modify.

use bstr::{B, BString};

let mut s = BString::from("résumé");
s.reverse_chars();
assert_eq!(s, B(b"\xCC\x81emus\xCC\x81er"));

A word of warning: the above example relies on the fact that résumé is in decomposed normal form, which means there are separate codepoints for the accents above e. If it is instead in composed normal form, then the example works:

use bstr::{B, BString};

let mut s = BString::from("résumé");
s.reverse_chars();
assert_eq!(s, "émusér");

The point here is to be cautious and not assume that just because reverse_chars works in one case, that it therefore works in all cases.

Source

pub fn is_ascii(&self) -> bool

Returns true if and only if every byte in this byte string is ASCII.

ASCII is an encoding that defines 128 codepoints. A byte corresponds to an ASCII codepoint if and only if it is in the inclusive range [0, 127].

§Examples

Basic usage:

use bstr::B;

assert!(B("abc").is_ascii());
assert!(!B("☃βツ").is_ascii());
assert!(!B(b"\xFF").is_ascii());
Source

pub fn is_utf8(&self) -> bool

Returns true if and only if the entire byte string is valid UTF-8.

If you need location information about where a byte string’s first invalid UTF-8 byte is, then use the to_str method.

§Examples

Basic usage:

use bstr::B;

assert!(B("abc").is_utf8());
assert!(B("☃βツ").is_utf8());
// invalid bytes
assert!(!B(b"abc\xFF").is_utf8());
// surrogate encoding
assert!(!B(b"\xED\xA0\x80").is_utf8());
// incomplete sequence
assert!(!B(b"\xF0\x9D\x9Ca").is_utf8());
// overlong sequence
assert!(!B(b"\xF0\x82\x82\xAC").is_utf8());
Source

pub fn split_at(&self, at: usize) -> (&BStr, &BStr)

Divides this byte string into two at an index.

The first byte string will contain all bytes at indices [0, at), and the second byte string will contain all bytes at indices [at, len).

§Panics

Panics if at > len.

§Examples

Basic usage:

use bstr::B;

assert_eq!(B("foobar").split_at(3), (B("foo"), B("bar")));
assert_eq!(B("foobar").split_at(0), (B(""), B("foobar")));
assert_eq!(B("foobar").split_at(6), (B("foobar"), B("")));
Source

pub fn split_at_mut(&mut self, at: usize) -> (&mut BStr, &mut BStr)

Divides this mutable byte string into two at an index.

The first byte string will contain all bytes at indices [0, at), and the second byte string will contain all bytes at indices [at, len).

§Panics

Panics if at > len.

§Examples

Basic usage:

use bstr::{B, BString};

let mut b = BString::from("foobar");
{
    let (left, right) = b.split_at_mut(3);
    left[2] = b'z';
    right[2] = b'z';
}
assert_eq!(b, B("fozbaz"));
Source

pub fn get<I: SliceIndex>(&self, at: I) -> Option<&I::Output>

Retrieve a reference to a byte or a subslice, depending on the type of the index given.

If given a position, this returns a reference to the byte at that position, if it exists.

If given a range, this returns the slice of bytes corresponding to that range in this byte string.

In the case of invalid indices, this returns None.

§Examples

Basic usage:

use bstr::B;

let s = B("baz");
assert_eq!(s.get(1), Some(&b'a'));
assert_eq!(s.get(0..2), Some(B("ba")));
assert_eq!(s.get(2..), Some(B("z")));
assert_eq!(s.get(1..=2), Some(B("az")));
Source

pub fn get_mut<I: SliceIndex>(&mut self, at: I) -> Option<&mut I::Output>

Retrieve a mutable reference to a byte or a subslice, depending on the type of the index given.

If given a position, this returns a reference to the byte at that position, if it exists.

If given a range, this returns the slice of bytes corresponding to that range in this byte string.

In the case of invalid indices, this returns None.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("baz");
if let Some(mut slice) = s.get_mut(1..) {
    slice[0] = b'o';
    slice[1] = b'p';
}
assert_eq!(s, "bop");
Source

pub unsafe fn get_unchecked<I: SliceIndex>(&self, at: I) -> &I::Output

Retrieve a reference to a byte or a subslice, depending on the type of the index given, while explicitly eliding bounds checks.

If given a position, this returns a reference to the byte at that position, if it exists.

If given a range, this returns the slice of bytes corresponding to that range in this byte string.

In the case of invalid indices, this returns None.

§Safety

Callers must ensure that the supplied bounds are correct. If they are out of bounds, then this results in undefined behavior. For a safe alternative, use get.

§Examples

Basic usage:

use bstr::B;

let s = B("baz");
unsafe {
    assert_eq!(s.get_unchecked(1), &b'a');
    assert_eq!(s.get_unchecked(0..2), "ba");
    assert_eq!(s.get_unchecked(2..), "z");
    assert_eq!(s.get_unchecked(1..=2), "az");
}
Source

pub unsafe fn get_unchecked_mut<I: SliceIndex>( &mut self, at: I, ) -> &mut I::Output

Retrieve a mutable reference to a byte or a subslice, depending on the type of the index given, while explicitly eliding bounds checks.

If given a position, this returns a reference to the byte at that position, if it exists.

If given a range, this returns the slice of bytes corresponding to that range in this byte string.

In the case of invalid indices, this returns None.

§Safety

Callers must ensure that the supplied bounds are correct. If they are out of bounds, then this results in undefined behavior. For a safe alternative, use get_mut.

§Examples

Basic usage:

use bstr::BString;

let mut s = BString::from("baz");
{
    let mut slice = unsafe { s.get_unchecked_mut(1..) };
    slice[0] = b'o';
    slice[1] = b'p';
}
assert_eq!(s, "bop");
Source

pub fn last(&self) -> Option<u8>

Returns the last byte in this byte string, if it’s non-empty. If this byte string is empty, this returns None.

§Examples

Basic usage:

use bstr::B;

assert_eq!(Some(b'z'), B("baz").last());
assert_eq!(None, B("").last());
Source

pub fn copy_within<R>(&mut self, src: R, dest: usize)
where R: RangeBounds<usize>,

Copies elements from one part of the slice to another part of itself, where the parts may be overlapping.

src is the range within this byte string to copy from, while dest is the starting index of the range within this byte string to copy to. The length indicated by src must be less than or equal to the number of bytes from dest to the end of the byte string.

§Panics

Panics if either range is out of bounds, or if src is too big to fit into dest, or if the end of src is before the start.

§Examples

Copying four bytes within a byte string:

use bstr::BStr;

let mut buf = *b"Hello, World!";
let s = BStr::new_mut(&mut buf);
s.copy_within(1..5, 8);
assert_eq!(s, "Hello, Wello!");
Source

pub fn as_ptr(&self) -> *const u8

Returns a raw pointer to this byte string’s underlying bytes.

§Safety

The caller must ensure that the byte string outlives the pointer this function returns, or else it will end up pointing to garbage.

Modifying the container (like a BString) referenced by this byte string may cause its buffer to be reallocated, which would also make any pointers to it invalid.

§Examples

Basic usage:

use bstr::B;

let s = B("hello");
let p = s.as_ptr();

unsafe {
    assert_eq!(*p.add(2), b'l');
}
Source

pub fn as_mut_ptr(&mut self) -> *mut u8

Returns a raw mutable pointer to this byte string’s underlying bytes.

§Safety

The caller must ensure that the byte string outlives the pointer this function returns, or else it will end up pointing to garbage.

Modifying the container (like a BString) referenced by this byte string may cause its buffer to be reallocated, which would also make any pointers to it invalid.

§Examples

Basic usage:

use bstr::BStr;

let mut buf = &mut [b'h', b'e', b'l', b'l', b'o'];
let mut s = BStr::new_mut(buf);
let p = s.as_mut_ptr();

unsafe {
    *p.add(2) = b'Z';
}
assert_eq!("heZlo", s);

Trait Implementations§

Source§

impl AsMut<[u8]> for BString

Source§

fn as_mut(&mut self) -> &mut [u8]

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsMut<BStr> for BString

Source§

fn as_mut(&mut self) -> &mut BStr

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsRef<[u8]> for BString

Source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<BStr> for BString

Source§

fn as_ref(&self) -> &BStr

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<BStr> for BString

Source§

fn borrow(&self) -> &BStr

Immutably borrows from an owned value. Read more
Source§

impl Clone for BString

Source§

fn clone(&self) -> BString

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BString

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for BString

Source§

type Target = BStr

The resulting type after dereferencing.
Source§

fn deref(&self) -> &BStr

Dereferences the value.
Source§

impl DerefMut for BString

Source§

fn deref_mut(&mut self) -> &mut BStr

Mutably dereferences the value.
Source§

impl Display for BString

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> From<&'a [u8]> for BString

Source§

fn from(s: &'a [u8]) -> BString

Converts to this type from the input type.
Source§

impl<'a> From<&'a BStr> for BString

Source§

fn from(s: &'a BStr) -> BString

Converts to this type from the input type.
Source§

impl<'a> From<&'a str> for BString

Source§

fn from(s: &'a str) -> BString

Converts to this type from the input type.
Source§

impl From<BString> for Vec<u8>

Source§

fn from(s: BString) -> Vec<u8>

Converts to this type from the input type.
Source§

impl From<String> for BString

Source§

fn from(s: String) -> BString

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for BString

Source§

fn from(s: Vec<u8>) -> BString

Converts to this type from the input type.
Source§

impl<'a> FromIterator<&'a [u8]> for BString

Source§

fn from_iter<T: IntoIterator<Item = &'a [u8]>>(iter: T) -> BString

Creates a value from an iterator. Read more
Source§

impl<'a> FromIterator<&'a BStr> for BString

Source§

fn from_iter<T: IntoIterator<Item = &'a BStr>>(iter: T) -> BString

Creates a value from an iterator. Read more
Source§

impl<'a> FromIterator<&'a str> for BString

Source§

fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> BString

Creates a value from an iterator. Read more
Source§

impl FromIterator<BString> for BString

Source§

fn from_iter<T: IntoIterator<Item = BString>>(iter: T) -> BString

Creates a value from an iterator. Read more
Source§

impl FromIterator<char> for BString

Source§

fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> BString

Creates a value from an iterator. Read more
Source§

impl FromIterator<u8> for BString

Source§

fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> BString

Creates a value from an iterator. Read more
Source§

impl Hash for BString

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for BString

Source§

fn cmp(&self, other: &BString) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'a, 'b> PartialEq<&'a [u8]> for BString

Source§

fn eq(&self, other: &&'a [u8]) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<&'a BStr> for BString

Source§

fn eq(&self, other: &&'a BStr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<&'a str> for BString

Source§

fn eq(&self, other: &&'a str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<[u8]> for BString

Source§

fn eq(&self, other: &[u8]) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BStr> for BString

Source§

fn eq(&self, other: &BStr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for &'a [u8]

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for &'a BStr

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for &'a str

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for [u8]

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for BStr

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for String

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for Vec<u8>

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<BString> for str

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<String> for BString

Source§

fn eq(&self, other: &String) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<Vec<u8>> for BString

Source§

fn eq(&self, other: &Vec<u8>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialEq<str> for BString

Source§

fn eq(&self, other: &str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq for BString

Source§

fn eq(&self, other: &BString) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a, 'b> PartialOrd<&'a [u8]> for BString

Source§

fn partial_cmp(&self, other: &&'a [u8]) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<&'a BStr> for BString

Source§

fn partial_cmp(&self, other: &&'a BStr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<&'a str> for BString

Source§

fn partial_cmp(&self, other: &&'a str) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<[u8]> for BString

Source§

fn partial_cmp(&self, other: &[u8]) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BStr> for BString

Source§

fn partial_cmp(&self, other: &BStr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for &'a [u8]

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for &'a BStr

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for &'a str

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for [u8]

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for BStr

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for String

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for Vec<u8>

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<BString> for str

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<String> for BString

Source§

fn partial_cmp(&self, other: &String) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<Vec<u8>> for BString

Source§

fn partial_cmp(&self, other: &Vec<u8>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'a, 'b> PartialOrd<str> for BString

Source§

fn partial_cmp(&self, other: &str) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd for BString

Source§

fn partial_cmp(&self, other: &BString) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Eq for BString

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.