armdb 0.15.1

sharded bitcask key-value storage optimized for NVMe
Documentation
use std::ptr;

use armour_core::{KeyScheme, KeyType};

/// Key metadata trait — describes key encoding for armdb collections.
///
/// Analogous to `Cid` in the armour crate, but without encode/decode methods.
/// Only carries compile-time constants for [`TreeMeta`](armour::TreeMeta) construction.
///
/// Implementations must guarantee that the type is safe to transmute to/from
/// `[u8; size_of::<Self>()]` — all bit patterns valid, no padding.
/// Use [`impl_key_zerocopy!`] for zerocopy types or [`impl_key_bytemuck!`]
/// for bytemuck types to get correct implementations.
///
/// # Example
///
/// ```ignore
/// use armdb::{Key, impl_key_zerocopy};
/// use armour_core::{KeyScheme, KeyType};
///
/// impl_key_zerocopy!(UserId, KeyScheme::Typed(&[KeyType::Fuid]));
/// ```
pub trait Key: Copy + Send + Sync {
    /// Key encoding scheme.
    const KEY_SCHEME: KeyScheme;
    /// Bits used for group_id / shard routing.
    const GROUP_BITS: u32 = 0;

    fn as_bytes(&self) -> &[u8];
    fn as_bytes_mut(&mut self) -> &mut [u8];
    /// Decode a key from exactly `size_of::<Self>()` bytes, at any alignment.
    ///
    /// # Panics
    ///
    /// Panics unless `bytes.len() == size_of::<Self>()`. Use
    /// [`Self::try_from_bytes`] for bytes that may have the wrong width.
    fn from_bytes(bytes: &[u8]) -> Self;
    fn zeroed() -> Self;

    /// `None` unless `bytes.len() == size_of::<Self>()`.
    fn try_from_bytes(bytes: &[u8]) -> Option<Self> {
        (bytes.len() == size_of::<Self>()).then(|| Self::from_bytes(bytes))
    }
}

// ── Location trait ─────────────────────────────────────────────────────────

/// Marker trait for disk location types stored in SkipList nodes.
/// DiskLoc (12 bytes) for Bitcask, u32 (4 bytes) for FixedStore slot_id.
pub trait Location: Copy + Send + Sync + 'static {
    fn zeroed() -> Self;
}

impl Location for crate::disk_loc::DiskLoc {
    fn zeroed() -> Self {
        crate::disk_loc::DiskLoc::new(0, 0, 0)
    }
}

impl Location for u32 {
    fn zeroed() -> Self {
        0
    }
}

// ── macros ──────────────────────────────────────────────────────────────────

/// Implement [`Key`] for a type that derives `zerocopy::{FromBytes, IntoBytes, Immutable}`.
#[macro_export]
macro_rules! impl_key_zerocopy {
    ($ty:ty, $scheme:expr) => {
        impl $crate::Key for $ty {
            const KEY_SCHEME: armour_core::KeyScheme = $scheme;

            #[inline(always)]
            fn as_bytes(&self) -> &[u8] {
                zerocopy::IntoBytes::as_bytes(self)
            }
            #[inline(always)]
            fn as_bytes_mut(&mut self) -> &mut [u8] {
                zerocopy::IntoBytes::as_mut_bytes(self)
            }
            #[inline(always)]
            fn from_bytes(bytes: &[u8]) -> Self {
                assert_eq!(bytes.len(), size_of::<Self>(), "key width mismatch");
                // SAFETY: the length is checked above in every build, the read is
                // unaligned, and implementors guarantee every bit pattern is valid.
                unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast()) }
            }
            #[inline(always)]
            fn zeroed() -> Self {
                zerocopy::FromZeros::new_zeroed()
            }
        }
    };
    ($ty:ty, $scheme:expr, group_bits = $gb:expr) => {
        impl $crate::Key for $ty {
            const KEY_SCHEME: armour_core::KeyScheme = $scheme;
            const GROUP_BITS: u32 = $gb;

            #[inline(always)]
            fn as_bytes(&self) -> &[u8] {
                zerocopy::IntoBytes::as_bytes(self)
            }
            #[inline(always)]
            fn as_bytes_mut(&mut self) -> &mut [u8] {
                zerocopy::IntoBytes::as_mut_bytes(self)
            }
            #[inline(always)]
            fn from_bytes(bytes: &[u8]) -> Self {
                assert_eq!(bytes.len(), size_of::<Self>(), "key width mismatch");
                // SAFETY: the length is checked above in every build, the read is
                // unaligned, and implementors guarantee every bit pattern is valid.
                unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast()) }
            }
            #[inline(always)]
            fn zeroed() -> Self {
                zerocopy::FromZeros::new_zeroed()
            }
        }
    };
}

