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

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

#1278 in Rust patterns

Download history 14/week @ 2024-07-21 42/week @ 2024-07-28 13/week @ 2024-08-04 14/week @ 2024-08-11 13/week @ 2024-08-18 17/week @ 2024-08-25 25/week @ 2024-09-01 19/week @ 2024-09-08 20/week @ 2024-09-15 34/week @ 2024-09-22 58/week @ 2024-09-29 7/week @ 2024-10-06 16/week @ 2024-10-13 19/week @ 2024-10-20 23/week @ 2024-10-27 29/week @ 2024-11-03

87 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