Use expect/match instead of unwrap

This commit is contained in:
Wei Tang 2018-04-09 20:27:53 +08:00
parent 6ad1ef5d9e
commit eb548831ab
1 changed files with 34 additions and 33 deletions

View File

@ -87,12 +87,10 @@ impl From<Num> for usize {
impl Num { impl Num {
// Reduce the data size to its minimal, and then try to convert it to a num. // Reduce the data size to its minimal, and then try to convert it to a num.
pub fn minimally_encode(data: &[u8], max_size: usize) -> Result<Self, Error> { pub fn minimally_encode(data: &[u8], max_size: usize) -> Result<Self, Error> {
if data.is_empty() { match data.last() {
return Num::from_slice(data, true, max_size); None => Num::from_slice(data, true, max_size),
} Some(last) => {
if *last != 0x00 && *last != 0x80 {
let last = *data.last().unwrap();
if last != 0x00 && last != 0x80 {
return Num::from_slice(data, true, max_size); return Num::from_slice(data, true, max_size);
} }
@ -114,14 +112,17 @@ impl Num {
return Num::from_slice(&[], true, max_size); return Num::from_slice(&[], true, max_size);
} }
if data.last().unwrap() & 0x80 == 0x80 { let second_last = *data.last().expect("vec emptiness is checked above; qed");
data.push(last); if second_last & 0x80 == 0x80 {
data.push(*last);
} else { } else {
*data.last_mut().unwrap() |= last; *data.last_mut().expect("vec emptiness is checked above; qed") |= *last
} }
Num::from_slice(&data, true, max_size) Num::from_slice(&data, true, max_size)
} }
}
}
pub fn from_slice(data: &[u8], require_minimal: bool, max_size: usize) -> Result<Self, Error> { pub fn from_slice(data: &[u8], require_minimal: bool, max_size: usize) -> Result<Self, Error> {
if data.len() > max_size { if data.len() > max_size {