/// Implement [`Key`] for a type that derives `bytemuck::{Pod, Zeroable}`.
#[macro_export]
macro_rules! impl_key_bytemuck {
    ($ty:ty, $scheme:expr) => {
        impl $crate::Key for $ty {
            const KEY_SCHEME: armour_core::KeyScheme = $scheme;

            #[inline(always)]
            fn as_bytes(&self) -> &[u8] {
                bytemuck::bytes_of(self)
            }
            #[inline(always)]
            fn as_bytes_mut(&mut self) -> &mut [u8] {
                bytemuck::bytes_of_mut(self)
            }
            #[inline(always)]
            fn from_bytes(bytes: &[u8]) -> Self {
                assert_eq!(bytes.len(), size_of::<Self>(), "key width mismatch");
                // SAFETY: the length is checked above in every build, the read is
                // unaligned, and implementors guarantee every bit pattern is valid.
                unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast()) }
            }
            #[inline(always)]
            fn zeroed() -> Self {
                bytemuck::Zeroable::zeroed()
            }
        }
    };
    ($ty:ty, $scheme:expr, group_bits = $gb:expr) => {
        impl $crate::Key for $ty {
            const KEY_SCHEME: armour_core::KeyScheme = $scheme;
            const GROUP_BITS: u32 = $gb;

            #[inline(always)]
            fn as_bytes(&self) -> &[u8] {
                bytemuck::bytes_of(self)
            }
            #[inline(always)]
            fn as_bytes_mut(&mut self) -> &mut [u8] {
                bytemuck::bytes_of_mut(self)
            }
            #[inline(always)]
            fn from_bytes(bytes: &[u8]) -> Self {
                assert_eq!(bytes.len(), size_of::<Self>(), "key width mismatch");
                // SAFETY: the length is checked above in every build, the read is
                // unaligned, and implementors guarantee every bit pattern is valid.
                unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast()) }
            }
            #[inline(always)]
            fn zeroed() -> Self {
                bytemuck::Zeroable::zeroed()
            }
        }
    };
}

// ── byte arrays ─────────────────────────────────────────────────────────────

impl<const N: usize> Key for [u8; N] {
    const KEY_SCHEME: KeyScheme = KeyScheme::Typed(&[KeyType::Array(N)]);

    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        self
    }
    #[inline(always)]
    fn as_bytes_mut(&mut self) -> &mut [u8] {
        self
    }
    #[inline(always)]
    fn from_bytes(bytes: &[u8]) -> Self {
        assert_eq!(bytes.len(), N, "key width mismatch");
        // SAFETY: the length is checked above and `[u8; N]` has alignment 1.
        unsafe { ptr::read_unaligned(bytes.as_ptr().cast()) }
    }
    #[inline(always)]
    fn zeroed() -> Self {
        [0u8; N]
    }
}

// ── rend (feature "armour") ─────────────────────────────────────────────────

#[cfg(feature = "armour")]
impl_key_zerocopy!(rend::u64_be, KeyScheme::Typed(&[KeyType::U64]));

// ── armour-core ID types ─────────────────────────────────────────────────────

impl<H: Send + Sync> Key for armour_core::fuid::Fuid<H> {
    const KEY_SCHEME: KeyScheme = KeyScheme::Typed(&[KeyType::Fuid]);

    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        zerocopy::IntoBytes::as_bytes(self)
    }
    #[inline(always)]
    fn as_bytes_mut(&mut self) -> &mut [u8] {
        zerocopy::IntoBytes::as_mut_bytes(self)
    }
    #[inline(always)]
    fn from_bytes(bytes: &[u8]) -> Self {
        assert_eq!(bytes.len(), size_of::<Self>(), "key width mismatch");
        // SAFETY: the length is checked above, the read is unaligned, and the
        // ID types are plain `u64_be` wrappers valid for every bit pattern.
        unsafe { ptr::read_unaligned(bytes.as_ptr().cast()) }
    }
    #[inline(always)]
    fn zeroed() -> Self {
        zerocopy::FromZeros::new_zeroed()
    }
}

