Struct spinoso_string::String[][src]

pub struct String { /* fields omitted */ }

Implementations

Constructs a new, empty String.

The String is conventionally UTF-8.

The string will not allocate until bytes are pushed onto it.

Examples

use spinoso_string::{Encoding, String};

const S: String = String::new();
assert_eq!(S.encoding(), Encoding::Utf8);

Constructs a new, empty String with the specified capacity.

The String is [conventionally UTF-8].

The string will be able to hold exactly capacity bytes without reallocating. If capacity is 0, the vector will not allocate.

It is important to note that although the returned string has the capacity specified, the string will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.

Examples

Encoding, capacity, and length:

use spinoso_string::{Encoding, String};

let s = String::with_capacity(10);
assert_eq!(s.encoding(), Encoding::Utf8);
assert_eq!(s.capacity(), 10);
assert_eq!(s.len(), 0);

Allocation:

use spinoso_string::{Encoding, String};

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

for ch in 'a'..='j' {
    s.push_byte(ch as u8);
}
// 10 elements have been inserted without reallocating.
assert_eq!(s.capacity(), 10);
assert_eq!(s.len(), 10);

Returns the Encoding of this String.

Examples

use spinoso_string::{Encoding, String};

let s = String::utf8(b"xyz".to_vec());
assert_eq!(s.encoding(), Encoding::Utf8);

Set the Encoding of this String.

Examples

use spinoso_string::{Encoding, String};

let mut s = String::utf8(b"xyz".to_vec());
assert_eq!(s.encoding(), Encoding::Utf8);
s.set_encoding(Encoding::Binary);
assert_eq!(s.encoding(), Encoding::Binary);

Extracts a slice containing the entire byte string.

Equivalent to &s[..].

Extracts a mutable slice containing the entire byte string.

Equivalent to &mut s[..].

Creates a String directly from the raw components of another string.

Safety

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

  • ptr needs to have been previously allocated via String (at least, it’s highly likely to be incorrect if it wasn’t).
  • length needs to be less than or equal to capacity.
  • capacity needs to be the capacity that the pointer was allocated with.

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

The ownership of ptr is effectively transferred to the String 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.

Decomposes a String into its raw components.

Returns the raw pointer to the underlying data, the length of the string (in bytes), and the allocated capacity of the data (in bytes). These are the same arguments in the same order as the arguments to from_raw_parts.

After calling this function, the caller is responsible for the memory previously managed by the String. The only way to do this is to convert the raw pointer, length, and capacity back into a String with the from_raw_parts function, allowing the destructor to perform the cleanup.

Converts self into a vector without clones or allocation.

This method consumes this String and returns its inner Vec<u8> buffer.

Examples

use spinoso_string::String;

let s = String::from("hello");
let buf = s.into_vec();
// `s` cannot be used anymore because it has been converted into `buf`.

assert_eq!(buf, b"hello".to_vec());

Converts the vector into Box<[u8]>.

Note that this will drop any excess capacity.

Examples

use spinoso_string::String;

let s = String::from("abc");
let slice = s.into_boxed_slice();

Any excess capacity is removed:

use spinoso_string::String;

let mut s = String::with_capacity(10);
s.extend_from_slice(&[b'a', b'b', b'c']);

assert_eq!(s.capacity(), 10);
let slice = s.into_boxed_slice();
assert_eq!(slice.into_vec().capacity(), 3);

Returns the number of bytes the string can hold without reallocating.

Examples

use spinoso_string::String;

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

Returns true if the vector contains no bytes.

Examples

use spinoso_string::String;

let mut s = String::new();
assert!(s.is_empty());

s.push_char('x');
assert!(!s.is_empty());

Returns the number of bytes in the string, also referred to as its ‘length’ or ‘bytesize’.

See also bytesize.

Examples

use spinoso_string::String;

let s = String::from("xyz");
assert_eq!(s.len(), 3);

Returns an iterator over this string’s underlying byte slice.

Examples

use spinoso_string::String;

let s = String::from("abc");
let mut iterator = s.iter();

assert_eq!(iterator.next(), Some(&b'a'));
assert_eq!(iterator.next(), Some(&b'b'));
assert_eq!(iterator.next(), Some(&b'c'));
assert_eq!(iterator.next(), None);

