From de649ea58966273392f4ab09f2bb72bb75650ae2 Mon Sep 17 00:00:00 2001 From: Justus Winter Date: Fri, 15 Jan 2021 09:51:27 +0100 Subject: net: Make conversion from u8 to Policy fallible. --- net/src/lib.rs | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) (limited to 'net') diff --git a/net/src/lib.rs b/net/src/lib.rs index dda95da8..450375cf 100644 --- a/net/src/lib.rs +++ b/net/src/lib.rs @@ -33,7 +33,7 @@ use hyper_tls::HttpsConnector; use native_tls::{Certificate, TlsConnector}; use percent_encoding::{percent_encode, AsciiSet, CONTROLS}; -use std::convert::From; +use std::convert::{From, TryFrom}; use std::fmt; use std::io::Cursor; use url::Url; @@ -114,20 +114,32 @@ impl<'a> From<&'a Policy> for u8 { } } +impl TryFrom for Policy { + type Error = TryFromU8Error; -// XXX: TryFrom would be nice. -impl From for Policy { - fn from(policy: u8) -> Self { + fn try_from(policy: u8) -> std::result::Result { match policy { - 0 => Policy::Offline, - 1 => Policy::Anonymized, - 2 => Policy::Encrypted, - 3 => Policy::Insecure, - n => panic!("Bad network policy: {}", n), + 0 => Ok(Policy::Offline), + 1 => Ok(Policy::Anonymized), + 2 => Ok(Policy::Encrypted), + 3 => Ok(Policy::Insecure), + n => Err(TryFromU8Error(n)), } } } +/// Indicates errors converting `u8` to `Policy`. +#[derive(Debug)] +pub struct TryFromU8Error(u8); + +impl fmt::Display for TryFromU8Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Bad network policy: {}", self.0) + } +} + +impl std::error::Error for TryFromU8Error {} + /// For accessing keyservers using HKP. pub struct KeyServer { client: Box, -- cgit v1.2.3