@@ -9,7 +9,35 @@ use core::ops::{Deref, DerefMut};
9
9
use serde:: de:: { Deserialize , Deserializer , Error , SeqAccess , Visitor } ;
10
10
use serde:: ser:: { Serialize , Serializer } ;
11
11
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
+ }
13
41
14
42
/// Wrapper around `[u8; N]` to serialize and deserialize efficiently.
15
43
///
@@ -191,15 +219,15 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
191
219
let mut idx = 0 ;
192
220
while let Some ( b) = visitor. next_element ( ) ? {
193
221
if idx >= N {
194
- return Err ( V :: Error :: custom ( ERROR_STRING ) ) ;
222
+ return Err ( V :: Error :: custom ( error_string_more ( N ) . as_ref ( ) ) ) ;
195
223
}
196
224
197
225
bytes[ idx] = b;
198
226
idx += 1 ;
199
227
}
200
228
201
229
if idx != N {
202
- return Err ( V :: Error :: custom ( ERROR_STRING ) ) ;
230
+ return Err ( V :: Error :: custom ( error_string ( N , idx ) . as_ref ( ) ) ) ;
203
231
}
204
232
205
233
Ok ( ByteArray :: from ( bytes) )
@@ -210,7 +238,9 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
210
238
E : Error ,
211
239
{
212
240
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 ( ) ) ) ?,
214
244
} )
215
245
}
216
246
@@ -222,7 +252,7 @@ impl<'de, const N: usize> Visitor<'de> for ByteArrayVisitor<N> {
222
252
bytes : v
223
253
. as_bytes ( )
224
254
. try_into ( )
225
- . map_err ( |_| E :: custom ( ERROR_STRING ) ) ?,
255
+ . map_err ( |_| E :: custom ( error_string ( N , v . len ( ) ) . as_ref ( ) ) ) ?,
226
256
} )
227
257
}
228
258
}
0 commit comments