binex/
utils.rs

1use crate::Error;
2
3pub struct Utils;
4
5impl Utils {
6    /// u16 decoding attempt, as specified by
7    /// [https://www.unavco.org/data/gps-gnss/data-formats/binex/conventions.html#uint2]
8    pub fn decode_u16(big_endian: bool, buf: &[u8]) -> Result<u16, Error> {
9        if buf.len() < 2 {
10            Err(Error::NotEnoughBytes)
11        } else if big_endian {
12            Ok(u16::from_be_bytes([buf[0], buf[1]]))
13        } else {
14            Ok(u16::from_le_bytes([buf[0], buf[1]]))
15        }
16    }
17    /// u32 decoding attempt, as specified by
18    /// [https://www.unavco.org/data/gps-gnss/data-formats/binex/conventions.html#uint4]
19    pub fn decode_u32(big_endian: bool, buf: &[u8]) -> Result<u32, Error> {
20        if buf.len() < 4 {
21            Err(Error::NotEnoughBytes)
22        } else if big_endian {
23            Ok(u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]))
24        } else {
25            Ok(u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]))
26        }
27    }
28    /// i32 decoding attempt, as specified by
29    /// [https://www.unavco.org/data/gps-gnss/data-formats/binex/conventions.html#sint4]
30    pub fn decode_i32(big_endian: bool, buf: &[u8]) -> Result<i32, Error> {
31        if buf.len() < 4 {
32            Err(Error::NotEnoughBytes)
33        } else if big_endian {
34            Ok(i32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]))
35        } else {
36            Ok(i32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]))
37        }
38    }
39    /// f32 decoding attempt, as specified by
40    /// [https://www.unavco.org/data/gps-gnss/data-formats/binex/conventions.html#real4]
41    pub fn decode_f32(big_endian: bool, buf: &[u8]) -> Result<f32, Error> {
42        if buf.len() < 4 {
43            Err(Error::NotEnoughBytes)
44        } else if big_endian {
45            Ok(f32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]))
46        } else {
47            Ok(f32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]))
48        }
49    }
50    /// f64 decoding attempt, as specified by
51    /// [https://www.unavco.org/data/gps-gnss/data-formats/binex/conventions.html#real8]
52    pub fn decode_f64(big_endian: bool, buf: &[u8]) -> Result<f64, Error> {
53        if buf.len() < 8 {
54            Err(Error::NotEnoughBytes)
55        } else if big_endian {
56            Ok(f64::from_be_bytes([
57                buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
58            ]))
59        } else {
60            Ok(f64::from_le_bytes([
61                buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
62            ]))
63        }
64    }
65}