Crate sconcat [] [src]

String concatenation

Concatenatation of characters (char), string slices (&str) and owned strings (String).

A concatenation is started with the Cat element, and any number of characters, string slices or strings can be concatenated using the + operator. The concatenation can be converted or appended to a String.

If the concatenation is converted to a String, and it starts with an owned string with enough capacity to store the result, no allocations or reallocations take place. If the concatenation is appended to a String with enough capacity, no allocations or reallocations take place. Otherwise, one allocation or reallocation takes place.

Examples

A concatenation can be converted to a String.

use sconcat::Cat;

let cat1 = Cat + "Hello, " + "world! " + '☺';
// One allocation:
let s1 = String::from(cat1);
assert_eq!(s1, "Hello, world! ☺");

let cat2 = Cat + String::from("Hello, ") + "world! " + '☺';
// At most one reallocation as the initial `String` is resized:
let s2 = String::from(cat2);
assert_eq!(s2, "Hello, world! ☺");

A concatenation can also be appended to a String.

use sconcat::Cat;

let cat = Cat + "world! " + '☺';
let mut s = String::from("Hello, ");
// At most one reallocation as the initial `s` is resized:
s += cat;
assert_eq!(s, "Hello, world! ☺");

If the concatenation starts with a String that has enough reserved space, no reallocations will take place.

use sconcat::Cat;

let mut buf = String::from("Hello, ");
// 7 bytes for "world! " and 3 bytes for '☺'
buf.reserve(10);
let ptr = buf.as_ptr();
let cat = Cat + buf + "world! " + '☺';
let s2 = String::from(cat);
assert_eq!(s2, "Hello, world! ☺");
assert_eq!(s2.as_ptr(), ptr);

The concatenation also implements Display and Debug. However, using to_string() can result in multiple reallocations, so String::from(cat) is preferred over cat.to_string() where possible.

use sconcat::Cat;

let cat = Cat + "Hello, " + "world! " + '☺';
// `s1` can be resized up to three times:
let s1 = cat.to_string();
assert_eq!(s1, "Hello, world! ☺");
// Only one allocation here:
let s2 = String::from(cat);
assert_eq!(s2, "Hello, world! ☺");
// The following would fail as now `cat` has been moved:
// let s3 = String::from(cat);

Usage

To use sconcat in your crate, add extern crate sconcat; to the crate root and add sconcat as a dependency in Cargo.toml:

[dependencies]
sconcat = "0.2"

Optional features

The crate supports an optional feature fast_fmt, which adds a dependency on the fast_fmt crate. When the feature is enabled, the concatenation implements fast_fmt::Fmt. To enable the feature, the dependency in Cargo.toml can be added as:

[dependencies]
sconcat = { version = "0.2", features = ["fast_fmt"] }

Structs

Cat

A term that is used to start a string concatenation.