impl<T: Send + Sync> Key for armour_core::id64::Id64<T> {
    const KEY_SCHEME: KeyScheme = KeyScheme::Typed(&[KeyType::U64]);

    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        zerocopy::IntoBytes::as_bytes(self)
    }
    #[inline(always)]
    fn as_bytes_mut(&mut self) -> &mut [u8] {
        zerocopy::IntoBytes::as_mut_bytes(self)
    }
    #[inline(always)]
    fn from_bytes(bytes: &[u8]) -> Self {
        assert_eq!(bytes.len(), size_of::<Self>(), "key width mismatch");
        // SAFETY: the length is checked above, the read is unaligned, and the
        // ID types are plain `u64_be` wrappers valid for every bit pattern.
        unsafe { ptr::read_unaligned(bytes.as_ptr().cast()) }
    }
    #[inline(always)]
    fn zeroed() -> Self {
        zerocopy::FromZeros::new_zeroed()
    }
}

// ── uuid ────────────────────────────────────────────────────────────────────

#[cfg(feature = "uuid")]
impl_key_bytemuck!(uuid::Uuid, KeyScheme::Typed(&[KeyType::Array(16)]));

// ── solana (feature "solana") ────────────────────────────────────────────────

#[cfg(feature = "solana")]
impl_key_bytemuck!(
    solana_pubkey::Pubkey,
    KeyScheme::Typed(&[KeyType::Array(32)])
);

#[cfg(feature = "solana")]
impl_key_bytemuck!(
    solana_signature::Signature,
    KeyScheme::Typed(&[KeyType::Array(64)])
);

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(
        Clone,
        Copy,
        Debug,
        PartialEq,
        zerocopy::FromBytes,
        zerocopy::IntoBytes,
        zerocopy::Immutable,
        zerocopy::KnownLayout,
    )]
    #[repr(C)]
    struct WideKey(u64);
    crate::impl_key_zerocopy!(WideKey, KeyScheme::Typed(&[KeyType::U64]));

    #[repr(C, align(8))]
    struct Aligned([u8; 16]);

    /// Bytes 1..9 of an 8-aligned buffer: never 8-aligned.
    fn misaligned(value: [u8; 8]) -> Aligned {
        let mut buf = Aligned([0; 16]);
        buf.0[1..9].copy_from_slice(&value);
        buf
    }

    #[test]
    fn key_from_bytes_reads_a_misaligned_slice() {
        let buf = misaligned(7u64.to_ne_bytes());
        assert_eq!(WideKey::from_bytes(&buf.0[1..9]), WideKey(7));
        assert_eq!(<[u8; 8]>::from_bytes(&buf.0[1..9]), 7u64.to_ne_bytes());
        let fuid = <armour_core::fuid::Fuid<()> as Key>::from_bytes(&buf.0[1..9]);
        assert_eq!(Key::as_bytes(&fuid), &buf.0[1..9]);
        let id = <armour_core::id64::Id64<()> as Key>::from_bytes(&buf.0[1..9]);
        assert_eq!(Key::as_bytes(&id), &buf.0[1..9]);
    }

    #[test]
    #[should_panic(expected = "key width mismatch")]
    fn key_from_bytes_panics_on_a_short_slice() {
        let _ = WideKey::from_bytes(&[0u8; 4]);
    }

    #[test]
    #[should_panic(expected = "key width mismatch")]
    fn key_from_bytes_panics_on_a_long_slice() {
        let _ = <[u8; 8]>::from_bytes(&[0u8; 9]);
    }

    #[test]
    fn key_try_from_bytes_checks_width() {
        let buf = misaligned(9u64.to_ne_bytes());
        assert_eq!(WideKey::try_from_bytes(&buf.0[1..9]), Some(WideKey(9)));
        assert_eq!(WideKey::try_from_bytes(&buf.0[1..5]), None);
        assert_eq!(WideKey::try_from_bytes(&buf.0[1..10]), None);
    }

    #[cfg(feature = "bytemuck-codec")]
    #[test]
    fn key_from_bytes_bytemuck_macro_reads_a_misaligned_slice() {
        #[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
        #[repr(C)]
        struct PodKey(u64);
        crate::impl_key_bytemuck!(PodKey, KeyScheme::Typed(&[KeyType::U64]));
        let buf = misaligned(5u64.to_ne_bytes());
        assert_eq!(PodKey::from_bytes(&buf.0[1..9]), PodKey(5));
    }
}