From 7301e928b06f1368cd8293820eb082171da2d515 Mon Sep 17 00:00:00 2001 From: Andrew Walbran Date: Fri, 19 Nov 2021 19:05:58 +0000 Subject: [PATCH] Implement Clone, Eq and PartialEq for Error. (#218) * Implement Eq and PartialEq for Error. * Implement Clone for Error. serde_json::Error doesn't implement Clone, so wrapped it in an Arc. --- src/errors.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index c6809ed..c695c74 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,6 +1,7 @@ use std::error::Error as StdError; use std::fmt; use std::result; +use std::sync::Arc; /// A crate private constructor for `Error`. pub(crate) fn new_error(kind: ErrorKind) -> Error { @@ -11,7 +12,7 @@ pub(crate) fn new_error(kind: ErrorKind) -> Error { pub type Result = result::Result; /// An error that can occur when encoding/decoding JWTs -#[derive(Debug)] +#[derive(Clone, Debug, Eq, PartialEq)] pub struct Error(Box); impl Error { @@ -32,7 +33,7 @@ impl Error { /// attribute makes sure clients don't count on exhaustive matching. /// (Otherwise, adding a new variant could break existing code.) #[non_exhaustive] -#[derive(Debug)] +#[derive(Clone, Debug)] pub enum ErrorKind { /// When a token doesn't have a valid JWT shape InvalidToken, @@ -70,7 +71,7 @@ pub enum ErrorKind { /// An error happened when decoding some base64 text Base64(base64::DecodeError), /// An error happened while serializing/deserializing JSON - Json(serde_json::Error), + Json(Arc), /// Some of the text was invalid UTF-8 Utf8(::std::string::FromUtf8Error), /// Something unspecified went wrong with crypto @@ -95,7 +96,7 @@ impl StdError for Error { ErrorKind::InvalidAlgorithmName => None, ErrorKind::InvalidKeyFormat => None, ErrorKind::Base64(ref err) => Some(err), - ErrorKind::Json(ref err) => Some(err), + ErrorKind::Json(ref err) => Some(err.as_ref()), ErrorKind::Utf8(ref err) => Some(err), ErrorKind::Crypto(ref err) => Some(err), } @@ -133,6 +134,9 @@ impl PartialEq for ErrorKind { } } +// Equality of ErrorKind is an equivalence relation: it is reflexive, symmetric and transitive. +impl Eq for ErrorKind {} + impl From for Error { fn from(err: base64::DecodeError) -> Error { new_error(ErrorKind::Base64(err)) @@ -141,7 +145,7 @@ impl From for Error { impl From for Error { fn from(err: serde_json::Error) -> Error { - new_error(ErrorKind::Json(err)) + new_error(ErrorKind::Json(Arc::new(err))) } }