#[cfg(all(feature = "fs", unix))]
pub mod fs;
pub mod nor;
use alloc::string::String;
use alloc::vec::Vec;
use crc::{CRC_32_ISO_HDLC, Crc};
use serde::{Serialize, de::DeserializeOwned};
use crate::ObjectId;
pub trait Backend: Sized + 'static {
type Error;
type Config;
fn mount(config: Self::Config) -> Result<Self, Self::Error>;
fn write<T: Serialize>(
&mut self,
id: ObjectId,
name: &str,
value: &T,
) -> Result<(), Self::Error>;
fn read<T: DeserializeOwned>(&mut self, id: ObjectId) -> Result<Option<T>, Self::Error>;
fn name(&mut self, id: ObjectId) -> Result<String, Self::Error>;
fn remove(&mut self, id: ObjectId) -> Result<(), Self::Error>;
fn usage(&self) -> Usage;
fn wear(&self) -> Option<Wear> {
None
}
fn ids(&self) -> Vec<ObjectId>;
fn unmount(self) -> Result<(), Self::Error> {
Ok(())
}
}
pub fn type_tag<T: ?Sized>() -> u32 {
let name = core::any::type_name::<T>();
name.bytes().fold(0x811c_9dc5, |hash, byte| {
(hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
})
}
fn decode<T: DeserializeOwned>(data: &[u8]) -> postcard::Result<Option<T>> {
let ((_name, tag), value): ((&str, [u8; 4]), _) = postcard::take_from_bytes(data)?;
if u32::from_le_bytes(tag) != type_tag::<T>() {
return Ok(None);
}
postcard::from_bytes(value).map(Some)
}
static CRC32: Crc<u32> = Crc::<u32>::new(&CRC_32_ISO_HDLC);
fn crc32(parts: &[&[u8]]) -> u32 {
let mut digest = CRC32.digest();
for part in parts {
digest.update(part);
}
digest.finalize()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Usage {
pub capacity: usize,
pub used: usize,
pub free: usize,
pub reclaimable: usize,
pub objects: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Wear {
pub sectors: u32,
pub most_worn: u32,
pub total_erases: u64,
}
impl Wear {
pub fn remaining_erases(&self, endurance: u32) -> u64 {
(u64::from(self.sectors) * u64::from(endurance)).saturating_sub(self.total_erases)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crc32_check_value() {
assert_eq!(crc32(&[b"1234", b"56789"]), 0xCBF4_3926);
}
}