From b0bd343188c604881df74c8b53950a322d279fed Mon Sep 17 00:00:00 2001 From: Alex Auvolat Date: Wed, 23 Nov 2022 13:22:24 +0100 Subject: [PATCH] Derive std::error::Error for error types --- Cargo.toml | 3 ++- src/crypto/mod.rs | 19 ++++++++++++++----- src/dec/error.rs | 25 +++++++++++-------------- src/enc/error.rs | 23 +++++++++-------------- 4 files changed, 36 insertions(+), 34 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d0ba9ae..b7e62e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "nettext" description = "A text-based data format for cryptographic network protocols" authors = ["Alex Auvolat "] -version = "0.2.2" +version = "0.2.3" edition = "2021" license = "AGPL-3.0" readme = "README.md" @@ -12,6 +12,7 @@ readme = "README.md" [dependencies] nom = "7.1" base64 = "0.13" +err-derive = "0.3" dryoc = { version = "0.4", optional = true } serde = { version = "1.0", optional = true, features = ["derive"] } diff --git a/src/crypto/mod.rs b/src/crypto/mod.rs index 82b726b..a5bce00 100644 --- a/src/crypto/mod.rs +++ b/src/crypto/mod.rs @@ -20,20 +20,29 @@ impl enc::Encode for sign::SigningKeyPair { } } - // ---- helpers ---- /// Compute the hash of a payload with default dryoc parameters and optionnal key pub fn compute_hash(bytes: &[u8], key: Option<&[u8; 32]>) -> generichash::Hash { - generichash::GenericHash::hash_with_defaults(bytes, key).unwrap() + generichash::GenericHash::hash_with_defaults(bytes, key).unwrap() } /// Compute the ed25519 signature of a message using a secret key pub fn compute_signature(message: &[u8], secret_key: &sign::SecretKey) -> sign::Signature { - SigningKeyPair::from_secret_key(secret_key.clone()).sign_with_defaults(message).unwrap().into_parts().0 + SigningKeyPair::from_secret_key(secret_key.clone()) + .sign_with_defaults(message) + .unwrap() + .into_parts() + .0 } /// Verify the ed25519 signature of a message using a public key -pub fn verify_signature(signature: &sign::Signature, message: &[u8], public_key: &sign::PublicKey) -> bool { - sign::SignedMessage::from_parts(signature.clone(), message).verify(public_key).is_ok() +pub fn verify_signature( + signature: &sign::Signature, + message: &[u8], + public_key: &sign::PublicKey, +) -> bool { + sign::SignedMessage::from_parts(signature.clone(), message) + .verify(public_key) + .is_ok() } diff --git a/src/dec/error.rs b/src/dec/error.rs index 9f7e224..a318e07 100644 --- a/src/dec/error.rs +++ b/src/dec/error.rs @@ -1,19 +1,26 @@ -use std::fmt; +use err_derive::Error; use crate::dec::debug; /// The type of errors returned by helper functions on `Term` -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Error)] pub enum TypeError { /// The term could not be decoded in the given type + #[error(display = "Not a {}", _0)] WrongType(&'static str), + /// The term is not an array of the requested length + #[error(display = "Expected {} items, got {}", _0, _1)] WrongLength(usize, usize), + /// The dictionnary is missing a key + #[error(display = "Missing key `{}` in dict", _0)] MissingKey(String), /// The dictionnary contains an invalid key + #[error(display = "Spurrious/unexpected key `{}` in dict", _0)] UnexpectedKey(String), /// The underlying raw string contains garbage (should not happen in theory) + #[error(display = "Garbage in underlying data")] Garbage, } @@ -23,18 +30,6 @@ impl From for TypeError { } } -impl std::fmt::Display for TypeError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - TypeError::WrongType(t) => write!(f, "Not a {}", t), - TypeError::WrongLength(n, m) => write!(f, "Expected {} items, got {}", m, n), - TypeError::MissingKey(k) => write!(f, "Missing key `{}` in dict", k), - TypeError::UnexpectedKey(k) => write!(f, "Spurrious/unexpected key `{}` in dict", k), - TypeError::Garbage => write!(f, "Garbage in underlying data"), - } - } -} - // ---- /// The error kind returned by the `decode` function. @@ -64,6 +59,8 @@ impl<'a> std::fmt::Debug for DecodeError<'a> { } } +impl<'a> std::error::Error for DecodeError<'a> {} + impl<'a> From>> for DecodeError<'a> { fn from(e: nom::Err>) -> DecodeError<'a> { match e { diff --git a/src/enc/error.rs b/src/enc/error.rs index 487b088..666e85f 100644 --- a/src/enc/error.rs +++ b/src/enc/error.rs @@ -1,23 +1,18 @@ -use std::fmt; +use err_derive::Error; /// An error that happenned when creating a nettext encoder term -#[derive(Debug)] +#[derive(Debug, Error)] pub enum Error { + #[error(display = "Invalid character '{}'", _0)] InvalidCharacter(u8), + #[error(display = "Invalid RAW nettext litteral")] InvalidRaw, + #[error(display = "Tried to insert into a term that isn't a dictionnary")] NotADictionnary, + #[error(display = "Duplicate key: {}", _0)] DuplicateKey(String), + #[error( + display = "Refusing to build nested lists with list(), use either list_flatten() or list_nested()" + )] ListInList, } - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Error::InvalidCharacter(c) => write!(f, "Invalid character '{}'", *c as char), - Error::InvalidRaw => write!(f, "Invalid RAW nettext litteral"), - Error::NotADictionnary => write!(f, "Tried to insert into a term that isn't a dictionnary"), - Error::DuplicateKey(s) => write!(f, "Duplicate dict key: {}", s), - Error::ListInList => write!(f, "Refusing to build nested lists with list(), use either list_flatten() or list_nested()"), - } - } -}