Struct Str

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

A UTF-8 encoded, growable string.

The Str type is string type that has owership over the char.

§Example

You can create a Str from a literal string with Str::from:

use str::Str;

let hello = Str::from("hello, world!");

You can append a char to a Str with the push method, and append a &str with the push_str method;

use str::Str;

let mut hello = Str::from("Hello, ");

hello.push('w');
hello.push_str("orld!");

If you have a String, you can create a Str from it with the from method, and you can convert Str to String whit the into method:

use str::Str;

let hello = String::from("Hello world!");

let world = Str::from(hello);

let hello_world: String = world.into();

§Representation

A Str is made up of three components: a pointer to some chars, a length, and a capacity. The pointer points to an internal buffer Str uses to store its data. The length is the munber of bytes currently stored in the buffer, and the capacity is the size of the buffer in chars. As such, the length will always be less than or equal to the capacity.

The buffer is always stored on the heap.

You can look at these with the as_ptr, len, and capacity methods:

use std::mem;
use str::Str;

let story = Str::from("Once upon a time...");

let ptr = story.as_ptr();
let len = story.len();
let capacity = story.capacity();

// story has nineteen chars
assert_eq!(19, len);

// Now that we have our parts, we throw the story away.
mem::forget(story);

// We can re-build a Str out of ptr, len, and capacity. This is all
// unsafe because we are responsible for making sure the components
// valid:
let s = unsafe { Str::from_raw_parts(ptr as *mut _, len, capacity) };

assert_eq!(Str::from("Once upon a time..."), s);

If a Str has enough capacity, adding elements to it will not re-allocate. For example, consider this program:

use str::Str;

let mut s = Str::new();

println!("{}", s.capacity());

for _ in 0..5 {
    s.push_str("hello");
    println!("{}", s.capacity());
}

This will output the following:

0
5
10
20
20
40

At first, we have no memory allocated at all, but as we append to the string, it increases its capacity appropriately. If we instead use the with_capacity method to allocate the correct capacity initially:

use str::Str;

let mut s = Str::with_capacity(25);

println!("{}", s.capacity());

for _ in 0..5 {
    s.push_str("hello");
    println!("{}", s.capacity());
}

We end up with a different output:

25
25
25
25
25
25

Here, there’s no need to allocate more memory inside the loop.

Implementations§

Source§

impl Str

Source

pub fn new() -> Str

Creates a new empty Str.

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

§Examples

Basic usage:

use str::Str;

let s = Str::new();
Source

pub fn with_capacity(capacity: usize) -> Str

Creates a new empty Str with a particular capacity.

Strs 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 Str, 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 Str, 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 str::Str;

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

// The Str 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('a');
}

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

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

pub fn capacity(&self) -> usize

Returns this Str’s capacity, in bytes.

§Examples

Basic usage:

use str::Str;

let s = Str::with_capacity(10);

assert!(s.capacity() >= 10);
Source

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

Ensures that this Str’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, see the reserve_exact method.

§Panics

Panics if the new capacity overflows usize.

§Examples

Basic usage:

use str::Str;

let mut s = Str::new();

s.reserve(10);

assert!(s.capacity() >= 10);

This may not actually increase the capacity:

use str::Str;

let mut s = Str::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of 10
assert_eq!(2, s.len());
assert_eq!(10, s.capacity());

// Since we already have an extra 8 capacity, calling this...
s.reserve(8);

// ... doesn't actually increase.
assert_eq!(10, s.capacity());
Source

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

Ensures that this Str’s capacity is 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 str::Str;

let mut s = Str::new();

s.reserve_exact(10);

assert!(s.capacity() >= 10);

This may not actually increase the capacity:

use str::Str;

let mut s = Str::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of 10
assert_eq!(2, s.len());
assert_eq!(10, s.capacity());

// Since we already have an extra 8 capacity, calling this...
s.reserve_exact(8);

// ... doesn't actually increase.
assert_eq!(10, s.capacity());
Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of this Str to match its length.