Returns an iterator that allows modifiying this string’s underlying byte slice.

Examples

use spinoso_string::String;

let mut s = String::from("abc");

for byte in s.iter_mut() {
    *byte = b'x';
}

assert_eq!(s, "xxx");

Returns an iterator over the bytes in this byte string.

Examples

use spinoso_string::String;

let s = String::utf8(b"foobar".to_vec());
let bytes: Vec<u8> = s.bytes().collect();
assert_eq!(bytes, s);

Reserves capacity for at least additional more bytes to be inserted in the given String. The string may reserve more space to avoid frequent reallocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

use spinoso_string::String;

let mut s = String::from("x");
s.reserve(10);
assert!(s.capacity() >= 11);

Reserves the minimum capacity for exactly additional more bytes to be inserted in the given String. After calling reserve_exact, capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

Note that the allocator may give the string more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer reserve if future insertions are expected.

Panics

Panics if the new capacity overflows usize.

Examples

use spinoso_string::String;

let mut s = String::from("x");
s.reserve_exact(10);
assert!(s.capacity() >= 11);

Shrinks the capacity of the vector as much as possible.

It will drop down as close as possible to the length but the allocator may still inform the string that there is space for a few more bytes.

Examples

use spinoso_string::String;

let mut s = String::with_capacity(10);
s.extend_from_slice(b"abc");
assert_eq!(s.capacity(), 10);
s.shrink_to_fit();
assert!(s.capacity() >= 3);

Returns a reference to a byte or sub-byteslice depending on the type of index.

  • If given a position, returns a reference to the byte at that position or None if out of bounds.
  • If given a range, returns the subslice corresponding to that range, or None if out of bounds.

Examples

use spinoso_string::String;

let s = String::from("abc");
assert_eq!(s.get(1), Some(&b'b'));
assert_eq!(s.get(0..2), Some(&b"ab"[..]));
assert_eq!(s.get(3), None);
assert_eq!(s.get(0..4), None);

Returns a mutable reference to a byte or sub-byteslice depending on the type of index (see get) or None if the index is out of bounds.

Examples

use spinoso_string::String;

let mut s = String::from("abc");

if let Some(byte) = s.get_mut(1) {
    *byte = b'x';
}
assert_eq!(s, "axc");

Returns a reference to a byte or sub-byteslice, without doing bounds checking.

For a safe alternative see get.

Safety

Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.

Examples

use spinoso_string::String;

let s = String::from("abc");

unsafe {
    assert_eq!(s.get_unchecked(1), &b'b');
}

Returns a mutable reference to a byte or sub-byteslice, without doing bounds checking.

For a safe alternative see get_mut.

Safety

Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.

Examples

use spinoso_string::String;

let mut s = String::from("abc");

unsafe {
    let byte = s.get_unchecked_mut(1);
    *byte = b'x';
}
assert_eq!(s, "axc");

Appends a given byte onto the end of this String.

The given byte is not required to be a valid byte given this String’s encoding because encodings are only conventional.

Examples

use spinoso_string::String;

let mut s = String::utf8(b"UTF-8?".to_vec());
s.push_byte(0xFF);
assert_eq!(s, &b"UTF-8?\xFF"[..]);

Try to append a given Unicode codepoint onto the end of this String.

This API is encoding-aware. For UTF-8 strings, the given integer is converted to a char before appending to this String using push_char. For ASCII and binary strings, the given integer is converted to a byte before appending to this String using push_byte.

This function can be used to implement the Ruby method String#<< for Integer arguments.

Errors

If this String is conventionally UTF-8 and the given codepoint is not a valid char, an error is returned.

If this String has ASCII or binary encoding and the given codepoint is not a valid byte, an error is returned.

Examples

For UTF-8 strings, the given codepoint is converted to a Unicode scalar value before appending:

use spinoso_string::String;

let mut s = String::utf8(b"".to_vec());
s.try_push_codepoint(b'a' as i64)?;
assert_eq!(s, "a");
assert!(s.try_push_codepoint(0xD83F).is_err());
assert!(s.try_push_codepoint(-1).is_err());

For ASCII and binary strings, the given codepoint must be a valid byte:

use spinoso_string::String;

