blob: fb9b81207c22dd3d32c05169da8c09d0257ecbd9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
use crate::ReadSeek;
use byteorder::ReadBytesExt;
use std::char::decode_utf16;
use std::io;
pub fn to_hex_string(bytes: &[u8]) -> String {
let strs: Vec<String> = bytes.iter().map(|b| format!("{:02X}", b)).collect();
strs.join("")
}
/// Reads a utf16 string from the given stream.
/// If `len` is given, exactly `len` u16 values are read from the stream.
/// If `len` is None, the string is assumed to be null terminated and the stream will be read to the first null (0).
pub fn read_utf16_string<T: ReadSeek>(stream: &mut T, len: Option<usize>) -> io::Result<String> {
let mut buffer = match len {
Some(len) => Vec::with_capacity(len),
None => Vec::new(),
};
match len {
Some(len) => {
for _ in 0..len {
let next_char = stream.read_u16::<byteorder::LittleEndian>()?;
buffer.push(next_char);
}
}
None => loop {
let next_char = stream.read_u16::<byteorder::LittleEndian>()?;
if next_char == 0 {
break;
}
buffer.push(next_char);
},
}
decode_utf16(buffer.into_iter())
.map(|r| r.map_err(|_e| io::Error::from(io::ErrorKind::InvalidData)))
.collect()
}
|