3 releases
0.1.2 | Feb 11, 2021 |
---|---|
0.1.1 | Feb 9, 2021 |
0.1.0 | Feb 9, 2021 |
#1278 in Rust patterns
87 downloads per month
Used in 4 crates
(3 directly)
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::Write
r
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
.