1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use napi_derive::napi;
use napi::Result;
use crate::binary::{ BinaryStream, Endianness };

#[napi]
/**
 * **Int24**
 * 
 * Represents a signed 24-bit ( 3 bytes ) integer. ( -8388608 to 8388607 )
*/
pub struct Int24 {}

#[napi]
impl Int24 {
  #[napi]
  /**
   * **read**
   * 
   * Reads a signed 24-bit ( 3 bytes ) integer from the stream. ( -8388608 to 8388607 )
  */
  pub fn read(stream: &mut BinaryStream, endian: Option<Endianness>) -> Result<i32> {
    let endian = match endian {
      Some(endian) => endian,
      None => Endianness::Big,
    };

    let bytes = match stream.read(3) {
      Ok(bytes) => bytes,
      Err(err) => return Err(err)
    };

    match endian {
      Endianness::Big => Ok(i32::from_be_bytes([0, bytes[0], bytes[1], bytes[2]])),
      Endianness::Little => Ok(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0])),
    }
  }

  #[napi]
  /**
   * **write**
   * 
   * Writes a signed 24-bit ( 3 bytes ) integer to the stream. ( -8388608 to 8388607 )
  */
  pub fn write(stream: &mut BinaryStream, value: i32, endian: Option<Endianness>) {
    let endian = match endian {
      Some(endian) => endian,
      None => Endianness::Big,
    };
        
    match endian {
      Endianness::Big => stream.write(value.to_be_bytes()[1..].to_vec()),
      Endianness::Little => stream.write(value.to_le_bytes()[..3].to_vec()),
    }
  }
}