Struct easy_strings::EZString [] [src]

pub struct EZString(_);

An ergonomic, garbage collected string.

EZString is similar to the strings in high level languages such as Python and Java. It is designed to be as easy to use as possible by always returning owned values, using reference counting and copy-on-write under the hood in order to make this efficient.

Creation

The most common way to create an EZString is from a string literal, using the ez() helper function. This interns the string so that calling it multiple times with the same string literal won't result in multiple copies or allocations. (It still requires locking and querying the interned string table each time.)

use easy_strings::{ez};
let s = ez("Hello, world!");

You can also create EZString from existing Strings or &strs.

use easy_strings::{EZString};
let s = EZString::from("foo");
let s = EZString::from("foo".to_string());

Concatenation

To concatenate strings, write &a + &b. This syntax works regardless of the types of a and b, whether they are EZString, &EZString, String, &String, or &str, as long as either a or b is an EZString or &EZString.

let e = ez("E");
let re = &e;
let s = "s".to_string();
let rs = &s;
let lit = "lit";
assert_eq!(&e + &e, "EE");
assert_eq!(&e + &re, "EE");
assert_eq!(&e + &s, "Es");
assert_eq!(&e + &rs, "Es");
assert_eq!(&e + &lit, "Elit");
assert_eq!(&lit + &e, "litE");
assert_eq!(&lit + &re, "litE");
assert_eq!(&s + &re, "sE");
assert_eq!(&rs + &e, "sE");

Note: If you're using Clippy, you should #[allow(needless_borrow)] or you'll get a lot of warnings.

You can also concatenate multiple strings this way, as long as at least one of the first two is EZString or &EZString.

assert_eq!(&lit + &re + &s + &e + &e + &rs, "litEsEEs");

You can also use the += operator. This is optimized to only copy the left hand string when it is not uniquely owned. This means that the following loop is O(n) rather than O(n2 ) and there is no need for a seperate StringBuilder type like there is in Java.

let mut s = ez("Some numbers: ");
for i in 0..5 {
    s += &i.to_string();
    s += &", ";
}
assert_eq!(s, "Some numbers: 0, 1, 2, 3, 4, ");

Slicing

Slicing is done via the substr() method. Note that the indices are by byte, not code point. If the provided indices are not on a code point boundary, substr() will panic.

let mut a = ez("Hello, world!");
assert_eq!(a.substr(1..), "ello, world!");
assert_eq!(a.substr(..6), "Hello,");
assert_eq!(a.substr(1..6), "ello,");
assert_eq!(a.substr(1..a.len()-1), "ello, world");

let b = a.substr(1..3);
a += &b; // b is a copy, so we can freely mutate a

substr() returns the substring as a new EZString. If you want a borrowed slice instead, you can use []. This avoids the extra copy and allocation, at the expense of forcing you to worry about lifetimes, which easy_strings was designed to avoid.

let b = &a[1..3];
assert_eq!(b, "el");
// a += &b; // compile error because b borrowed a

Equality

Equality testing between multiple EZStrings or &EZStrings just works. If you want to compare to a String or &str, the EZString should be on the left. If it is on the right, you'll have to prefix it with * (or ** for &EZString).

let e = ez("AAA");
let er = &e;
let s = String::from("AAA");
let sr = &s;
let lit = "AAA";
assert!(e == e);
assert!(er == er);
assert!(e == er);
assert!(er == e);
assert!(e == s);
assert!(e == sr);
assert!(e == lit);
assert!(er == s);
assert!(er == sr);
assert!(er == lit);
assert!(s == *e);
assert!(*sr == *e);
assert!(lit == *e);
assert!(s == **er);
assert!(*sr == **er);
assert!(lit == **er);

Cloning

EZString is not Copy, which means you must clone it whenever you want to reuse it by value. To work around this, it is recommended that your functions always take EZString parameters by reference and return owned EZStrings. This provides maximum flexibility to the caller and avoids requiring clone()s everywhere. EZString's own methods, such as trim() here, already do this.

// bad: requires caller to clone() argument
fn foo(s: EZString) -> EZString { s.trim() }
// good
fn bar(s: &EZString) -> EZString { s.trim() }

That being said, sometimes taking by value is unavoidable. In this case, you need to clone your string. Remember, this doesn't actually copy the string, it just increments the reference count.

The simplest and most standard way is to call .clone(). However, if this is too verbose for your taste, there is also a shorthand .c() method. c() also has the advantage of always cloning the underlying EZString, even if you call it on nested references (clone() clones the reference instead in this case).

