summaryrefslogtreecommitdiff
path: root/src/string.rs
diff options
context:
space:
mode:
authorGravatar VersBinarii <versbinarii@gmail.com> 2022-03-15 15:36:10 +0100
committerGravatar VersBinarii <versbinarii@gmail.com> 2022-03-15 15:36:10 +0100
commitc7bc3c8166e3dd48df3df606c96c12b641b36181 (patch)
treeeb9991dd80aa146b7852a8a8d06937ebccdf42cc /src/string.rs
parent9fb9cd70451bd8c4e6ccf51ca3c77b8cb033fc27 (diff)
downloadheapless-c7bc3c8166e3dd48df3df606c96c12b641b36181.tar.gz
heapless-c7bc3c8166e3dd48df3df606c96c12b641b36181.tar.zst
heapless-c7bc3c8166e3dd48df3df606c96c12b641b36181.zip
Implement FromIterator for String
Diffstat (limited to '')
-rw-r--r--src/string.rs46
1 files changed, 45 insertions, 1 deletions
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<const N: usize> str::FromStr for String<N> {
}
}
+impl<const N: usize> iter::FromIterator<char> for String<N> {
+ fn from_iter<T: IntoIterator<Item = char>>(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<N> {
+ fn from_iter<T: IntoIterator<Item = &'a char>>(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<N> {
+ fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
+ let mut new = String::new();
+ for c in iter {
+ new.push_str(c).unwrap();
+ }
+ new
+ }
+}
+
impl<const N: usize> Clone for String<N> {
fn clone(&self) -> Self {
Self {
@@ -559,6 +589,20 @@ mod tests {
}
#[test]
+ fn from_iter() {
+ let mut v: Vec<char, 5> = 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() {
let _: String<4> = String::from("12345");