#join #string #iterator #separator #items #io #write

string-join

A python-like way to join items in an iterator with a separator

3 releases

0.1.2 Feb 11, 2021
0.1.1 Feb 9, 2021
0.1.0 Feb 9, 2021

#1348 in Rust patterns

Download history 16/week @ 2023-12-18 9/week @ 2023-12-25 17/week @ 2024-01-08 10/week @ 2024-01-15 2/week @ 2024-01-22 3/week @ 2024-01-29 4/week @ 2024-02-05 22/week @ 2024-02-12 24/week @ 2024-02-19 46/week @ 2024-02-26 22/week @ 2024-03-04 60/week @ 2024-03-11 23/week @ 2024-03-18 26/week @ 2024-03-25 64/week @ 2024-04-01

178 downloads per month
Used in 4 crates (3 directly)

AGPL-3.0

15KB
168 lines

String join

A helper trait for joining an iterator by a string-like thing using a python-like syntax

Usage

use string_join::Join

"=>".join(["a", "b"].iter().cycle().take(5)); // => "a=>b=>a=>b=>a"
" ".join(&["a", "b", "c"]); // => "a b c"

let mut f = File::write("foo.txt").unwrap();
"\n".write_join(&mut f, &["a", "b", "c"]); // std::io::Result<5> (writes joined string to writer and returns a result
                                           // with either the number of bytes written, or a std::io::Error


lib.rs:

String join

Uses a python-like syntax to join any iterator-like thing with any string-like thing

Example

use string_join::Join;

assert_eq!("=".join(&["a", "b", "c"]), String::from("a=b=c"));

You can also write a joined collection directly to an io::Writer

use std::fs::File;
use string_join::display::Join;

let mut f = File::create("foo.txt")?;
"\n".write_join(&mut f, &['a', 'b', 'c'])?; // => writes `a\nb\nc` to the writer and returns
                                            //    the number of bytes written (5, in this case)

AsRef<str> vs Display

There are two ways to convert items in a collection to a joined string. If all the items, as well as the separator, implement AsRef<str>, then we only have to allocate a single string and can write bytes into it. However, this limits the types that we can join. If we instead limit the types we can join to types that implement Display, we can join a lot more types, with the tradeoff that a lot more allocations will be happening.

Therefore, there are two modules in this crate, string_join::as_ref and string_join::display. They both provide a trait called Join and both the traits have methods write_join and join. However, one is implemented for AsRef<str> types and one for Display types. This way, the user of the crate can decide which implementation they want to use.

To keep backwards compatibility, string_join::Join is the same as string_join::as_ref::Join.

No runtime deps