1
0
Fork 0
mirror of https://codeberg.org/icewind/vbsp.git synced 2026-06-03 18:54:05 +02:00

normal generic code written by normal people

to de-deplicate some bits
This commit is contained in:
Robin Appelman 2022-12-24 00:14:54 +01:00
commit 5912584a74
2 changed files with 40 additions and 19 deletions

View file

@ -1,4 +1,5 @@
use super::vector::Vector;
use crate::data::try_read_enum;
use crate::error::InvalidNeighbourError;
use binrw::{BinRead, BinResult, ReadOptions};
use bitflags::bitflags;
@ -137,15 +138,12 @@ impl BinRead for NeighbourSpan {
options: &ReadOptions,
args: Self::Args,
) -> BinResult<Self> {
let start = reader.stream_position().unwrap();
let raw = u8::read_options(reader, options, args)?;
NeighbourSpan::try_from(raw)
.map_err(|_| InvalidNeighbourError::InvalidNeighbourSpan(raw))
.map_err(|e| binrw::Error::Custom {
pos: start,
err: Box::new(e),
})
try_read_enum(
reader,
options,
args,
InvalidNeighbourError::InvalidNeighbourSpan,
)
}
}
@ -166,15 +164,12 @@ impl BinRead for NeighbourOrientation {
options: &ReadOptions,
args: Self::Args,
) -> BinResult<Self> {
let start = reader.stream_position().unwrap();
let raw = u8::read_options(reader, options, args)?;
NeighbourOrientation::try_from(raw)
.map_err(|_| InvalidNeighbourError::InvalidNeighbourOrientation(raw))
.map_err(|e| binrw::Error::Custom {
pos: start,
err: Box::new(e),
})
try_read_enum(
reader,
options,
args,
InvalidNeighbourError::InvalidNeighbourOrientation,
)
}
}

View file

@ -10,14 +10,16 @@ pub use self::vector::*;
use crate::bspfile::LumpType;
use crate::{BspResult, StringError};
use arrayvec::ArrayString;
use binrw::error::CustomError;
use binrw::{BinRead, BinResult, ReadOptions};
use bitflags::bitflags;
use bv::BitVec;
use num_enum::TryFromPrimitive;
use std::borrow::Cow;
use std::cmp::min;
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::io::{Cursor, Read};
use std::io::{Cursor, Read, Seek};
use std::mem::{align_of, size_of};
use std::ops::Index;
use std::sync::Mutex;
@ -470,3 +472,27 @@ impl Packfile {
Ok(Some(buff))
}
}
fn try_read_enum<T, R, E, F>(
reader: &mut R,
options: &ReadOptions,
args: <<T as TryFromPrimitive>::Primitive as BinRead>::Args,
err_map: F,
) -> BinResult<T>
where
R: Read + Seek,
T: TryFromPrimitive,
T::Primitive: BinRead,
F: FnOnce(T::Primitive) -> E,
E: CustomError + 'static,
{
let start = reader.stream_position().unwrap();
let raw = <T::Primitive>::read_options(reader, options, args)?;
T::try_from_primitive(raw)
.map_err(|e| err_map(e.number))
.map_err(|e| binrw::Error::Custom {
pos: start,
err: Box::new(e),
})
}