add helper trait for reading fixed-length byte arrays
a minor thing, but helps turn this pattern into a nice 1-liner
This commit is contained in:
parent
f2ec776d3f
commit
c59d115aba
|
@ -1,3 +1,6 @@
|
|||
use byteorder::ReadBytesExt;
|
||||
use std::io::Error;
|
||||
|
||||
pub trait FixedLengthByteArrays {
|
||||
fn as_unpadded_slice(&self) -> &[u8];
|
||||
fn to_fixed_length(&self, length: usize) -> Vec<u8>;
|
||||
|
@ -30,6 +33,19 @@ impl<T: AsRef<[u8]> + ?Sized> FixedLengthByteArrays for T {
|
|||
}
|
||||
}
|
||||
|
||||
pub trait ReadFixedLengthByteArray {
|
||||
fn read_bytes<const N: usize>(&mut self) -> Result<[u8; N], std::io::Error>;
|
||||
}
|
||||
|
||||
impl<T: ReadBytesExt> ReadFixedLengthByteArray for T {
|
||||
fn read_bytes<const N: usize>(&mut self) -> Result<[u8; N], Error> {
|
||||
assert_ne!(N, 0);
|
||||
let mut array = [0u8; N];
|
||||
self.read_exact(&mut array)?;
|
||||
Ok(array)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -113,8 +113,7 @@ impl QuestBin {
|
|||
number: quest_number_and_episode,
|
||||
};
|
||||
|
||||
let mut name_bytes = [0u8; QUEST_BIN_NAME_LENGTH];
|
||||
reader.read_exact(&mut name_bytes)?;
|
||||
let name_bytes: [u8; QUEST_BIN_NAME_LENGTH] = reader.read_bytes()?;
|
||||
let name = match language.decode_text(name_bytes.as_unpadded_slice()) {
|
||||
Err(e) => {
|
||||
return Err(QuestBinError::DataFormatError(format!(
|
||||
|
@ -125,8 +124,8 @@ impl QuestBin {
|
|||
Ok(value) => value,
|
||||
};
|
||||
|
||||
let mut short_description_bytes = [0u8; QUEST_BIN_SHORT_DESCRIPTION_LENGTH];
|
||||
reader.read_exact(&mut short_description_bytes)?;
|
||||
let short_description_bytes: [u8; QUEST_BIN_SHORT_DESCRIPTION_LENGTH] =
|
||||
reader.read_bytes()?;
|
||||
let short_description =
|
||||
match language.decode_text(short_description_bytes.as_unpadded_slice()) {
|
||||
Err(e) => {
|
||||
|
@ -138,8 +137,8 @@ impl QuestBin {
|
|||
Ok(value) => value,
|
||||
};
|
||||
|
||||
let mut long_description_bytes = [0u8; QUEST_BIN_LONG_DESCRIPTION_LENGTH];
|
||||
reader.read_exact(&mut long_description_bytes)?;
|
||||
let long_description_bytes: [u8; QUEST_BIN_LONG_DESCRIPTION_LENGTH] =
|
||||
reader.read_bytes()?;
|
||||
let long_description =
|
||||
match language.decode_text(long_description_bytes.as_unpadded_slice()) {
|
||||
Err(e) => {
|
||||
|
|
Loading…
Reference in a new issue