§Examples

Basic usage:

use str::Str;

let mut s = Str::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to_fit();
assert_eq!(3, s.capacity());
Source

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

Converts a Str to a raw pointer. As Str are a vector of chars, the raw pointer points to a char. This pointer will be pointing to the first byte of the Str.

§Examples

Basic usage:

use str::Str;

let s = Str::from("Hello");
let ptr = s.as_ptr();
Source

pub unsafe fn from_raw_parts( buf: *mut char, length: usize, capacity: usize, ) -> Str

Creates a new Str from a length, capacity, and pointer.

§Safety

This is highly unsafe, due to the number of invariants that aren’t checked:

  • The memory at ptr needs to have been previously allocated by the same allocator the standard library uses.
  • length needs to be less than or equal to capacity.
  • capacity needs to be the correct value.

Violating these may cause problems like corrupting the allocator’s internal datastructures.

The ownership of ptr is effectively transferred to the Str which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.

§Examples

Basic usage:

use std::mem;
use str::Str;

let s = Str::from("hello");
let ptr = s.as_ptr();
let len = s.len();
let capacity = s.capacity();

mem::forget(s);

let s = unsafe { Str::from_raw_parts(ptr as *mut _, len, capacity) };

assert_eq!(Str::from("hello"), s);
Source

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

Converts a Str into a byte vector.

§Examples

Basic usage:

use str::Str;

let s = Str::from("hello");
let bytes = s.as_bytes();

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

pub fn as_slice(&self) -> &[char]

Converts a Str into a char slice.

This consumes the Str, so we do not need to copy its contents.

§Examples

Basic usage:

use str::Str;

let s = Str::from("hello");
let bytes = s.as_slice();

assert_eq!(&['h', 'e', 'l', 'l', 'o'][..], &bytes[..]);
Source

pub fn as_mut_slice(&mut self) -> &mut [char]

Converts a Str into a mut char slice.

This consumes the Str, so we do not need to copy its contents.

§Examples

Basic usage:

use str::Str;

let mut s = Str::from("hello");
{
    let bytes = s.as_mut_slice();
    bytes[1] = 'a';
}

assert_eq!(Str::from("hallo"), s);
Source

pub fn as_vec(self) -> Vec<char>

Converts a Str into a char vector.

This consumes the Str, so we do not need to copy its contents.

§Examples

Basic usage:

use str::Str;

let s = Str::from("hello");
let bytes = s.as_vec();

assert_eq!(&['h', 'e', 'l', 'l', 'o'], &bytes[..]);
Source

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

Converts a Str into a mut char slice.

This consumes the Str, so we do not need to copy its contents.

§Examples

Basic usage:

use str::Str;

let mut s = Str::from("hello");
{
    let bytes = s.as_mut_vec();
    bytes[1] = 'a';
}

assert_eq!(Str::from("hallo"), s);
Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&char) -> bool,

Source

pub fn get(&self, idx: usize) -> Option<&char>

Source

pub fn get_mut(&mut self, idx: usize) -> Option<&mut char>

Source

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

Source

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

Source

pub fn push_str(&mut self, string: &str)

Source

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

Source

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

Source

pub fn insert(&mut self, idx: usize, ch: char)

Source

pub fn insert_str(&mut self, _idx: usize, _string: &str)

Source

pub fn append(&mut self, other: &mut Self)

Source

pub fn len(&self) -> usize

Source

pub fn is_empty(&self) -> bool

Source

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

Source

pub fn split_at(&self, mid: usize) -> (Str, Str)

Source

pub fn clear(&mut self)

Source

pub fn iter(self) -> StrIterator

Trait Implementations§

Source§

impl<'a> Add<&'a str> for Str

Source§

type Output = Str

The resulting type after applying the + operator.
Source§

fn add(self, other: &str) -> Str

Performs the + operation. Read more
Source§

impl Add<char> for Str

Source§

type Output = Str

The resulting type after applying the + operator.
Source§

