lilliput_core/encoder/
float.rs

1use crate::{
2    error::Result, header::FloatHeader, io::Write, num::WithValidatedPackedBeBytes as _,
3    value::FloatValue,
4};
5
6use super::Encoder;
7
8impl<W> Encoder<W>
9where
10    W: Write,
11{
12    // MARK: - Value
13
14    /// Encodes a 32-bit floating-point value.
15    pub fn encode_f32(&mut self, value: f32) -> Result<()> {
16        let validator = self.config.floats.validation.f32.clone();
17
18        value.with_validated_packed_be_bytes(self.config.floats.packing, &validator, |bytes| {
19            self.encode_float_header(&FloatHeader::new(bytes.len() as u8))?;
20
21            // Push the value itself:
22            self.push_bytes(bytes)
23        })
24    }
25
26    /// Encodes a 64-bit floating-point value.
27    pub fn encode_f64(&mut self, value: f64) -> Result<()> {
28        let validator = self.config.floats.validation.f64.clone();
29
30        value.with_validated_packed_be_bytes(self.config.floats.packing, &validator, |bytes| {
31            self.encode_float_header(&FloatHeader::new(bytes.len() as u8))?;
32
33            // Push the value itself:
34            self.push_bytes(bytes)
35        })
36    }
37
38    /// Encodes a floating-point value, from a `FloatValue`.
39    pub fn encode_float_value(&mut self, value: &FloatValue) -> Result<()> {
40        match value {
41            FloatValue::F32(value) => self.encode_f32(*value),
42            FloatValue::F64(value) => self.encode_f64(*value),
43        }
44    }
45
46    // MARK: - Header
47
48    /// Encodes a floating-point value's header.
49    pub fn encode_float_header(&mut self, header: &FloatHeader) -> Result<()> {
50        let width = header.width();
51
52        let mut byte = FloatHeader::TYPE_BITS;
53
54        byte |= (width - 1) & FloatHeader::VALUE_WIDTH_BITS;
55
56        #[cfg(feature = "tracing")]
57        tracing::debug!(byte = crate::binary::fmt_byte(byte), width = width);
58
59        // Push the value's header:
60        self.push_byte(byte)
61    }
62}