let mut v: Vec<EZString> = Vec::new();
let s = ez("foo");
let rs = &s;
let rrs = &rs;

v.push(s.clone());
v.push(s.c());
v.push(rs.clone());
v.push(rs.c());
// v.push(rrs.clone()); // compile error
v.push(rrs.c());

Coercions

Most libraries operate on Strings and &strs, rather than EZStrings. Luckily, EZString Derefs to &str, so in most cases, you can pass &s in and it will just work,

fn take_str(_: &str) {}
let s = ez("");
let rs = &s;

take_str(&s);
take_str(&rs);

In complicated cases, such as with generic functions, inference may not work. In that case, you can explicitly get a &str via as_str().

take_str(s.as_str());
take_str(rs.as_str());

If a function requires an owned String, you can use the to_string() method.

fn take_string(_: String) {}
take_string(s.to_string());

String searching

The contains(), starts_with(), ends_with(), find(), and rfind() methods are generic, meaning that you'll get a confusing compile error if you naively pass in an EZString. The easiest solution is to use as_str() as mentioned in the previous section. Alternatively, you can write &*s for EZStrings and &**s for &EZStrings. No special syntax is required to pass in a literal.

let s = ez("Hello, world!");

assert!(s.contains("o, wo"));
assert!(s.starts_with("Hello"));
assert!(s.ends_with("world!"));
assert!(!s.ends_with("worl"));
assert_eq!(s.find("ld"), Some(10));
assert_eq!(s.find("l"), Some(2));
assert_eq!(s.rfind("l"), Some(10));

let p = ez("wor");
let r = &p;
assert!(s.contains(&*p));
assert!(s.contains(&**r));
assert!(s.contains(p.as_str()));
assert!(s.contains(r.as_str()));

Note that find() and rfind() return an Option. To get behavior similar to Python's str.index(), which throws if the substring isn't present, just call unwrap() on the result.

assert_eq!(s.find("ld").unwrap(), 10);

String splitting

You can split by newlines, whitespace, or a provided substring. The returned iterators wrap the results in new EZStrings.

let s = ez(" Hello,   world!\nLine two. ");

assert_eq!(s.lines().collect::<Vec<_>>(), vec![ez(" Hello,   world!"), ez("Line two. ")]);
assert_eq!(s.split_whitespace().collect::<Vec<_>>(),
           vec![ez("Hello,"), ez("world!"), ez("Line"), ez("two.")]);

let s = ez("aaa-bbb-ccc");
assert_eq!(s.split("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb"), ez("ccc")]);
assert_eq!(s.rsplit("-").collect::<Vec<_>>(), vec![ez("ccc"), ez("bbb"), ez("aaa")]);

You can also limit the number of splits via splitn().

let s = ez("aaa-bbb-ccc");
assert_eq!(s.splitn(2, "-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb-ccc")]);
assert_eq!(s.rsplitn(2, "-").collect::<Vec<_>>(), vec![ez("ccc"), ez("aaa-bbb")]);

split_terminator() and rsplit_terminator() are the same as split()/rsplit() except that if the final substring is empty, it is skipped. This is useful if the string is terminated, rather than seperated, by a seperator.

let s = ez("aaa-bbb-");
assert_eq!(s.split("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb"),  ez("")]);
assert_eq!(s.split_terminator("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb")]);
assert_eq!(s.rsplit_terminator("-").collect::<Vec<_>>(), vec![ez("bbb"), ez("aaa")]);

let s = ez("aaa-bbb");
assert_eq!(s.split("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb")]);
assert_eq!(s.split_terminator("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb")]);

Although the iterators are lazy, they hold a reference to a copy of the string at time of creation. Therefore, if you later modify the string, the iteration results don't change.

