|
1 |
| -use core::{cmp::Ordering, fmt, fmt::Write, hash, ops, str}; |
| 1 | +use core::{cmp::Ordering, fmt, fmt::Write, hash, iter, ops, str}; |
2 | 2 |
|
3 | 3 | use hash32;
|
4 | 4 |
|
@@ -307,6 +307,36 @@ impl<const N: usize> str::FromStr for String<N> {
|
307 | 307 | }
|
308 | 308 | }
|
309 | 309 |
|
| 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 | + |
310 | 340 | impl<const N: usize> Clone for String<N> {
|
311 | 341 | fn clone(&self) -> Self {
|
312 | 342 | Self {
|
@@ -558,6 +588,20 @@ mod tests {
|
558 | 588 | assert_eq!(e, ());
|
559 | 589 | }
|
560 | 590 |
|
| 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 | + |
561 | 605 | #[test]
|
562 | 606 | #[should_panic]
|
563 | 607 | fn from_panic() {
|
|
0 commit comments