fn add(self, other: char) -> Str

Performs the + operation. Read more
Source§

impl Add for Str

Source§

type Output = Str

The resulting type after applying the + operator.
Source§

fn add(self, other: Str) -> Str

Performs the + operation. Read more
Source§

impl<'a> AddAssign<&'a str> for Str

Source§

fn add_assign(&mut self, other: &str)

Performs the += operation. Read more
Source§

impl AddAssign<char> for Str

Source§

fn add_assign(&mut self, other: char)

Performs the += operation. Read more
Source§

impl AddAssign for Str

Source§

fn add_assign(&mut self, other: Str)

Performs the += operation. Read more
Source§

impl AsMut<[char]> for Str

Source§

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

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

impl AsMut<Str> for Str

Source§

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

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

impl AsRef<[char]> for Str

Source§

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

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

impl AsRef<Str> for Str

Source§

fn as_ref(&self) -> &Str

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

impl Clone for Str

Source§

fn clone(&self) -> Str

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 Str

Source§

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

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

impl Default for Str

Source§

fn default() -> Str

Returns the “default value” for a type. Read more
Source§

impl Display for Str

Source§

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

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

impl<'a> From<&'a [char]> for Str

Source§

fn from(s: &'a [char]) -> Str

Converts to this type from the input type.
Source§

impl<'a> From<&'a mut [char]> for Str

Source§

fn from(s: &'a mut [char]) -> Str

Converts to this type from the input type.
Source§

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

Source§

fn from(string: &'a str) -> Str

Converts to this type from the input type.
Source§

impl From<String> for Str

Source§

fn from(string: String) -> Str

Converts to this type from the input type.
Source§

impl From<Vec<char>> for Str

Source§

fn from(s: Vec<char>) -> Str

Converts to this type from the input type.
Source§

impl Index<Range<usize>> for Str

Source§

type Output = [char]

The returned type after indexing.
Source§

fn index(&self, range: Range<usize>) -> &[char]

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeFrom<usize>> for Str

Source§

type Output = [char]

The returned type after indexing.
Source§

fn index(&self, range: RangeFrom<usize>) -> &[char]

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeFull> for Str

Source§

type Output = [char]

The returned type after indexing.
Source§

fn index(&self, _range: RangeFull) -> &[char]

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<RangeTo<usize>> for Str

Source§

type Output = [char]

The returned type after indexing.
Source§

fn index(&self, range: RangeTo<usize>) -> &[char]

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<usize> for Str

Source§

type Output = char

The returned type after indexing.
Source§

fn index(&self, idx: usize) -> &char

Performs the indexing (container[index]) operation. Read more
Source§

impl IndexMut<Range<usize>> for Str

Source§

fn index_mut(&mut self, range: Range<usize>) -> &mut [char]

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeFrom<usize>> for Str

Source§

fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut [char]

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeFull> for Str

Source§

fn index_mut(&mut self, range: RangeFull) -> &mut [char]

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<RangeTo<usize>> for Str

Source§

fn index_mut(&mut self, range: RangeTo<usize>) -> &mut [char]

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<usize> for Str

Source§

fn index_mut(&mut self, idx: usize) -> &mut char

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<'a> Into<String> for &'a Str

Source§

fn into(self) -> String

Converts this type into the (usually inferred) input type.
Source§

impl Into<String> for Str

Source§

fn into(self) -> String

Converts this type into the (usually inferred) input type.
Source§

impl IntoIterator for Str

Source§

type Item = char

The type of the elements being iterated over.
Source§

type IntoIter = StrIterator

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl Ord for Str

Source§

fn cmp(&self, other: &Str) -> 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 PartialEq for Str

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 PartialOrd for Str

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 Eq for Str

Auto Trait Implementations§

§

impl Freeze for Str

§

impl RefUnwindSafe for Str

§

impl Send for Str

§

impl Sync for Str

§

impl Unpin for Str

§

impl UnwindSafe for Str

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<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.