From 9207e7442fb290eff82a6a8d76a383c48a083d4b Mon Sep 17 00:00:00 2001 From: Aleksei Voronov Date: Sun, 23 Dec 2018 12:50:29 +0100 Subject: [PATCH] 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. --- src/array_string.rs | 11 +++++++++++ tests/tests.rs | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/src/array_string.rs b/src/array_string.rs index a52fb58..d83b463 100644 --- a/src/array_string.rs +++ b/src/array_string.rs @@ -5,6 +5,7 @@ use std::hash::{Hash, Hasher}; use std::ptr; use std::ops::{Deref, DerefMut}; use std::str; +use std::str::FromStr; use std::str::Utf8Error; use std::slice; @@ -507,6 +508,16 @@ impl Ord for ArrayString } } +impl FromStr for ArrayString + where A: Array + Copy +{ + type Err = CapacityError; + + fn from_str(s: &str) -> Result { + Self::from(s).map_err(CapacityError::simplify) + } +} + #[cfg(feature="serde-1")] /// Requires crate feature `"serde-1"` impl Serialize for ArrayString diff --git a/tests/tests.rs b/tests/tests.rs index 5c8a911..ae45121 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -487,6 +487,14 @@ fn test_string_from() { assert_eq!(u.len(), text.len()); } +#[test] +fn test_string_parse_from_str() { + let text = "hello world"; + let u: ArrayString<[_; 11]> = text.parse().unwrap(); + assert_eq!(&u, text); + assert_eq!(u.len(), text.len()); +} + #[test] fn test_string_from_bytes() { let text = "hello world";