Skip to content

Commit

Permalink
more type casting to allow easy i32 extraction
Browse files Browse the repository at this point in the history
  • Loading branch information
matko committed Oct 18, 2023
1 parent f807c74 commit 4d40d8a
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/structure/tfc/datatypes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,12 @@ impl TdbDataType for u32 {
}
}

impl FromLexical<u16> for u32 {
fn from_lexical<B: Buf>(b: B) -> Self {
b.reader().read_u16::<BigEndian>().unwrap() as u32
}
}

impl FromLexical<u32> for u32 {
fn from_lexical<B: Buf>(b: B) -> Self {
b.reader().read_u32::<BigEndian>().unwrap()
Expand Down Expand Up @@ -244,13 +250,49 @@ impl TdbDataType for i32 {
}
}

impl FromLexical<i16> for i32 {
fn from_lexical<B: Buf>(b: B) -> Self {
b.reader().read_i16::<BigEndian>().unwrap() as i32
}
}

impl FromLexical<u16> for i32 {
fn from_lexical<B: Buf>(b: B) -> Self {
b.reader().read_u16::<BigEndian>().unwrap() as i32
}
}

impl FromLexical<i32> for i32 {
fn from_lexical<B: Buf>(b: B) -> Self {
let i = b.reader().read_u32::<BigEndian>().unwrap();
(I32_BYTE_MASK ^ i) as i32
}
}

impl ToLexical<u8> for i32 {
fn to_lexical(&self) -> Bytes {
<i32 as ToLexical<i32>>::to_lexical(&self as &i32)
}
}

impl ToLexical<u16> for i32 {
fn to_lexical(&self) -> Bytes {
<i32 as ToLexical<i32>>::to_lexical(&self as &i32)
}
}

impl ToLexical<i8> for i32 {
fn to_lexical(&self) -> Bytes {
<i32 as ToLexical<i32>>::to_lexical(&self as &i32)
}
}

impl ToLexical<i16> for i32 {
fn to_lexical(&self) -> Bytes {
<i32 as ToLexical<i32>>::to_lexical(&self as &i32)
}
}

impl ToLexical<i32> for i32 {
fn to_lexical(&self) -> Bytes {
let sign_flip = I32_BYTE_MASK ^ (*self as u32);
Expand Down
16 changes: 16 additions & 0 deletions src/structure/tfc/typed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ impl TypedDictEntry {
T::from_lexical(self.entry.as_buf())
}

pub fn as_casted_val<T, Q: Into<T> + TdbDataType + FromLexical<Q>>(&self) -> T {
assert_eq!(Q::datatype(), self.datatype);
Q::from_lexical(self.entry.as_buf()).into()
}

pub fn as_i32(&self) -> Option<i32> {
match self.datatype {
Datatype::Int32 => Some(self.as_casted_val::<i32, i32>()),
Datatype::UInt8 => Some(self.as_casted_val::<i32, u8>()),
Datatype::Int8 => Some(self.as_casted_val::<i32, i8>()),
Datatype::UInt16 => Some(self.as_casted_val::<i32, u16>()),
Datatype::Int16 => Some(self.as_casted_val::<i32, i16>()),
_ => None,
}
}

pub fn datatype(&self) -> Datatype {
self.datatype
}
Expand Down

0 comments on commit 4d40d8a

Please sign in to comment.