pub struct Quantizer { /* private fields */ }Expand description
Packs a batch of f32 readings into a compact byte form for a metered link.
A quantizer rounds each reading to a fixed precision - set by the scale, where
100.0 keeps two decimal places - turns it into an integer, and delta-encodes the
batch with encode_deltas. This is lossy by exactly the rounding step, which is
the right trade for a cheap sensor on an expensive link: a temperature to the
nearest hundredth of a degree costs a byte or two per sample instead of four.
The same scale must be used to encode and decode, and nothing in the bytes
records it.
A reading that is not a number, or is infinite, is refused rather than packed:
the format has no way to say “no reading”, and a dead sensor’s NaN sent as a
real value would be worse than an error.
§Examples
use pamoja_codec::Quantizer;
// Quantize to 0.1 precision and pack a slowly-rising series.
let quantizer = Quantizer::new(10.0);
let readings = [20.0, 20.1, 20.2, 20.3];
let packed = quantizer.encode(&readings).unwrap();
assert!(packed.len() < readings.len() * 4); // smaller than four bytes per reading
let restored = quantizer.decode(&packed).unwrap();
assert!((restored[2] - 20.2).abs() < 0.05);Implementations§
Source§impl Quantizer
impl Quantizer
Sourcepub fn encode(&self, readings: &[f32]) -> Result<Vec<u8>>
pub fn encode(&self, readings: &[f32]) -> Result<Vec<u8>>
Quantizes and delta-encodes a batch of readings.
§Arguments
readings- the readings to pack, in order.
§Returns
The compact encoding of the batch.
§Errors
Returns Error::Codec if the scale is not a
positive, finite number, if a reading is not a number or is infinite, or if a
reading at this scale is past what the batch can carry, about 9.2e18.
Sourcepub fn decode(&self, bytes: &[u8]) -> Result<Vec<f32>>
pub fn decode(&self, bytes: &[u8]) -> Result<Vec<f32>>
Decodes a batch back into readings, to within the quantizer’s precision.
§Arguments
bytes- the encoding produced byencodewith the same scale.
§Returns
The decoded readings, in order.
§Errors
Returns Error::Codec if the scale is not a
positive, finite number, or bytes is malformed.