Reduce unwrap and expect usage

This commit is contained in:
link2xt
2022-05-21 14:12:23 +00:00
parent 9549aca48b
commit 73341394ee
16 changed files with 134 additions and 130 deletions

View File

@@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use std::fmt;
use std::io::Cursor;
use anyhow::{format_err, Context as _, Result};
use anyhow::{ensure, Context as _, Result};
use async_trait::async_trait;
use num_traits::FromPrimitive;
use pgp::composed::Deserializable;
@@ -82,7 +82,7 @@ pub trait DcKey: Serialize + Deserializable + KeyTrait + Clone {
/// The fingerprint for the key.
fn fingerprint(&self) -> Fingerprint {
Fingerprint::new(KeyTrait::fingerprint(self)).expect("Invalid fingerprint from rpgp")
Fingerprint::new(KeyTrait::fingerprint(self))
}
}
@@ -320,11 +320,9 @@ pub async fn store_self_keypair(
pub struct Fingerprint(Vec<u8>);
impl Fingerprint {
pub fn new(v: Vec<u8>) -> Result<Fingerprint> {
match v.len() {
20 => Ok(Fingerprint(v)),
_ => Err(format_err!("Wrong fingerprint length")),
}
pub fn new(v: Vec<u8>) -> Fingerprint {
debug_assert_eq!(v.len(), 20);
Fingerprint(v)
}
/// Make a hex string from the fingerprint.
@@ -364,14 +362,15 @@ impl fmt::Display for Fingerprint {
impl std::str::FromStr for Fingerprint {
type Err = anyhow::Error;
fn from_str(input: &str) -> std::result::Result<Self, Self::Err> {
fn from_str(input: &str) -> Result<Self> {
let hex_repr: String = input
.to_uppercase()
.chars()
.filter(|&c| ('0'..='9').contains(&c) || ('A'..='F').contains(&c))
.collect();
let v: Vec<u8> = hex::decode(hex_repr)?;
let fp = Fingerprint::new(v)?;
let v: Vec<u8> = hex::decode(&hex_repr)?;
ensure!(v.len() == 20, "wrong fingerprint length: {}", hex_repr);
let fp = Fingerprint::new(v);
Ok(fp)
}
}
@@ -589,8 +588,7 @@ i8pcjGO+IZffvyZJVRWfVooBJmWWbPB1pueo3tx8w3+fcuzpxz+RLFKaPyqXO+dD
fn test_fingerprint_from_str() {
let res = Fingerprint::new(vec![
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
])
.unwrap();
]);
let fp: Fingerprint = "0102030405060708090A0B0c0d0e0F1011121314".parse().unwrap();
assert_eq!(fp, res);
@@ -607,8 +605,7 @@ i8pcjGO+IZffvyZJVRWfVooBJmWWbPB1pueo3tx8w3+fcuzpxz+RLFKaPyqXO+dD
fn test_fingerprint_hex() {
let fp = Fingerprint::new(vec![
1, 2, 4, 8, 16, 32, 64, 128, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
])
.unwrap();
]);
assert_eq!(fp.hex(), "0102040810204080FF0A0B0C0D0E0F1011121314");
}
@@ -616,8 +613,7 @@ i8pcjGO+IZffvyZJVRWfVooBJmWWbPB1pueo3tx8w3+fcuzpxz+RLFKaPyqXO+dD
fn test_fingerprint_to_string() {
let fp = Fingerprint::new(vec![
1, 2, 4, 8, 16, 32, 64, 128, 255, 1, 2, 4, 8, 16, 32, 64, 128, 255, 19, 20,
])
.unwrap();
]);
assert_eq!(
fp.to_string(),
"0102 0408 1020 4080 FF01\n0204 0810 2040 80FF 1314"