Skip to content

Commit

Permalink
Remove unwrap from hex::encode
Browse files Browse the repository at this point in the history
  • Loading branch information
yukibtc committed Sep 12, 2023
1 parent 09909cb commit 6c26ca2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
13 changes: 8 additions & 5 deletions src/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use core::fmt;

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
/// Invalid char
InvalidChar,
/// An invalid character was found
InvalidHexCharacter { c: char, index: usize },
/// A hex string's length needs to be even, as two digits correspond to
Expand All @@ -20,6 +22,7 @@ impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidChar => write!(f, "Invalid char"),
Self::InvalidHexCharacter { c, index } => {
write!(f, "Invalid character {} at position {}", c, index)
}
Expand All @@ -28,17 +31,17 @@ impl fmt::Display for Error {
}
}

pub fn encode<T>(data: T) -> String
pub fn encode<T>(data: T) -> Result<String, Error>
where
T: AsRef<[u8]>,
{
let bytes: &[u8] = data.as_ref();
let mut hex = String::with_capacity(2 * bytes.len());
for byte in bytes.iter() {
hex.push(char::from_digit((byte >> 4) as u32, 16).unwrap());
hex.push(char::from_digit((byte & 0xF) as u32, 16).unwrap());
hex.push(char::from_digit((byte >> 4) as u32, 16).ok_or(Error::InvalidChar)?);
hex.push(char::from_digit((byte & 0xF) as u32, 16).ok_or(Error::InvalidChar)?);
}
hex.to_lowercase()
Ok(hex.to_lowercase())
}

const fn val(c: u8, idx: usize) -> Result<u8, Error> {
Expand Down Expand Up @@ -81,7 +84,7 @@ mod test {

#[test]
fn test_encode() {
assert_eq!(encode("foobar"), "666f6f626172");
assert_eq!(encode("foobar").unwrap(), "666f6f626172");
}

#[test]
Expand Down
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ impl Negentropy {
let k = self.items[i].get_id();
if !their_elems.contains(k) {
if self.is_initiator {
have_ids.push(hex::encode(k));
have_ids.push(hex::encode(k)?);
}
} else {
their_elems.remove(k);
Expand All @@ -373,7 +373,7 @@ impl Negentropy {

if self.is_initiator {
for k in their_elems.into_iter() {
need_ids.push(hex::encode(k));
need_ids.push(hex::encode(k)?);
}
} else {
let mut response_have_ids: Vec<&[u8]> = Vec::new();
Expand Down Expand Up @@ -587,7 +587,7 @@ impl Negentropy {
output.extend(self.encode_var_int(4)); // mode = Continue
}

Ok(hex::encode(output))
Ok(hex::encode(output)?)
}

fn get_bytes(&self, encoded: &mut &[u8], n: u64) -> Result<Vec<u8>, Error> {
Expand Down

0 comments on commit 6c26ca2

Please sign in to comment.