From f906a69aaada10afdd66a3e84b5c9248824e2023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20=E2=80=9Cpep=E2=80=9D=20Buquet?= Date: Tue, 30 Jun 2020 00:02:56 +0200 Subject: [PATCH] pkstring: implement TryFrom and TryFrom<&str> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Maxime “pep” Buquet --- pkstrings/src/lib.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/pkstrings/src/lib.rs b/pkstrings/src/lib.rs index d29f0a5..a8aa58b 100644 --- a/pkstrings/src/lib.rs +++ b/pkstrings/src/lib.rs @@ -135,3 +135,31 @@ impl Into> for PKString { vec } } + +impl TryFrom<&str> for PKString { + type Error = Error; + + fn try_from(data: &str) -> Result { + for chr in data.chars() { + if ! STRTOHEX.contains_key(&chr) { + return Err(Error::InvalidCharacter); + } + } + + Ok(PKString(String::from(data))) + } +} + +impl TryFrom for PKString { + type Error = Error; + + fn try_from(data: String) -> Result { + for chr in data.chars() { + if ! STRTOHEX.contains_key(&chr) { + return Err(Error::InvalidCharacter); + } + } + + Ok(PKString(data)) + } +}