physis/havok/
slice_ext.rs

1// SPDX-FileCopyrightText: 2020 Inseok Lee
2// SPDX-License-Identifier: MIT
3
4#![allow(dead_code)]
5
6use core::convert::TryInto;
7
8pub trait SliceByteOrderExt {
9    fn to_int_be<T>(&self) -> T
10    where
11        T: Integer;
12
13    fn to_int_le<T>(&self) -> T
14    where
15        T: Integer;
16
17    fn to_float_be<T>(&self) -> T
18    where
19        T: Float;
20}
21
22impl SliceByteOrderExt for &[u8] {
23    fn to_int_be<T>(&self) -> T
24    where
25        T: Integer,
26    {
27        let sliced = &self[..core::mem::size_of::<T>()];
28
29        T::from_be_bytes(sliced)
30    }
31
32    fn to_int_le<T>(&self) -> T
33    where
34        T: Integer,
35    {
36        let sliced = &self[..core::mem::size_of::<T>()];
37
38        T::from_le_bytes(sliced)
39    }
40
41    fn to_float_be<T>(&self) -> T
42    where
43        T: Float,
44    {
45        let sliced = &self[..core::mem::size_of::<T>()];
46
47        T::from_be_bytes(sliced)
48    }
49}
50
51pub trait Integer {
52    fn from_be_bytes(bytes: &[u8]) -> Self;
53    fn from_le_bytes(bytes: &[u8]) -> Self;
54}
55
56impl Integer for u32 {
57    fn from_be_bytes(bytes: &[u8]) -> Self {
58        Self::from_be_bytes(bytes.try_into().unwrap())
59    }
60
61    fn from_le_bytes(bytes: &[u8]) -> Self {
62        Self::from_le_bytes(bytes.try_into().unwrap())
63    }
64}
65
66impl Integer for i32 {
67    fn from_be_bytes(bytes: &[u8]) -> Self {
68        Self::from_be_bytes(bytes.try_into().unwrap())
69    }
70
71    fn from_le_bytes(bytes: &[u8]) -> Self {
72        Self::from_le_bytes(bytes.try_into().unwrap())
73    }
74}
75
76impl Integer for u16 {
77    fn from_be_bytes(bytes: &[u8]) -> Self {
78        Self::from_be_bytes(bytes.try_into().unwrap())
79    }
80
81    fn from_le_bytes(bytes: &[u8]) -> Self {
82        Self::from_le_bytes(bytes.try_into().unwrap())
83    }
84}
85
86impl Integer for i16 {
87    fn from_be_bytes(bytes: &[u8]) -> Self {
88        Self::from_be_bytes(bytes.try_into().unwrap())
89    }
90
91    fn from_le_bytes(bytes: &[u8]) -> Self {
92        Self::from_le_bytes(bytes.try_into().unwrap())
93    }
94}
95
96impl Integer for u8 {
97    fn from_be_bytes(bytes: &[u8]) -> Self {
98        Self::from_be_bytes(bytes.try_into().unwrap())
99    }
100
101    fn from_le_bytes(bytes: &[u8]) -> Self {
102        Self::from_le_bytes(bytes.try_into().unwrap())
103    }
104}
105
106impl Integer for i8 {
107    fn from_be_bytes(bytes: &[u8]) -> Self {
108        Self::from_be_bytes(bytes.try_into().unwrap())
109    }
110
111    fn from_le_bytes(bytes: &[u8]) -> Self {
112        Self::from_le_bytes(bytes.try_into().unwrap())
113    }
114}
115
116pub trait Float {
117    fn from_be_bytes(bytes: &[u8]) -> Self;
118}
119
120impl Float for f32 {
121    fn from_be_bytes(bytes: &[u8]) -> Self {
122        Self::from_be_bytes(bytes.try_into().unwrap())
123    }
124}