Skip to content

Commit 9207e74

Browse files
committed
Implement FromStr for ArrayString
This is very useful for generic code that may want to parse arbitrary input string into arbitrary other types. Limitations of the FromStr trait don't allow us to keep the original string slice inside the CapacityError, unfortunately.
1 parent cffdb46 commit 9207e74

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/array_string.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::hash::{Hash, Hasher};
55
use std::ptr;
66
use std::ops::{Deref, DerefMut};
77
use std::str;
8+
use std::str::FromStr;
89
use std::str::Utf8Error;
910
use std::slice;
1011

@@ -507,6 +508,16 @@ impl<A> Ord for ArrayString<A>
507508
}
508509
}
509510

511+
impl<A> FromStr for ArrayString<A>
512+
where A: Array<Item=u8> + Copy
513+
{
514+
type Err = CapacityError;
515+
516+
fn from_str(s: &str) -> Result<Self, Self::Err> {
517+
Self::from(s).map_err(CapacityError::simplify)
518+
}
519+
}
520+
510521
#[cfg(feature="serde-1")]
511522
/// Requires crate feature `"serde-1"`
512523
impl<A> Serialize for ArrayString<A>

tests/tests.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,14 @@ fn test_string_from() {
487487
assert_eq!(u.len(), text.len());
488488
}
489489

490+
#[test]
491+
fn test_string_parse_from_str() {
492+
let text = "hello world";
493+
let u: ArrayString<[_; 11]> = text.parse().unwrap();
494+
assert_eq!(&u, text);
495+
assert_eq!(u.len(), text.len());
496+
}
497+
490498
#[test]
491499
fn test_string_from_bytes() {
492500
let text = "hello world";

0 commit comments

Comments
 (0)