Skip to content

Commit 985cd97

Browse files
committed
Use Error::invalid_length instead of a custom error function
1 parent 5b80ef9 commit 985cd97

File tree

1 file changed

+4
-34
lines changed

1 file changed

+4
-34
lines changed

src/bytearray.rs

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

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-
}
41-
4212
/// Wrapper around `[u8; N]` to serialize and deserialize efficiently.
4313
///
4414
/// ```
@@ -219,15 +189,15 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
219189
let mut idx = 0;
220190
while let Some(b) = visitor.next_element()? {
221191
if idx >= N {
222-
return Err(V::Error::custom(error_string_more(N).as_ref()));
192+
return Err(V::Error::invalid_length(N, &self));
223193
}
224194

225195
bytes[idx] = b;
226196
idx += 1;
227197
}
228198

229199
if idx != N {
230-
return Err(V::Error::custom(error_string(N, idx).as_ref()));
200+
return Err(V::Error::invalid_length(N, &self));
231201
}
232202

233203
Ok(ByteArray::from(bytes))
@@ -240,7 +210,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
240210
Ok(ByteArray {
241211
bytes: v
242212
.try_into()
243-
.map_err(|_| E::custom(error_string(N, v.len()).as_ref()))?,
213+
.map_err(|_| E::invalid_length(v.len(), &self))?,
244214
})
245215
}
246216

@@ -252,7 +222,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
252222
bytes: v
253223
.as_bytes()
254224
.try_into()
255-
.map_err(|_| E::custom(error_string(N, v.len()).as_ref()))?,
225+
.map_err(|_| E::invalid_length(v.len(), &self))?,
256226
})
257227
}
258228
}

0 commit comments

Comments
 (0)