binarystream/types/floats/
float64.rs

1use napi_derive::napi;
2use napi::{bindgen_prelude::FromNapiValue, Result};
3use crate::{binary::BinaryStream, stream::Endianness};
4
5#[napi]
6#[derive(Clone)]
7/**
8 * **Float64**
9 * 
10 * Respresents a signed 64 bit ( 8 bytes ) floating point number. ( -1.7976931348623157e308 to 1.7976931348623157e308 )
11*/
12pub struct Float64 {}
13
14#[napi]
15impl Float64 {
16  #[napi]
17  /**
18   * **read**
19   * 
20   * Reads a signed 64 bit ( 8 bytes ) floating point number from the stream. ( -1.7976931348623157e308 to 1.7976931348623157e308 )
21  */
22  pub fn read(stream: &mut BinaryStream, endian: Option<Endianness>) -> Result<f64> {
23    let endian = match endian {
24      Some(endian) => endian,
25      None => Endianness::Big,
26    };
27
28    let bytes = match stream.read(8) {
29      Ok(bytes) => bytes,
30      Err(err) => return Err(err)
31    };
32
33    match endian {
34      Endianness::Big => Ok(f64::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]])),
35      Endianness::Little => Ok(f64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]])),
36    }
37  }
38
39  #[napi]
40  /**
41   * **write**
42   * 
43   * Writes a signed 64 bit ( 8 bytes ) floating point number to the stream. ( -1.7976931348623157e308 to 1.7976931348623157e308 )
44  */
45  pub fn write(stream: &mut BinaryStream, value: f64, endian: Option<Endianness>) {
46    let endian = match endian {
47      Some(endian) => endian,
48      None => Endianness::Big,
49    };
50    
51    match endian {
52      Endianness::Big => stream.write(value.to_be_bytes().to_vec()),
53      Endianness::Little => stream.write(value.to_le_bytes().to_vec()),
54    }
55  }
56}
57
58impl FromNapiValue for Float64 {
59  unsafe fn from_napi_value(_: napi::sys::napi_env, _: napi::sys::napi_value) -> Result<Self> {
60    Ok(Float64 {})
61  }
62}