Skip to main content

flow_fcs/
byteorder.rs

1use anyhow::{Result, anyhow};
2use byteorder::{BigEndian as BE, ByteOrder as BO, LittleEndian as LE};
3use serde::{Deserialize, Serialize};
4use strum_macros::Display;
5
6/// Byte order (endianness) for reading numeric data from FCS files
7///
8/// FCS files can be written on either little-endian or big-endian systems.
9/// The `$BYTEORD` keyword specifies which format is used.
10#[derive(Display, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
11pub enum ByteOrder {
12    LittleEndian,
13    BigEndian,
14}
15impl ByteOrder {
16    /// Matches the string pattern and returns the corresponding byte order
17    /// # Errors
18    /// Will return `Err` if `byte_order` is not a valid byte order
19    pub fn from_keyword_str(byte_order: &str) -> Result<Self> {
20        match byte_order {
21            "1,2,3,4" => Ok(Self::LittleEndian),
22            "4,3,2,1" => Ok(Self::BigEndian),
23            _ => Err(anyhow!("Invalid byte order")),
24        }
25    }
26
27    /// Returns the byte order as a string
28    pub const fn to_keyword_str(&self) -> &str {
29        match self {
30            Self::LittleEndian => "1,2,3,4",
31            Self::BigEndian => "4,3,2,1",
32        }
33    }
34
35    /// Reads a single 32-bit floating point number from a byte slice
36    pub fn read_f32(&self, bytes: &[u8]) -> f32 {
37        match self {
38            Self::LittleEndian => LE::read_f32(bytes),
39            Self::BigEndian => BE::read_f32(bytes),
40        }
41    }
42}