let mut s = ez("aaa-bbb-ccc");
let it = s.split("-");
s += &"-ddd";
assert_eq!(it.collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb"), ez("ccc")]);
let it2 = s.split("-");
assert_eq!(it2.collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb"), ez("ccc"), ez("ddd")]);

Returning Iterators

Every iteration method returns a distinct type. If you want to return one of several iterators, you need to either box them or eagerly evaluate them.

For example, suppose you wanted to emulate Python's str.split() method, which splits on a substring if one is passed in and splits on whitespace if no argument is passed. The naive approach doesn't work as EZString::split() and EZString::split_whitespace() return distinct types. One solution is to eagerly evaluate them and return a list of strings.

fn split<'a, P: Into<Option<&'a str>>>(s: &EZString, sep: P) -> Vec<EZString> {
    match sep.into() {
        Some(sep) => s.split(sep).collect(),
        None => s.split_whitespace().collect(),
    }
}

let s = ez("x  x-x 77x");
assert_eq!(split(&s, "x"), vec![ez(""), ez("  "), ez("-"), ez(" 77"), ez("")]);
assert_eq!(split(&s, None), vec![ez("x"), ez("x-x"), ez("77x")]);

Alternatively, you can box the iterators, thus preserving the laziness.

fn split<'a, P: Into<Option<&'a str>>>(s: &EZString, sep: P) -> Box<Iterator<Item=EZString>> {
    match sep.into() {
        Some(sep) => Box::new(s.split(sep)),
        None => Box::new(s.split_whitespace()),
    }
}

Trimming

The trim(), trim_left(), and trim_right() methods trim whitespace from the ends of the string.

assert_eq!(ez("  hello \n ").trim(), "hello");
let s = ez("  hello \n ").trim_right();
assert_eq!(s, "  hello");
assert_eq!(s.trim_left(), "hello");

trim_left_matches() and trim_right_matches() trim matches of a given substring from the ends of the string. Note that unlike Python, they do not take a set of characters to trim, but a substring. Note that trim_matches() is different from all of the other methods. It takes a char rather than a substring.

assert_eq!(ez("  hello   ").trim_matches(' '), "hello");
let s = ez(" x xhello x x x").trim_right_matches(" x");
assert_eq!(s, " x xhello");
assert_eq!(s.trim_left_matches(" x"), "hello");

String replacement

You can replace one substring with another via .replace().

let s = ez("one fish two fish, old fish, new fish");
assert_eq!(s.replace("fish", "bush"), "one bush two bush, old bush, new bush");
assert_eq!(s.replace(&ez("fish"), &ez("bush")), "one bush two bush, old bush, new bush");

You can also replace a the first n occurences of a substring via .replacen()

let s = ez("one fish two fish, old fish, new fish");
assert_eq!(s.replacen("fish", "bush", 3), "one bush two bush, old bush, new fish");
assert_eq!(s.replacen(&ez("fish"), &ez("bush"), 2), "one bush two bush, old fish, new fish");

Other methods

to_lowercase(), to_uppercase(), and repeat() are pretty much self explanatory.

let s = ez("Hello, World!");
assert_eq!(s.to_lowercase(), "hello, world!");
assert_eq!(s.to_uppercase(), "HELLO, WORLD!");
assert_eq!(s.repeat(3), "Hello, World!Hello, World!Hello, World!");

Note that to_lowercase and to_uppercase are Unicode aware, but locale independent. i.e. there is no way to get Turkish capitalization for 'i'.

let s = ez("ὈΔΥΣΣΕΎΣ");
assert_eq!(s.to_lowercase(), "ὀδυσσεύς");

Pointer equality

The == operator tests for value equality, that is whether the given strings contain the same bytes. If you want to test whether two EZStrings share the same underlying buffer, you can use the ptr_eq() method. Note that since EZString is copy-on-write, there is no observeable effect of sharing buffers, apart from reduced memory usage. Therefore, this method is rarely useful.

let a = ez("xxx");
let mut b = a.clone();
let c = &ez("xx") + &ez("x");
assert!(a.ptr_eq(&b));
assert!(b == c && !b.ptr_eq(&c));

b += &"foo";
// += is copy on write, so b no longer points to a
assert!(!a.ptr_eq(&b));
assert!(a == "xxx");
assert!(b == "xxxfoo");

Methods

impl EZString
[src]

Shorthand for clone().

This will derefence any number of references, unlike clone(), which only works on an EZString or &EZString.

let r = &&&&&ez("");
let s: EZString = r.c(); // works
//let s: EZString = r.clone(); // doesn't work

Returns whether two strings share the same underlying buffer. This is similar to the is operator in Python.

let a = ez("xxx");
let mut b = a.clone();
let c = &ez("xx") + &ez("x");
assert!(a.ptr_eq(&b));
assert!(b == c && !b.ptr_eq(&c));

b += &"foo";
// += is copy on write, so b no longer points to a
assert!(!a.ptr_eq(&b));

Returns a substring. This creates an independent EZString, which involves copying the sliced data. Panics if the given bounds are not at a code point boundary or are greater than the length of the string.

let mut a = ez("Hello, world!");
assert_eq!(a.substr(1..), "ello, world!");
assert_eq!(a.substr(..6), "Hello,");
assert_eq!(a.substr(1..6), "ello,");
assert_eq!(a.substr(1..a.len()-1), "ello, world");

let b = a.substr(1..3);
a += &b; // b is a copy, so we can freely mutate a

Note: If you want a borrowed slice instead, you can use []. This avoids the extra copy and allocation, at the expense of forcing you to worry about lifetimes, which easy_strings was designed to avoid.

let mut a = ez("Hello, world!");
let b = &a[1..3];
assert_eq!(b, "el");
// a += &b; // compile error because b borrowed a

Returns a reference to the underlying String.

Returns a copy of the underlying String.

Divide one string into two at an index.

The argument, mid, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

The two strings returned go from the start of the string to mid, and from mid to the end of the string.

Panics if mid is not on a UTF-8 code point boundary, or if it is beyond the last code point of the string.

Returns an iterator over the chars of a string.

As a string consists of valid UTF-8, we can iterate through a string by char. This method returns such an iterator.

It's important to remember that char represents a Unicode Scalar Value, and may not match your idea of what a 'character' is. Iteration over grapheme clusters may be what you actually want.

Returns an iterator over the chars of a string, and their positions.

As a string consists of valid UTF-8, we can iterate through a string by char. This method returns an iterator of both these chars, as well as their byte positions.

The iterator yields tuples. The position is first, the char is second.

An iterator over the bytes of a string.

As a string consists of a sequence of bytes, we can iterate through a string by byte. This method returns such an iterator.

Split a string by whitespace.

'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space.

This iterator is double ended.

let s = ez(" Hello,   world!\nLine two. ");
assert_eq!(s.split_whitespace().collect::<Vec<_>>(),
           vec![ez("Hello,"), ez("world!"), ez("Line"), ez("two.")]);

An iterator over the lines of a string.

Lines are ended with either a newline (\n) or a carriage return with a line feed (\r\n).

The final line ending is optional.

This iterator is double ended.

let s = ez(" Hello,   world!\nLine two. ");
assert_eq!(s.lines().collect::<Vec<_>>(), vec![ez(" Hello,   world!"), ez("Line two. ")]);

Split a string by substring

let s = ez("aaa-bbb-ccc");
assert_eq!(s.split("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb"), ez("ccc")]);

Split a string by substring and return results in reverse order.

let s = ez("aaa-bbb-ccc");
assert_eq!(s.rsplit("-").collect::<Vec<_>>(), vec![ez("ccc"), ez("bbb"), ez("aaa")]);

split_terminator() is the same as split() except that if the final substring is empty, it is skipped. This is useful if the string is terminated, rather than seperated, by a seperator.

let s = ez("aaa-bbb-");
assert_eq!(s.split("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb"),  ez("")]);
assert_eq!(s.split_terminator("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb")]);

