use esp_idf_svc::nvs::{
EspCustomNvsPartition, EspDefaultNvsPartition, EspNvs, EspNvsPartition, NvsCustom, NvsDefault,
NvsPartitionId,
};
use esp_idf_svc::sys::EspError;
use rusty_esp_mid_core::esp_core::error::{Error, Result};
use rusty_esp_mid_core::esp_core::hal::{Kv, check_key};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protection {
Encrypted,
Plaintext,
}
pub const NVS_ENCRYPTION: bool = cfg!(esp_idf_nvs_encryption);
pub const FLASH_ENCRYPTION: bool = cfg!(esp_idf_secure_flash_enc_enabled);
#[must_use]
pub const fn protection() -> Protection {
if NVS_ENCRYPTION && FLASH_ENCRYPTION {
Protection::Encrypted
} else {
Protection::Plaintext
}
}
pub const IDENTITY_PARTITION: &str = "identity";
pub struct EspNvsKv<T: NvsPartitionId = NvsDefault> {
nvs: EspNvs<T>,
protection: Protection,
}
impl<T: NvsPartitionId> core::fmt::Debug for EspNvsKv<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("EspNvsKv")
.field("protection", &self.protection)
.finish_non_exhaustive()
}
}
fn map(e: EspError) -> Error {
match e.code() {
esp_idf_svc::sys::ESP_ERR_NVS_NOT_FOUND => Error::Corrupt,
esp_idf_svc::sys::ESP_ERR_NVS_INVALID_LENGTH
| esp_idf_svc::sys::ESP_ERR_NVS_INVALID_NAME => Error::InvalidFormat,
esp_idf_svc::sys::ESP_ERR_NVS_NOT_ENOUGH_SPACE => Error::BufferTooSmall { needed: 0 },
_ => Error::Hardware,
}
}
fn refuse_plaintext() -> Result<()> {
if protection() == Protection::Plaintext && !cfg!(feature = "allow-insecure-dev") {
return Err(Error::Denied);
}
Ok(())
}
impl<T: NvsPartitionId> EspNvsKv<T> {
pub fn open_in(partition: EspNvsPartition<T>, namespace: &str) -> Result<Self> {
refuse_plaintext()?;
Self::open_unchecked_in(partition, namespace)
}
pub fn open_unchecked_in(partition: EspNvsPartition<T>, namespace: &str) -> Result<Self> {
let nvs = EspNvs::new(partition, namespace, true).map_err(map)?;
Ok(EspNvsKv {
nvs,
protection: protection(),
})
}
#[must_use]
pub fn protection(&self) -> Protection {
self.protection
}
}
impl EspNvsKv<NvsDefault> {
pub fn open(partition: EspDefaultNvsPartition, namespace: &str) -> Result<Self> {
Self::open_in(partition, namespace)
}
pub fn open_unchecked(partition: EspDefaultNvsPartition, namespace: &str) -> Result<Self> {
Self::open_unchecked_in(partition, namespace)
}
}
impl EspNvsKv<NvsCustom> {
pub fn open_custom(label: &str, namespace: &str) -> Result<Self> {
refuse_plaintext()?;
Self::open_custom_unchecked(label, namespace)
}
pub fn open_custom_unchecked(label: &str, namespace: &str) -> Result<Self> {
let partition = EspCustomNvsPartition::take(label).map_err(map)?;
Self::open_unchecked_in(partition, namespace)
}
}
fn get_str_value<T: NvsPartitionId>(nvs: &EspNvs<T>, key: &str, out: &mut [u8]) -> Result<Option<usize>> {
let Some(with_nul) = nvs.str_len(key).map_err(map)? else {
return Ok(None);
};
let len = with_nul.saturating_sub(1);
if out.len() < len {
return Err(Error::BufferTooSmall { needed: len });
}
let mut buf = vec![0u8; with_nul.max(1)];
let read = nvs.get_str(key, &mut buf).map_err(map).map(|s| {
s.map(|s| {
out[..s.len()].copy_from_slice(s.as_bytes());
s.len()
})
});
buf.fill(0);
core::hint::black_box(&buf);
read
}
impl<T: NvsPartitionId> Kv for EspNvsKv<T> {
fn get(&self, key: &str, out: &mut [u8]) -> Result<Option<usize>> {
check_key(key)?;
let Some(len) = self.nvs.blob_len(key).map_err(map)? else {
return get_str_value(&self.nvs, key, out);
};
if out.len() < len {
return Err(Error::BufferTooSmall { needed: len });
}
match self.nvs.get_blob(key, out).map_err(map)? {
Some(v) => Ok(Some(v.len())),
None => Ok(None),
}
}
fn put(&mut self, key: &str, value: &[u8]) -> Result<()> {
check_key(key)?;
if self.nvs.str_len(key).map_err(map)?.is_some() {
self.nvs.remove(key).map_err(map)?;
}
self.nvs.set_blob(key, value).map_err(map)
}
fn remove(&mut self, key: &str) -> Result<bool> {
check_key(key)?;
self.nvs.remove(key).map_err(map)
}
}