let mut s = String::binary(b"".to_vec());
s.try_push_codepoint(b'a' as i64)?;
assert_eq!(s, "a");
assert!(s.try_push_codepoint(1024).is_err());
assert!(s.try_push_codepoint(-1).is_err());

Appends a given char onto the end of this String.

The given char is UTF-8 encoded and the UTF-8 bytes are appended to the end of this String.

Examples

use spinoso_string::String;

let mut s = String::from("<3");
s.push_char('💎');
assert_eq!(s, &b"<3\xF0\x9F\x92\x8E"[..]); // "<3💎"

Appends a given string slice onto the end of this String.

Examples

use spinoso_string::String;

let mut s = String::utf8(b"spinoso".to_vec());
s.push_str("-string");
assert_eq!(s, "spinoso-string");

Copies and appends all bytes in a slice to the String.

Iterates over the slice other, copies each element, and then appends it to this String. The other byte slice is traversed in-order.

Examples

use spinoso_string::String;

let mut s = String::from("a");
s.extend_from_slice(&b"bc"[..]);
assert_eq!(s, "abc");

Appends the given bytes to this String.

See also Extend.

This function can be used to implement the Ruby method String#<< for String arguments.

Examples

use spinoso_string::String;

let mut s = String::ascii(b"abc".to_vec());
s.concat(", easy as 123");
assert_eq!(s, "abc, easy as 123");

Returns true for a string which has only ASCII characters.

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

This function ignores this String’s encoding.

Examples

use spinoso_string::String;

let s = String::utf8("abc".as_bytes().to_vec());
assert!(s.is_ascii_only());
let s = String::utf8("abc\u{6666}".as_bytes().to_vec());
assert!(!s.is_ascii_only());

Change the encoding of this String to Encoding::Binary.

This function can be used to implement the Ruby method String#b.

Examples

use spinoso_string::{Encoding, String};

let mut s = String::utf8(b"xyz".to_vec());
assert_eq!(s.encoding(), Encoding::Utf8);
s.make_binary();
assert_eq!(s.encoding(), Encoding::Binary);

Returns the length of this String in bytes.

bytesize is an Encoding-oblivious API and is equivalent to String::len.

This function can be used to implement the Ruby method String#bytesize.

Examples

use spinoso_string::String;

let s = String::utf8("💎".as_bytes().to_vec());
assert_eq!(s.bytesize(), 4);
assert_eq!(s.bytesize(), s.len());

Modify this String to have the first character converted to uppercase and the remainder to lowercase.

Centers this String in width with the given padding.

This function returns an iterator that yields u8.

If width is greater than the length of this String, the returned iterator yields a byte sequence of length width with the byte content of this String centered and padded with the given padding; otherwise, yields the original bytes.

If the given padding is None, the String is padded with an ASCII space.

Errors

If given an empty padding bytestring, this function returns an error. This error is returned regardless of whether the String would be centered with the given

Examples

use spinoso_string::String;
let s = String::from("hello");

assert_eq!(s.center(4, None)?.collect::<Vec<_>>(), b"hello");
assert_eq!(s.center(20, None)?.collect::<Vec<_>>(), b"       hello        ");
assert_eq!(s.center(20, Some(&b"123"[..]))?.collect::<Vec<_>>(), b"1231231hello12312312");

This iterator is encoding-aware. Conventionally UTF-8 strings are iterated by UTF-8 byte sequences.

use spinoso_string::String;
let s = String::from("💎");

assert_eq!(s.center(3, None)?.collect::<Vec<_>>(), " 💎 ".as_bytes());

Modifies this String in-place with the given record separator removed from the end of str (if given).

If separator is None (i.e. separator has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is it will remove \n, \r, and \r\n). If separator is an empty string, it will remove all trailing newlines from the string.

A None separator does not mean that chomp is passed a nil separator. For str.chomp nil, MRI returns str.dup. For str.chomp! nil, MRI makes no changes to the receiver and returns nil.

Examples

use spinoso_string::String;

let mut s = String::utf8(b"This is a paragraph.\r\n\n\n".to_vec());
let modified = s.chomp(None::<&[u8]>);
assert!(modified);
assert_eq!(s, "This is a paragraph.\r\n\n");