let s = ez("aaa-bbb");
assert_eq!(s.split("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb")]);
assert_eq!(s.split_terminator("-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb")]);

Same as split_terminator, except it returns the results in reverse order.

let s = ez("aaa-bbb-");
assert_eq!(s.rsplit_terminator("-").collect::<Vec<_>>(), vec![ez("bbb"), ez("aaa")]);

Split a string by substring, up to n-1 times (returning up to n results).

let s = ez("aaa-bbb-ccc");
assert_eq!(s.splitn(2, "-").collect::<Vec<_>>(), vec![ez("aaa"), ez("bbb-ccc")]);

Split a string by substring starting from the end, up to n-1 times (returning up to n results).

let s = ez("aaa-bbb-ccc");
assert_eq!(s.rsplitn(2, "-").collect::<Vec<_>>(), vec![ez("ccc"), ez("aaa-bbb")]);

Returns a string with leading and trailing whitespace removed.

'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space.

assert_eq!(ez("  hello \n ").trim(), "hello");

Returns a string with leading whitespace removed.

'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space.

assert_eq!(ez("  hello \n ").trim_left(), "hello \n ");

Returns a string with trailing whitespace removed.

'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space.

assert_eq!(ez("  hello \n ").trim_right(), "  hello");

Returns a string with all instances of a given character removed from the beginning and end.

assert_eq!(ez("  hello   ").trim_matches(' '), "hello");

