Skip to content

Commit

Permalink
Add the lengths to the error message when alloc is available
Browse files Browse the repository at this point in the history
  • Loading branch information
sgued committed Aug 30, 2022
1 parent 1bdc428 commit c688fdc
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions src/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,35 @@ use core::ops::{Deref, DerefMut};
use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
use serde::ser::{Serialize, Serializer};

const ERROR_STRING: &str = "Expected a fixed amount of bytes, got a different amount";
#[cfg(any(feature = "alloc", feature = "std"))]
fn error_string(expected: usize, got: usize) -> impl AsRef<str> {
#[cfg(not(feature = "std"))]
let res = alloc::format!("Expected {} bytes, got {}", expected, got);

#[cfg(feature = "std")]
let res = format!("Expected {} bytes, got {}", expected, got);
res
}

#[cfg(all(not(feature = "alloc"), not(feature = "std")))]
fn error_string(_expected: usize, _got: usize) -> impl AsRef<str> {
"Expected a fixed amount of bytes, got a different amount"
}

#[cfg(any(feature = "alloc", feature = "std"))]
fn error_string_more(expected: usize) -> impl AsRef<str> {
#[cfg(not(feature = "std"))]
let res = alloc::format!("Got more than the expected {} bytes", expected);

#[cfg(feature = "std")]
let res = format!("Got more than the expected {} bytes", expected);
res
}

#[cfg(all(not(feature = "alloc"), not(feature = "std")))]
fn error_string_more(_expected: usize) -> impl AsRef<str> {
"Got more than the expected number of bytes"
}

/// Wrapper around `[u8; N]` to serialize and deserialize efficiently.
///
Expand Down Expand Up @@ -191,15 +219,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(ERROR_STRING));
return Err(V::Error::custom(error_string_more(N).as_ref()));
}

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

if idx != N {
return Err(V::Error::custom(ERROR_STRING));
return Err(V::Error::custom(error_string(N, idx).as_ref()));
}

Ok(ByteArray::from(bytes))
Expand All @@ -210,7 +238,9 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
E: Error,
{
Ok(ByteArray {
bytes: v.try_into().map_err(|_| E::custom(ERROR_STRING))?,
bytes: v
.try_into()
.map_err(|_| E::custom(error_string(N, v.len()).as_ref()))?,
})
}

Expand All @@ -222,7 +252,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
bytes: v
.as_bytes()
.try_into()
.map_err(|_| E::custom(ERROR_STRING))?,
.map_err(|_| E::custom(error_string(N, v.len()).as_ref()))?,
})
}
}
Expand Down

0 comments on commit c688fdc

Please sign in to comment.