let mut s = String::utf8(b"This is a paragraph.\r\n\n\n".to_vec());
let modified = s.chomp(Some(""));
assert!(modified);
assert_eq!(s, "This is a paragraph.");

let mut s = String::utf8(b"hello\r\n\r\r\n".to_vec());
let modified = s.chomp(None::<&[u8]>);
assert!(modified);
assert_eq!(s, "hello\r\n\r");

let mut s = String::utf8(b"hello\r\n\r\r\n".to_vec());
let modified = s.chomp(Some(""));
assert!(modified);
assert_eq!(s, "hello\r\n\r");

let mut s = String::utf8(b"This is a paragraph.".to_vec());
let modified = s.chomp(Some("."));
assert!(modified);
assert_eq!(s, "This is a paragraph");

let mut s = String::utf8(b"This is a paragraph.".to_vec());
let modified = s.chomp(Some("abc"));
assert!(!modified);
assert_eq!(s, "This is a paragraph.");

Modifies this String in-place and removes the last character.

This method returns a bool that indicates if this string was modified.

If the string ends with \r\n, both characters are removed. When applying chop to an empty string, the string remains empty.

String::chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

Examples

use spinoso_string::String;

let mut s = String::utf8(b"This is a paragraph.\r\n".to_vec());
let modified = s.chop();
assert!(modified);
assert_eq!(s, "This is a paragraph.");

let mut s = String::utf8(b"This is a paragraph.".to_vec());
let modified = s.chop();
assert!(modified);
assert_eq!(s, "This is a paragraph");

let mut s = String::utf8(b"".to_vec());
let modified = s.chop();
assert!(!modified);
assert_eq!(s, "");

let mut s = String::utf8(b"x".to_vec());
let modified = s.chop();
assert!(modified);
assert_eq!(s, "");

Returns a one-character string at the beginning of the string.

Examples

Conventionally UTF-8 Strings perform a partial UTF-8 decode to compute the first character.

use spinoso_string::String;

let s = String::utf8(b"abcde".to_vec());
assert_eq!(s.chr(), &b"a"[..]);

let s = String::utf8(b"".to_vec());
assert_eq!(s.chr(), &[]);

let s = String::utf8("🦀spinoso💎".as_bytes().to_vec());
assert_eq!(s.chr(), &b"\xF0\x9F\xA6\x80"[..]);

let s = String::utf8(b"\xFFspinoso".to_vec());
assert_eq!(s.chr(), &b"\xFF"[..]);

For ASCII and binary Strings this function returns a slice of the first byte or the empty slice if the String is empty.

use spinoso_string::String;

let s = String::binary(b"abcde".to_vec());
assert_eq!(s.chr(), &b"a"[..]);

let s = String::binary(b"".to_vec());
assert_eq!(s.chr(), &[]);

let s = String::binary("🦀spinoso💎".as_bytes().to_vec());
assert_eq!(s.chr(), &b"\xF0"[..]);

let s = String::binary(b"\xFFspinoso".to_vec());
assert_eq!(s.chr(), &b"\xFF"[..]);

Returns the index of the first occurrence of the given substring in this String.

Returns None if not found. If the second parameter is present, it specifies the position in the string to begin the search.

This function can be used to implement String#index.

Examples

use spinoso_string::String;

let s = String::from("hello");
assert_eq!(s.index("e", None), Some(1));
assert_eq!(s.index("lo", None), Some(3));
assert_eq!(s.index("a", None), None);
assert_eq!(s.index("l", Some(3)), Some(3));

Returns an iterator that yields a debug representation of the String.

This iterator produces char sequences like "spinoso" and "invalid-\xFF-utf8".

This function can be used to implement the Ruby method String#inspect.

Returns the Integer ordinal of a one-character string.

Errors

If this String is empty, an error is returned.

If this String is conventionally UTF-8 and the string contents begin with an invalid UTF-8 byte sequence, an error is returned.

Returns an iterator over the chars of a String.

This function is encoding-aware. Strings with UTF-8 encoding are only conventionally UTF-8. This iterator yields &[u8] byte slices that correspond to either a valid UTF-8 byte sequence or a single invalid UTF-8 byte. For ASCII encoded and binary encoded strings, this iterator yields slices of single bytes.