Trim matches of a given substring from the beginning of the string. Note that unlike Python, it does not take a set of characters to trim, but a substring. Note that this differs from trim_matches(), which takes a char.

let s = ez(" x xhello x x x").trim_right_matches(" x");
assert_eq!(s, " x xhello");
assert_eq!(s.trim_left_matches(" x"), "hello");

Trim matches of a given substring from the end of the string. Note that unlike Python, it does not take a set of characters to trim, but a substring. Note that this differs from trim_matches(), which takes a char.

let s = ez(" x xhello x x x").trim_right_matches(" x");
assert_eq!(s, " x xhello");
assert_eq!(s.trim_left_matches(" x"), "hello");

Replaces all matches of a string with another string.

let s = ez("one fish two fish, old fish, new fish");
assert_eq!(s.replace("fish", "bush"), "one bush two bush, old bush, new bush");
assert_eq!(s.replace(&ez("fish"), &ez("bush")), "one bush two bush, old bush, new bush");

Replaces the first n matches of a string with another string.

let s = ez("one fish two fish, old fish, new fish");
assert_eq!(s.replacen("fish", "bush", 3), "one bush two bush, old bush, new fish");
assert_eq!(s.replacen(&ez("fish"), &ez("bush"), 2), "one bush two bush, old fish, new fish");

Returns the lowercase equivalent of this string.

'Lowercase' is defined according to the terms of the Unicode Derived Core Property Lowercase.

let s = ez("Hello, World!");
assert_eq!(s.to_lowercase(), "hello, world!");

let s = ez("ὈΔΥΣΣΕΎΣ");
assert_eq!(s.to_lowercase(), "ὀδυσσεύς");

Returns the uppercase equivalent of this string.

'Uppercase' is defined according to the terms of the Unicode Derived Core Property Uppercase.

let s = ez("Hello, World!");
assert_eq!(s.to_uppercase(), "HELLO, WORLD!");

Create a new string by repeating a string n times.

let s = ez("Hello, World!");
assert_eq!(s.repeat(3), "Hello, World!Hello, World!Hello, World!");

Methods from Deref<Target = String>

Converts a String into a byte vector.

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

Examples

Basic usage:

let s = String::from("hello");
let bytes = s.into_bytes();

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

Extracts a string slice containing the entire string.

Extracts a string slice containing the entire string.

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

Examples

Basic usage:

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

s.push_str("bar");

assert_eq!("foobar", s);

Returns this String's capacity, in bytes.

Examples

Basic usage:

let s = String::with_capacity(10);

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

Ensures that this String'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:

let mut s = String::new();

s.reserve(10);

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

This may not actually increase the capacity:

let mut s = String::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());

Ensures that this String'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:

let mut s = String::new();

s.reserve_exact(10);

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

This may not actually increase the capacity:

let mut s = String::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());

Shrinks the capacity of this String to match its length.

Examples

Basic usage:

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

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

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

Appends the given char to the end of this String.

Examples

Basic usage:

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

s.push('1');
s.push('2');
s.push('3');

assert_eq!("abc123", s);

Returns a byte slice of this String's contents.

The inverse of this method is from_utf8.

Examples

Basic usage:

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

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

Shortens this String to the specified length.

If new_len is greater than the string's current length, this has no effect.

Note that this method has no effect on the allocated capacity of the string

Panics

Panics if new_len does not lie on a char boundary.

Examples

Basic usage:

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

s.truncate(2);

assert_eq!("he", s);

Removes the last character from the string buffer and returns it.

Returns None if this String is empty.

Examples

Basic usage:

let mut s = String::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);

Removes a char from this String at a byte position and returns it.

This is an O(n) operation, as it requires copying every element in the buffer.

Panics

Panics if idx is larger than or equal to the String's length, or if it does not lie on a char boundary.

Examples

Basic usage:

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

assert_eq!(s.remove(0), 'f');
assert_eq!(s.remove(1), 'o');
assert_eq!(s.remove(0), 'o');

Inserts a character into this String at a byte position.

This is an O(n) operation as it requires copying every element in the buffer.

Panics

Panics if idx is larger than the String's length, or if it does not lie on a char boundary.

Examples

Basic usage:

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

s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');

assert_eq!("foo", s);

Inserts a string slice into this String at a byte position.

This is an O(n) operation as it requires copying every element in the buffer.

Panics

Panics if idx is larger than the String's length, or if it does not lie on a char boundary.

Examples

Basic usage:

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

s.insert_str(0, "foo");

assert_eq!("foobar", s);

