Derive std::error::Error for error types

This commit is contained in:
Alex 2022-11-23 13:22:24 +01:00
parent 2abd28c663
commit b0bd343188
Signed by: lx
GPG key ID: 0E496D15096376BE
4 changed files with 36 additions and 34 deletions

View file

@ -2,7 +2,7 @@
name = "nettext"
description = "A text-based data format for cryptographic network protocols"
authors = ["Alex Auvolat <alex@adnab.me>"]
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"] }

View file

@ -20,7 +20,6 @@ impl enc::Encode for sign::SigningKeyPair<sign::PublicKey, sign::SecretKey> {
}
}
// ---- helpers ----
/// Compute the hash of a payload with default dryoc parameters and optionnal key
@ -30,10 +29,20 @@ pub fn compute_hash(bytes: &[u8], key: Option<&[u8; 32]>) -> generichash::Hash {
/// 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()
}

View file

@ -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<std::str::Utf8Error> 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<nom::Err<nom::error::Error<&'a [u8]>>> for DecodeError<'a> {
fn from(e: nom::Err<nom::error::Error<&'a [u8]>>) -> DecodeError<'a> {
match e {

View file

@ -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()"),
}
}
}