ove/
nvs.rs

1// Copyright (C) 2026 Kamil Lulko <kamil.lulko@gmail.com>
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4//
5// This file is part of oveRTOS.
6
7//! Non-Volatile Storage (NVS) subsystem for oveRTOS.
8//!
9//! Provides key-value persistence backed by flash or EEPROM. All keys must be
10//! null-terminated byte slices (e.g. `b"my_key\0"`).
11
12use crate::bindings;
13use crate::error::{Error, Result};
14
15/// Initialize the NVS subsystem.
16///
17/// Must be called once before any `read`, `write`, or `erase` operations.
18///
19/// # Errors
20/// Returns an error if the underlying storage backend fails to initialize.
21pub fn init() -> Result<()> {
22    let rc = unsafe { bindings::ove_nvs_init() };
23    Error::from_code(rc)
24}
25
26/// Read a value from NVS into `buf`. `key` must be `\0`-terminated.
27///
28/// Returns the number of bytes actually read, which may be less than `buf.len()`
29/// if the stored value is shorter.
30///
31/// # Errors
32/// Returns [`Error::NotRegistered`] if the key does not exist, or another error
33/// if the read fails.
34pub fn read(key: &[u8], buf: &mut [u8]) -> Result<usize> {
35    let mut out_len: usize = 0;
36    let rc = unsafe {
37        bindings::ove_nvs_read(
38            key.as_ptr() as *const _,
39            buf.as_mut_ptr() as *mut _,
40            buf.len(),
41            &mut out_len,
42        )
43    };
44    Error::from_code(rc)?;
45    Ok(out_len)
46}
47
48/// Write `data` under `key` in NVS. `key` must be `\0`-terminated.
49///
50/// If the key already exists its value is replaced.
51///
52/// # Errors
53/// Returns [`Error::NoMemory`] if storage is full, or another error on failure.
54pub fn write(key: &[u8], data: &[u8]) -> Result<()> {
55    let rc = unsafe {
56        bindings::ove_nvs_write(
57            key.as_ptr() as *const _,
58            data.as_ptr() as *const _,
59            data.len(),
60        )
61    };
62    Error::from_code(rc)
63}
64
65/// Erase the entry for `key` from NVS. `key` must be `\0`-terminated.
66///
67/// # Errors
68/// Returns [`Error::NotRegistered`] if the key does not exist.
69pub fn erase(key: &[u8]) -> Result<()> {
70    let rc = unsafe { bindings::ove_nvs_erase(key.as_ptr() as *const _) };
71    Error::from_code(rc)
72}