15
15
//! # Example
16
16
//!
17
17
//! ```
18
+ //! # #[cfg(not(feature = "alloc"))]
19
+ //! # let mut output = [0; 0x18];
20
+ //! #
21
+ //! # #[cfg(not(feature = "alloc"))]
22
+ //! # hex::encode_to_slice(b"Hello world!", &mut output).unwrap();
23
+ //! #
24
+ //! # #[cfg(not(feature = "alloc"))]
25
+ //! # let hex_string = ::core::str::from_utf8(&output).unwrap();
26
+ //! #
27
+ //! # #[cfg(feature = "alloc")]
18
28
//! let hex_string = hex::encode("Hello world!");
19
29
//!
20
30
//! println!("{}", hex_string); // Prints "48656c6c6f20776f726c6421"
27
37
#![ cfg_attr( docsrs, feature( doc_cfg) ) ]
28
38
#![ allow( clippy:: unreadable_literal) ]
29
39
30
- #[ cfg( not ( feature = "std" ) ) ]
40
+ #[ cfg( feature = "alloc" ) ]
31
41
extern crate alloc;
32
- #[ cfg( not ( feature = "std" ) ) ]
42
+ #[ cfg( feature = "alloc" ) ]
33
43
use alloc:: { string:: String , vec:: Vec } ;
34
44
35
45
use core:: iter;
@@ -41,7 +51,9 @@ pub use crate::error::FromHexError;
41
51
#[ cfg_attr( docsrs, doc( cfg( feature = "serde" ) ) ) ]
42
52
pub mod serde;
43
53
#[ cfg( feature = "serde" ) ]
44
- pub use crate :: serde:: { deserialize, serialize, serialize_upper} ;
54
+ pub use crate :: serde:: deserialize;
55
+ #[ cfg( all( feature = "alloc" , feature = "serde" ) ) ]
56
+ pub use crate :: serde:: { serialize, serialize_upper} ;
45
57
46
58
/// Encoding values as hex string.
47
59
///
@@ -95,7 +107,7 @@ impl<'a> Iterator for BytesToHexChars<'a> {
95
107
Some ( current) => Some ( current) ,
96
108
None => self . inner . next ( ) . map ( |byte| {
97
109
let current = self . table [ ( byte >> 4 ) as usize ] as char ;
98
- self . next = Some ( self . table [ ( byte & 0xf ) as usize ] as char ) ;
110
+ self . next = Some ( self . table [ ( byte & 0x0F ) as usize ] as char ) ;
99
111
current
100
112
} ) ,
101
113
}
@@ -117,6 +129,7 @@ impl<'a> iter::ExactSizeIterator for BytesToHexChars<'a> {
117
129
}
118
130
}
119
131
132
+ #[ inline]
120
133
fn encode_to_iter < T : iter:: FromIterator < char > > ( table : & ' static [ u8 ; 16 ] , source : & [ u8 ] ) -> T {
121
134
BytesToHexChars :: new ( source, table) . collect ( )
122
135
}
@@ -139,17 +152,14 @@ impl<T: AsRef<[u8]>> ToHex for T {
139
152
///
140
153
/// ```
141
154
/// use hex::FromHex;
155
+ /// use core::str;
142
156
///
143
- /// match Vec::from_hex("48656c6c6f20776f726c6421") {
144
- /// Ok(vec) => {
145
- /// for b in vec {
146
- /// println!("{}", b as char);
147
- /// }
148
- /// }
149
- /// Err(e) => {
150
- /// // Deal with the error ...
151
- /// }
152
- /// }
157
+ /// let buffer = <[u8; 12]>::from_hex("48656c6c6f20776f726c6421")?;
158
+ /// let string = str::from_utf8(&buffer).expect("invalid buffer length");
159
+ ///
160
+ /// println!("{}", string); // prints "Hello world!"
161
+ /// # assert_eq!("Hello world!", string);
162
+ /// # Ok::<(), hex::FromHexError>(())
153
163
/// ```
154
164
pub trait FromHex : Sized {
155
165
type Error ;
@@ -174,6 +184,7 @@ fn val(c: u8, idx: usize) -> Result<u8, FromHexError> {
174
184
}
175
185
}
176
186
187
+ #[ cfg( feature = "alloc" ) ]
177
188
impl FromHex for Vec < u8 > {
178
189
type Error = FromHexError ;
179
190
@@ -198,7 +209,7 @@ macro_rules! from_hex_array_impl {
198
209
type Error = FromHexError ;
199
210
200
211
fn from_hex<T : AsRef <[ u8 ] >>( hex: T ) -> Result <Self , Self :: Error > {
201
- let mut out = [ 0u8 ; $len] ;
212
+ let mut out = [ 0_u8 ; $len] ;
202
213
decode_to_slice( hex, & mut out as & mut [ u8 ] ) ?;
203
214
Ok ( out)
204
215
}
@@ -243,6 +254,8 @@ from_hex_array_impl! {
243
254
/// assert_eq!(hex::encode("Hello world!"), "48656c6c6f20776f726c6421");
244
255
/// assert_eq!(hex::encode(vec![1, 2, 3, 15, 16]), "0102030f10");
245
256
/// ```
257
+ #[ must_use]
258
+ #[ cfg( feature = "alloc" ) ]
246
259
pub fn encode < T : AsRef < [ u8 ] > > ( data : T ) -> String {
247
260
data. encode_hex ( )
248
261
}
@@ -257,6 +270,8 @@ pub fn encode<T: AsRef<[u8]>>(data: T) -> String {
257
270
/// assert_eq!(hex::encode_upper("Hello world!"), "48656C6C6F20776F726C6421");
258
271
/// assert_eq!(hex::encode_upper(vec![1, 2, 3, 15, 16]), "0102030F10");
259
272
/// ```
273
+ #[ must_use]
274
+ #[ cfg( feature = "alloc" ) ]
260
275
pub fn encode_upper < T : AsRef < [ u8 ] > > ( data : T ) -> String {
261
276
data. encode_hex_upper ( )
262
277
}
@@ -277,6 +292,7 @@ pub fn encode_upper<T: AsRef<[u8]>>(data: T) -> String {
277
292
/// assert_eq!(hex::decode("123"), Err(hex::FromHexError::OddLength));
278
293
/// assert!(hex::decode("foo").is_err());
279
294
/// ```
295
+ #[ cfg( feature = "alloc" ) ]
280
296
pub fn decode < T : AsRef < [ u8 ] > > ( data : T ) -> Result < Vec < u8 > , FromHexError > {
281
297
FromHex :: from_hex ( data)
282
298
}
@@ -316,11 +332,14 @@ pub fn decode_to_slice<T: AsRef<[u8]>>(data: T, out: &mut [u8]) -> Result<(), Fr
316
332
// (4, 5)
317
333
// (6, 7)
318
334
// ...
335
+ #[ inline]
319
336
fn generate_iter ( len : usize ) -> impl Iterator < Item = ( usize , usize ) > {
320
337
( 0 ..len) . step_by ( 2 ) . zip ( ( 0 ..len) . skip ( 1 ) . step_by ( 2 ) )
321
338
}
322
339
323
340
// the inverse of `val`.
341
+ #[ inline]
342
+ #[ must_use]
324
343
fn byte2hex ( byte : u8 , table : & [ u8 ; 16 ] ) -> ( u8 , u8 ) {
325
344
let high = table[ ( ( byte & 0xf0 ) >> 4 ) as usize ] ;
326
345
let low = table[ ( byte & 0x0f ) as usize ] ;
@@ -350,7 +369,11 @@ pub fn encode_to_slice<T: AsRef<[u8]>>(input: T, output: &mut [u8]) -> Result<()
350
369
return Err ( FromHexError :: InvalidStringLength ) ;
351
370
}
352
371
353
- for ( byte, ( i, j) ) in input. as_ref ( ) . iter ( ) . zip ( generate_iter ( input. as_ref ( ) . len ( ) * 2 ) ) {
372
+ for ( byte, ( i, j) ) in input
373
+ . as_ref ( )
374
+ . iter ( )
375
+ . zip ( generate_iter ( input. as_ref ( ) . len ( ) * 2 ) )
376
+ {
354
377
let ( high, low) = byte2hex ( * byte, HEX_CHARS_LOWER ) ;
355
378
output[ i] = high;
356
379
output[ j] = low;
@@ -362,11 +385,12 @@ pub fn encode_to_slice<T: AsRef<[u8]>>(input: T, output: &mut [u8]) -> Result<()
362
385
#[ cfg( test) ]
363
386
mod test {
364
387
use super :: * ;
365
- #[ cfg( not ( feature = "std" ) ) ]
388
+ #[ cfg( feature = "alloc" ) ]
366
389
use alloc:: string:: ToString ;
367
390
use pretty_assertions:: assert_eq;
368
391
369
392
#[ test]
393
+ #[ cfg( feature = "alloc" ) ]
370
394
fn test_gen_iter ( ) {
371
395
let mut result = Vec :: new ( ) ;
372
396
result. push ( ( 0 , 1 ) ) ;
@@ -405,38 +429,53 @@ mod test {
405
429
406
430
let mut output_3 = [ 0 ; 4 ] ;
407
431
408
- assert_eq ! ( decode_to_slice( b"6" , & mut output_3) , Err ( FromHexError :: OddLength ) ) ;
432
+ assert_eq ! (
433
+ decode_to_slice( b"6" , & mut output_3) ,
434
+ Err ( FromHexError :: OddLength )
435
+ ) ;
409
436
}
410
437
411
438
#[ test]
439
+ #[ cfg( feature = "alloc" ) ]
412
440
fn test_encode ( ) {
413
441
assert_eq ! ( encode( "foobar" ) , "666f6f626172" ) ;
414
442
}
415
443
416
444
#[ test]
445
+ #[ cfg( feature = "alloc" ) ]
417
446
fn test_decode ( ) {
418
- assert_eq ! ( decode( "666f6f626172" ) , Ok ( String :: from( "foobar" ) . into_bytes( ) ) ) ;
447
+ assert_eq ! (
448
+ decode( "666f6f626172" ) ,
449
+ Ok ( String :: from( "foobar" ) . into_bytes( ) )
450
+ ) ;
419
451
}
420
452
421
453
#[ test]
454
+ #[ cfg( feature = "alloc" ) ]
422
455
pub fn test_from_hex_okay_str ( ) {
423
456
assert_eq ! ( Vec :: from_hex( "666f6f626172" ) . unwrap( ) , b"foobar" ) ;
424
457
assert_eq ! ( Vec :: from_hex( "666F6F626172" ) . unwrap( ) , b"foobar" ) ;
425
458
}
426
459
427
460
#[ test]
461
+ #[ cfg( feature = "alloc" ) ]
428
462
pub fn test_from_hex_okay_bytes ( ) {
429
463
assert_eq ! ( Vec :: from_hex( b"666f6f626172" ) . unwrap( ) , b"foobar" ) ;
430
464
assert_eq ! ( Vec :: from_hex( b"666F6F626172" ) . unwrap( ) , b"foobar" ) ;
431
465
}
432
466
433
467
#[ test]
468
+ #[ cfg( feature = "alloc" ) ]
434
469
pub fn test_invalid_length ( ) {
435
470
assert_eq ! ( Vec :: from_hex( "1" ) . unwrap_err( ) , FromHexError :: OddLength ) ;
436
- assert_eq ! ( Vec :: from_hex( "666f6f6261721" ) . unwrap_err( ) , FromHexError :: OddLength ) ;
471
+ assert_eq ! (
472
+ Vec :: from_hex( "666f6f6261721" ) . unwrap_err( ) ,
473
+ FromHexError :: OddLength
474
+ ) ;
437
475
}
438
476
439
477
#[ test]
478
+ #[ cfg( feature = "alloc" ) ]
440
479
pub fn test_invalid_char ( ) {
441
480
assert_eq ! (
442
481
Vec :: from_hex( "66ag" ) . unwrap_err( ) ,
@@ -445,11 +484,13 @@ mod test {
445
484
}
446
485
447
486
#[ test]
487
+ #[ cfg( feature = "alloc" ) ]
448
488
pub fn test_empty ( ) {
449
489
assert_eq ! ( Vec :: from_hex( "" ) . unwrap( ) , b"" ) ;
450
490
}
451
491
452
492
#[ test]
493
+ #[ cfg( feature = "alloc" ) ]
453
494
pub fn test_from_hex_whitespace ( ) {
454
495
assert_eq ! (
455
496
Vec :: from_hex( "666f 6f62617" ) . unwrap_err( ) ,
@@ -471,6 +512,7 @@ mod test {
471
512
}
472
513
473
514
#[ test]
515
+ #[ cfg( feature = "alloc" ) ]
474
516
fn test_to_hex ( ) {
475
517
assert_eq ! (
476
518
[ 0x66 , 0x6f , 0x6f , 0x62 , 0x61 , 0x72 ] . encode_hex:: <String >( ) ,
0 commit comments