For UTF-8 encoded strings, the yielded byte slices can be parsed into chars with str::from_utf8 and str::chars.

Examples

Iterating over the characters of a conventionally UTF-8 string:

use core::str;
use spinoso_string::String;

let s = String::utf8(b"ab\xF0\x9F\x92\x8E\xFF".to_vec());
let mut chars = s.chars();
assert_eq!(chars.next(), Some(&b"a"[..]));
assert_eq!(chars.next().map(str::from_utf8), Some(Ok("b")));
assert_eq!(chars.next(), Some(&[0xF0, 0x9F, 0x92, 0x8E][..]));
assert_eq!(chars.next(), Some(&b"\xFF"[..]));
assert_eq!(chars.next(), None);

Iterating over the characters of a binary string:

use spinoso_string::String;

let s = String::binary("💎".as_bytes().to_vec());
let mut chars = s.chars();
assert_eq!(chars.next(), Some(&[0xF0][..]));
assert_eq!(chars.next(), Some(&[0x9F][..]));
assert_eq!(chars.next(), Some(&[0x92][..]));
assert_eq!(chars.next(), Some(&[0x8E][..]));
assert_eq!(chars.next(), None);

Returns the character length of this String.

This function is encoding-aware. For Strings with UTF-8 encoding, multi-byte Unicode characters are length 1 and invalid UTF-8 bytes are length 1. For Strings with ASCII encoding or binary encoding, this function is equivalent to len and bytesize.

Examples

use spinoso_string::String;

let s = String::utf8(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abc💎\xFF"
assert_eq!(s.char_len(), 5);

let b = String::binary(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abc💎\xFF"
assert_eq!(b.char_len(), 8);

Returns true for a String which is encoded correctly.

For this method to return true, Strings with conventionally UTF-8 must be well-formed UTF-8; ASCII-encoded Strings must only contain bytes in the range 0..=127; binary-encoded Strings may contain any byte sequence.

This method is suitable for implementing the Ruby method String#valid_encoding?.

Examples

use spinoso_string::{Encoding, String};

let s = String::utf8(b"xyz".to_vec());
assert!(s.is_valid_encoding());
let s = String::utf8("🚀".to_string().into_bytes());
assert!(s.is_valid_encoding());
let s = String::utf8(b"abc\xFF\xFExyz".to_vec());
assert!(!s.is_valid_encoding());

let s = String::ascii(b"xyz".to_vec());
assert!(s.is_valid_encoding());
let s = String::ascii("🚀".to_string().into_bytes());
assert!(!s.is_valid_encoding());
let s = String::ascii(b"abc\xFF\xFExyz".to_vec());
assert!(!s.is_valid_encoding());

let s = String::binary(b"xyz".to_vec());
assert!(s.is_valid_encoding());
let s = String::binary("🚀".to_string().into_bytes());
assert!(s.is_valid_encoding());
let s = String::binary(b"abc\xFF\xFExyz".to_vec());
assert!(s.is_valid_encoding());

Trait Implementations

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Immutably borrows from an owned value. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

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

The resulting type after dereferencing.

Dereferences the value.

Mutably dereferences the value.

Extends a collection with the contents of an iterator. Read more

🔬 This is a nightly-only experimental API. (extend_one)

Extends a collection with exactly one element.

🔬 This is a nightly-only experimental API. (extend_one)

Reserves capacity in a collection for the given number of additional elements. Read more

Extends a collection with the contents of an iterator. Read more

🔬 This is a nightly-only experimental API. (extend_one)

Extends a collection with exactly one element.

🔬 This is a nightly-only experimental API. (extend_one)

Reserves capacity in a collection for the given number of additional elements. Read more

Extends a collection with the contents of an iterator. Read more

🔬 This is a nightly-only experimental API. (extend_one)

Extends a collection with exactly one element.

🔬 This is a nightly-only experimental API. (extend_one)

Reserves capacity in a collection for the given number of additional elements. Read more

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Creates a value from an iterator. Read more

Creates a value from an iterator. Read more

Creates a value from an iterator. Read more

Creates a value from an iterator. Read more

Creates a value from an iterator. Read more

Creates a value from an iterator. Read more

Feeds this value into the given Hasher. Read more

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

The returned type after indexing.

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

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

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

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

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.