Skip to content

Commit c688fdc

Browse files
committed
Add the lengths to the error message when alloc is available
1 parent 1bdc428 commit c688fdc

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

src/bytearray.rs

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,35 @@ use core::ops::{Deref, DerefMut};
99
use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
1010
use serde::ser::{Serialize, Serializer};
1111

12-
const ERROR_STRING: &str = "Expected a fixed amount of bytes, got a different amount";
12+
#[cfg(any(feature = "alloc", feature = "std"))]
13+
fn error_string(expected: usize, got: usize) -> impl AsRef<str> {
14+
#[cfg(not(feature = "std"))]
15+
let res = alloc::format!("Expected {} bytes, got {}", expected, got);
16+
17+
#[cfg(feature = "std")]
18+
let res = format!("Expected {} bytes, got {}", expected, got);
19+
res
20+
}
21+
22+
#[cfg(all(not(feature = "alloc"), not(feature = "std")))]
23+
fn error_string(_expected: usize, _got: usize) -> impl AsRef<str> {
24+
"Expected a fixed amount of bytes, got a different amount"
25+
}
26+
27+
#[cfg(any(feature = "alloc", feature = "std"))]
28+
fn error_string_more(expected: usize) -> impl AsRef<str> {
29+
#[cfg(not(feature = "std"))]
30+
let res = alloc::format!("Got more than the expected {} bytes", expected);
31+
32+
#[cfg(feature = "std")]
33+
let res = format!("Got more than the expected {} bytes", expected);
34+
res
35+
}
36+
37+
#[cfg(all(not(feature = "alloc"), not(feature = "std")))]
38+
fn error_string_more(_expected: usize) -> impl AsRef<str> {
39+
"Got more than the expected number of bytes"
40+
}
1341

1442
/// Wrapper around `[u8; N]` to serialize and deserialize efficiently.
1543
///
@@ -191,15 +219,15 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
191219
let mut idx = 0;
192220
while let Some(b) = visitor.next_element()? {
193221
if idx >= N {
194-
return Err(V::Error::custom(ERROR_STRING));
222+
return Err(V::Error::custom(error_string_more(N).as_ref()));
195223
}
196224

197225
bytes[idx] = b;
198226
idx += 1;
199227
}
200228

201229
if idx != N {
202-
return Err(V::Error::custom(ERROR_STRING));
230+
return Err(V::Error::custom(error_string(N, idx).as_ref()));
203231
}
204232

205233
Ok(ByteArray::from(bytes))
@@ -210,7 +238,9 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
210238
E: Error,
211239
{
212240
Ok(ByteArray {
213-
bytes: v.try_into().map_err(|_| E::custom(ERROR_STRING))?,
241+
bytes: v
242+
.try_into()
243+
.map_err(|_| E::custom(error_string(N, v.len()).as_ref()))?,
214244
})
215245
}
216246

@@ -222,7 +252,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
222252
bytes: v
223253
.as_bytes()
224254
.try_into()
225-
.map_err(|_| E::custom(ERROR_STRING))?,
255+
.map_err(|_| E::custom(error_string(N, v.len()).as_ref()))?,
226256
})
227257
}
228258
}

0 commit comments

Comments
 (0)