Returns a mutable reference to the contents of this String.

Safety

This function is unsafe because it does not check that the bytes passed to it are valid UTF-8. If this constraint is violated, it may cause memory unsafety issues with future users of the String, as the rest of the standard library assumes that Strings are valid UTF-8.

Examples

Basic usage:

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

unsafe {
    let vec = s.as_mut_vec();
    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);

    vec.reverse();
}
assert_eq!(s, "olleh");

Returns the length of this String, in bytes.

Examples

Basic usage:

let a = String::from("foo");

assert_eq!(a.len(), 3);

Returns true if this String has a length of zero.

Returns false otherwise.

Examples

Basic usage:

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

v.push('a');
assert!(!v.is_empty());

Splits the string into two at the given index.

Returns a newly allocated String. self contains bytes [0, at), and the returned String contains bytes [at, len). at must be on the boundary of a UTF-8 code point.

Note that the capacity of self does not change.

Panics

Panics if at is not on a UTF-8 code point boundary, or if it is beyond the last code point of the string.

Examples

let mut hello = String::from("Hello, World!");
let world = hello.split_off(7);
assert_eq!(hello, "Hello, ");
assert_eq!(world, "World!");

Truncates this String, removing all contents.

While this means the String will have a length of zero, it does not touch its capacity.

Examples

Basic usage:

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

s.clear();

assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(3, s.capacity());

Creates a draining iterator that removes the specified range in the string and yields the removed chars.

Note: The element range is removed even if the iterator is not consumed until the end.

Panics

Panics if the starting point or end point do not lie on a char boundary, or if they're out of bounds.

Examples

Basic usage:

let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Remove the range up until the β from the string
let t: String = s.drain(..beta_offset).collect();
assert_eq!(t, "α is alpha, ");
assert_eq!(s, "β is beta");

// A full range clears the string
s.drain(..);
assert_eq!(s, "");

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

recently added

Creates a splicing iterator that removes the specified range in the string, replaces with the given string, and yields the removed chars. The given string doesn’t need to be the same length as the range.

Note: The element range is removed when the Splice is dropped, even if the iterator is not consumed until the end.

Panics

Panics if the starting point or end point do not lie on a char boundary, or if they're out of bounds.

Examples

Basic usage:

#![feature(splice)]
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Replace the range up until the β from the string
let t: String = s.splice(..beta_offset, "Α is capital alpha; ").collect();
assert_eq!(t, "α is alpha, ");
assert_eq!(s, "Α is capital alpha; β is beta");

Converts this String into a Box<str>.

This will drop any excess capacity.

Examples

Basic usage:

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

let b = s.into_boxed_str();

Trait Implementations

impl Clone for EZString
[src]

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

impl Default for EZString
[src]

Returns the "default value" for a type. Read more

impl PartialOrd for EZString
[src]

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

impl Ord for EZString
[src]

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

impl Eq for EZString
[src]

impl Hash for EZString
[src]

Feeds this value into the given [Hasher]. Read more

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

impl Debug for EZString
[src]

Formats the value using the given formatter.

impl Deref for EZString
[src]

The resulting type after dereferencing

The method called to dereference a value

impl DerefMut for EZString
[src]

Returns a mutable reference to the underlying string, copying it if necessary.

impl Borrow<String> for EZString
[src]

Immutably borrows from an owned value. Read more

impl Borrow<str> for EZString
[src]

Immutably borrows from an owned value. Read more

impl AsRef<String> for EZString
[src]

Performs the conversion.

impl AsRef<str> for EZString
[src]

Performs the conversion.

impl From<String> for EZString
[src]

Performs the conversion.

impl<'a> From<&'a str> for EZString
[src]

Performs the conversion.

impl<'a, 'b> Add<&'a str> for &'b EZString
[src]

The resulting type after applying the + operator

The method for the + operator

impl<'a> Add<&'a str> for EZString
[src]

The resulting type after applying the + operator

The method for the + operator

impl<'a, T: AsRef<str> + ?Sized> AddAssign<&'a T> for EZString
[src]

The method for the += operator

impl AddAssign<EZString> for EZString
[src]

The method for the += operator

impl<T: AsRef<str> + ?Sized> PartialEq<T> for EZString
[src]

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

This method tests for !=.

impl<'a> PartialEq<EZString> for &'a EZString
[src]

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

This method tests for !=.

impl<'a> PartialEq<String> for &'a EZString
[src]

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

This method tests for !=.