Skip to content

Commit 4ad6060

Browse files
Merge #274
274: Implement FromIterator for String r=japaric a=VersBinarii Implements FromIterator trait on String. It also addresses issue: #245 Co-authored-by: VersBinarii <[email protected]>
2 parents 0cb35c7 + c7bc3c8 commit 4ad6060

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

src/string.rs

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::{cmp::Ordering, fmt, fmt::Write, hash, ops, str};
1+
use core::{cmp::Ordering, fmt, fmt::Write, hash, iter, ops, str};
22

33
use hash32;
44

@@ -307,6 +307,36 @@ impl<const N: usize> str::FromStr for String<N> {
307307
}
308308
}
309309

310+
impl<const N: usize> iter::FromIterator<char> for String<N> {
311+
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
312+
let mut new = String::new();
313+
for c in iter {
314+
new.push(c).unwrap();
315+
}
316+
new
317+
}
318+
}
319+
320+
impl<'a, const N: usize> iter::FromIterator<&'a char> for String<N> {
321+
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
322+
let mut new = String::new();
323+
for c in iter {
324+
new.push(*c).unwrap();
325+
}
326+
new
327+
}
328+
}
329+
330+
impl<'a, const N: usize> iter::FromIterator<&'a str> for String<N> {
331+
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
332+
let mut new = String::new();
333+
for c in iter {
334+
new.push_str(c).unwrap();
335+
}
336+
new
337+
}
338+
}
339+
310340
impl<const N: usize> Clone for String<N> {
311341
fn clone(&self) -> Self {
312342
Self {
@@ -558,6 +588,20 @@ mod tests {
558588
assert_eq!(e, ());
559589
}
560590

591+
#[test]
592+
fn from_iter() {
593+
let mut v: Vec<char, 5> = Vec::new();
594+
v.push('h').unwrap();
595+
v.push('e').unwrap();
596+
v.push('l').unwrap();
597+
v.push('l').unwrap();
598+
v.push('o').unwrap();
599+
let string1: String<5> = v.iter().collect(); //&char
600+
let string2: String<5> = "hello".chars().collect(); //char
601+
assert_eq!(string1, "hello");
602+
assert_eq!(string2, "hello");
603+
}
604+
561605
#[test]
562606
#[should_panic]
563607
fn from_panic() {

0 commit comments

Comments
 (0)