sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
//! Binding a Rust type to a sensor ID: the [`SensorData`] trait.
//!
//! Implementing it is what makes a type storable — the sensor ID and the schema
//! version stop being arguments a caller has to remember and become properties
//! of the type. Everything you then *do* with such a type lives on the logs and
//! on the capability ports, not here:
//!
//! ```ignore
//! // On a concrete log — no trait import needed:
//! db.append_sensor(timestamp, &Temperature { celsius: 25.5 })?;
//! let latest = db.latest_sensor::<Temperature>()?;
//!
//! // Over any log, in generic code:
//! use sensor_db::{LogSinkExt, LogSourceExt};
//!
//! fn record<L: LogSinkExt>(log: &mut L, t: u64) -> Result<(), Error> {
//!     log.append_sensor(t, &Temperature { celsius: 25.5 })
//! }
//! ```
//!
//! # Example
//!
//! ```ignore
//! use zerocopy::{FromBytes, IntoBytes, KnownLayout, Immutable};
//! use sensor_db::SensorData;
//!
//! #[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
//! #[repr(C)]
//! struct Temperature {
//!     celsius: f32,
//! }
//!
//! impl SensorData for Temperature {
//!     const SENSOR_ID: u16 = 0x01;
//! }
//! ```

use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

// ---------------------------------------------------------------------------
// SensorData trait (base — users implement this)
// ---------------------------------------------------------------------------

/// Base trait for sensor data types that can be stored and retrieved with type safety.
///
/// Implementors bind a zerocopy-compatible type to a specific sensor ID. Only
/// [`SENSOR_ID`](Self::SENSOR_ID) needs to be defined;
/// [`SCHEMA_VERSION`](Self::SCHEMA_VERSION) defaults to 0.
///
/// The methods that use it live on the logs and on the capability ports:
///
/// ```ignore
/// db.append_sensor(timestamp, &Temperature { celsius: 25.5 })?;
/// if let Some((_, t)) = db.latest_sensor::<Temperature>()? { ... }
/// ```
///
/// # Requirements
///
/// The implementing type must derive the following zerocopy traits:
/// - [`FromBytes`]: Allows reading from raw bytes
/// - [`IntoBytes`]: Allows writing to raw bytes
/// - [`KnownLayout`]: Provides compile-time layout information
/// - [`Immutable`]: Ensures the type has no interior mutability
///
/// Additionally, the type should use `#[repr(C)]` to ensure a stable layout.
///
/// # Endianness
///
/// The entry header uses little-endian wire format, but payload bytes are
/// stored as-is from the `#[repr(C)]` struct's in-memory representation
/// (native endianness). If your data will be read on a different architecture,
/// use `zerocopy::little_endian::*` wrapper types (e.g., `U32`, `I16`) in
/// your struct fields to ensure portable byte order.
///
/// # Struct Padding
///
/// `#[repr(C)]` structs may contain padding bytes between fields, which would
/// waste flash space — but this is not a footgun you have to watch for, because
/// `IntoBytes` refuses to derive for a type with padding and reports the exact
/// number of wasted bytes. When it does, either:
/// - Use `#[repr(C, packed)]` (may cause unaligned access on some platforms)
/// - Order fields from largest to smallest alignment
/// - Use only types with alignment ≤ 1 (e.g., `u8`, `zerocopy::little_endian::*`)
///
/// # Example
///
/// With the `derive` feature, the ID and version are named at the type:
///
/// ```ignore
/// use sensor_db::SensorData;
/// use sensor_db::zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
///
/// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, SensorData)]
/// #[sensor(id = 0x02, version = 1)]
/// #[repr(C)]
/// struct Accelerometer {
///     x: i16,
///     y: i16,
///     z: i16,
/// }
/// ```
///
/// Written out, which is all the derive expands to:
///
/// ```ignore
/// use sensor_db::SensorData;
/// use sensor_db::zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
///
/// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
/// #[repr(C)]
/// struct Accelerometer {
///     x: i16,
///     y: i16,
///     z: i16,
/// }
///
/// impl SensorData for Accelerometer {
///     const SENSOR_ID: u16 = 0x02;
///     const SCHEMA_VERSION: u8 = 1;
/// }
/// ```
///
/// The zerocopy derives are written out in both, because a derive macro cannot
/// add attributes to the item it is applied to, and because zerocopy's derives
/// expand to absolute `::zerocopy::` paths — so `zerocopy` must be a direct
/// dependency of your crate regardless. Import its traits through
/// [`sensor_db::zerocopy`](crate::zerocopy) to keep the version in step with
/// the one this crate's bounds name.
pub trait SensorData: FromBytes + IntoBytes + KnownLayout + Immutable + Sized {
    /// The unique sensor ID associated with this data type.
    ///
    /// This ID is used when storing and querying entries in the database.
    const SENSOR_ID: u16;

    /// The version of this struct's layout and meaning.
    ///
    /// Stored as a one-byte tag in front of the payload, so an entry written by
    /// an older firmware is never silently reinterpreted by a newer one. **Bump
    /// it on any change to the struct** — a field added or removed, reordered,
    /// retyped, rescaled, or simply given a new meaning. The last of those is
    /// the case nothing else catches: `celsius` becoming `fahrenheit` keeps the
    /// size, so without a version the old readings come back as plausible
    /// nonsense.
    ///
    /// # Reading both eras
    ///
    /// Keep the old struct and give the new one the next version. Both name the
    /// same sensor ID, so the log needs no migration pass:
    ///
    /// ```ignore
    /// impl SensorData for TemperatureV0 {
    ///     const SENSOR_ID: u16 = 0x01;
    ///     const SCHEMA_VERSION: u8 = 0;   // the default; older firmware wrote this
    /// }
    ///
    /// impl SensorData for Temperature {
    ///     const SENSOR_ID: u16 = 0x01;
    ///     const SCHEMA_VERSION: u8 = 1;
    /// }
    /// ```
    ///
    /// `query_sensor` skips entries of another version, so each type reads its
    /// own era. `latest_sensor` and `oldest_sensor` instead return
    /// [`Error::SchemaMismatch`](crate::Error::SchemaMismatch), naming the
    /// version they found.
    ///
    /// # Cost
    ///
    /// One byte per typed entry. The raw API (`append` / `append_value` /
    /// `query_range`) is untagged and unaffected — and does not interoperate
    /// with the typed API, precisely because it carries no version.
    const SCHEMA_VERSION: u8 = 0;
}