diff --git a/src/string.rs b/src/string.rs index faec39e1..c995622f 100644 --- a/src/string.rs +++ b/src/string.rs @@ -1,4 +1,4 @@ -use core::{cmp::Ordering, fmt, fmt::Write, hash, ops, str}; +use core::{cmp::Ordering, fmt, fmt::Write, hash, iter, ops, str}; use hash32; @@ -307,6 +307,36 @@ impl str::FromStr for String { } } +impl iter::FromIterator for String { + fn from_iter>(iter: T) -> Self { + let mut new = String::new(); + for c in iter { + new.push(c).unwrap(); + } + new + } +} + +impl<'a, const N: usize> iter::FromIterator<&'a char> for String { + fn from_iter>(iter: T) -> Self { + let mut new = String::new(); + for c in iter { + new.push(*c).unwrap(); + } + new + } +} + +impl<'a, const N: usize> iter::FromIterator<&'a str> for String { + fn from_iter>(iter: T) -> Self { + let mut new = String::new(); + for c in iter { + new.push_str(c).unwrap(); + } + new + } +} + impl Clone for String { fn clone(&self) -> Self { Self { @@ -558,6 +588,20 @@ mod tests { assert_eq!(e, ()); } + #[test] + fn from_iter() { + let mut v: Vec = Vec::new(); + v.push('h').unwrap(); + v.push('e').unwrap(); + v.push('l').unwrap(); + v.push('l').unwrap(); + v.push('o').unwrap(); + let string1: String<5> = v.iter().collect(); //&char + let string2: String<5> = "hello".chars().collect(); //char + assert_eq!(string1, "hello"); + assert_eq!(string2, "hello"); + } + #[test] #[should_panic] fn from_panic() {