Crate joinery[][src]

Joinery provides generic joining of iterables with separators. While it is primarily designed the typical use case of writing to a writer or creating a String by joining a list of data with some kind of string separator (such as ", "), it is fully generic and can be used to combine any iterator or collection with any separator. In this way it is intended to supercede the existing SliceConcatExt::join method, which only works on slices and can only join with a matching type.

Examples

Create a comma separated list:

use joinery::Joinable;

let result = [1, 2, 3, 4].iter().join_with(", ").to_string();
assert_eq!(result, "1, 2, 3, 4")

Create a newline separated list, using a python-style syntax (with the separator at the beginning of the expression):

use joinery::Separator;

let result = '\n'.separate(&[1, 2, 3]).to_string();
assert_eq!(result, "1\n2\n3");

write! a comma-separated list:

use joinery::Joinable;

let join = vec![1, 2, 3, 4, 5].join_with(", ");

let mut result = String::new();

write!(&mut result, "Numbers: {}", join);
assert_eq!(result, "Numbers: 1, 2, 3, 4, 5");

// Note that joins are stateless; they can be reused after writing
let result2 = join.to_string();
assert_eq!(result2, "1, 2, 3, 4, 5");

Iterate over joins:

use joinery::{Joinable, JoinItem};

// Note that the collection values and the separator can be different types
let join = ["some", "sample", "text"].iter().join_with(' ');
let mut join_iter = join.iter();

assert_eq!(join_iter.next(), Some(JoinItem::Element(&"some")));
assert_eq!(join_iter.next(), Some(JoinItem::Separator(&' ')));
assert_eq!(join_iter.next(), Some(JoinItem::Element(&"sample")));
assert_eq!(join_iter.next(), Some(JoinItem::Separator(&' ')));
assert_eq!(join_iter.next(), Some(JoinItem::Element(&"text")));
assert_eq!(join_iter.next(), None);

Display the first 5 consecutive multiples of 1-5 on separate lines:

use joinery::Joinable;
let multiples = 1..=5;
let ranges = multiples.map(|m| (1..=5).map(move |n| n * m));

let lines = ranges.map(|range| range.join_with(", "));
let result = lines.join_with('\n').to_string();
assert_eq!(result, "1, 2, 3, 4, 5\n\
                    2, 4, 6, 8, 10\n\
                    3, 6, 9, 12, 15\n\
                    4, 8, 12, 16, 20\n\
                    5, 10, 15, 20, 25");

Modules

prelude

The joinery prelude

Structs

Join

The primary data structure for representing a joined sequence.

JoinIter

An iterator for a Join.

NoSeparator

Zero-size type representing the empty separator.

Enums

JoinItem

Enum representing the elements of a JoinIter.

Traits

Joinable

A trait for converting iterables and collections into Join instances.

Separator

A trait for using a separator to produce a Join.