aquatic_ws: deserialize 20 byte strings: improve code

This commit is contained in:
Joakim Frostegård 2020-05-11 23:35:45 +02:00
parent 761952513f
commit 9030944c02

View file

@ -20,28 +20,28 @@ impl<'de> Visitor<'de> for TwentyByteVisitor {
// var infoHash = 'abcd..'; // 40 hexadecimals // var infoHash = 'abcd..'; // 40 hexadecimals
// Buffer.from(infoHash, 'hex').toString('binary'); // Buffer.from(infoHash, 'hex').toString('binary');
// ``` // ```
// which produces a UTF16 string with each char having only the low // which seemingly produces a UTF16 string with each char having only
// byte set. Here, we extract it by casting to u8. // the "low byte" set. Here, we extract it by casting it to an u8.
let mut arr = [0u8; 20]; let mut arr = [0u8; 20];
let mut max_i = 0; let mut char_iter = value.chars();
for (i, (a, c)) in arr.iter_mut().zip(value.chars()).enumerate(){ for a in arr.iter_mut(){
if c as u32 > 255 { if let Some(c) = char_iter.next(){
return Err(E::custom(format!( if c as u32 > 255 {
"character not in single byte range: {}", return Err(E::custom(format!(
c "character not in single byte range: {:#?}",
))) c
)));
}
*a = c as u8;
} else {
return Err(E::custom(format!("not 20 bytes: {:#?}", value)));
} }
*a = c as u8;
max_i = i;
} }
if max_i == 19 { Ok(arr)
Ok(arr)
} else {
Err(E::custom(format!("not 20 bytes: {}", value)))
}
} }
} }