Skip to content

Commit

Permalink
Fix no_std issues
Browse files Browse the repository at this point in the history
  • Loading branch information
sgued committed Jul 16, 2022
1 parent 189da0d commit e3a2120
Showing 1 changed file with 6 additions and 35 deletions.
41 changes: 6 additions & 35 deletions src/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use core::ops::{Deref, DerefMut};
use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
use serde::ser::{Serialize, Serializer};

const ERROR_STRING: &'static str = "Expected a fixed amount of bytes, got a different amount";

/// Wrapper around `[u8; N]` to serialize and deserialize efficiently.
///
/// ```
Expand Down Expand Up @@ -189,21 +191,15 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
let mut idx = 0;
while let Some(b) = visitor.next_element()? {
if idx >= N {
return Err(V::Error::custom(format!(
"Expected [u8; {0}], got more than {0} elements",
N
)));
return Err(V::Error::custom(ERROR_STRING));
}

bytes[idx] = b;
idx += 1;
}

if idx != N {
return Err(V::Error::custom(format!(
"Expected [u8; {}], got [u8; {}]",
N, idx
)));
return Err(V::Error::custom(ERROR_STRING));
}

Ok(ByteArray::from(bytes))
Expand All @@ -214,20 +210,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
E: Error,
{
Ok(ByteArray {
bytes: v
.try_into()
.map_err(|_| E::custom(format!("Expected [u8; {}]", N)))?,
})
}

fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteArray<N>, E>
where
E: Error,
{
Ok(ByteArray {
bytes: v
.try_into()
.map_err(|_| E::custom(format!("Expected [u8; {}]", N)))?,
bytes: v.try_into().map_err(|_| E::custom(ERROR_STRING))?,
})
}

Expand All @@ -239,19 +222,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
bytes: v
.as_bytes()
.try_into()
.map_err(|_| E::custom(format!("Expected [u8; {}]", N)))?,
})
}

fn visit_string<E>(self, v: String) -> Result<ByteArray<N>, E>
where
E: Error,
{
Ok(ByteArray {
bytes: v
.as_bytes()
.try_into()
.map_err(|_| E::custom(format!("Expected [u8; {}]", N)))?,
.map_err(|_| E::custom(ERROR_STRING))?,
})
}
}
Expand Down

0 comments on commit e3a2120

Please sign in to comment.