pi_block_device 0.1.0

Asynchronous copy-on-write block storage abstractions
Documentation
//! 文件块读取缓冲及其所有权形式。

use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;

use memmap2::Mmap;

use super::RetirementNotifier;

/// 一个 ReadBuf 对单一物理路径的精确运行时 lease。
///
/// lease 不持有整个 State;最后一个强引用释放时只唤醒退休 worker,不在 Drop 中
/// 执行阻塞 unlink 或目录同步。
pub(crate) struct ReadLease {
    /// 此 lease 精确保护的普通段或独立大块路径。
    _path: PathBuf,
    /// 弱所有权语义的共享通知器;不引用 StoreInner,避免 worker/store Arc 环。
    notifier: Arc<RetirementNotifier>,
}

impl ReadLease {
    /// 创建精确路径 lease;调用方必须已在 RuntimeState 同一锁内登记其 Weak。
    pub(super) fn new(path: PathBuf, notifier: Arc<RetirementNotifier>) -> Self {
        Self {
            _path: path,
            notifier,
        }
    }
}

impl Drop for ReadLease {
    /// 仅通知退休 worker 重新检查队列;不会在调用方线程执行文件 I/O。
    fn drop(&mut self) {
        self.notifier.notify();
    }
}

/// 把精确物理路径 lease 绑定到读取结果生命周期。
pub struct FileReadGuard {
    /// 覆盖返回缓冲生命周期的精确路径 lease。
    _lease: Arc<ReadLease>,
}

impl FileReadGuard {
    /// 从已在 RuntimeState 注册的强 lease 创建读取保护对象。
    fn new(lease: Arc<ReadLease>) -> Self {
        Self { _lease: lease }
    }
}

/// 文件存储返回的稳定读取缓冲。
///
/// Active 段使用拥有的 Vec;Sealed 段和大块可持有只读内存映射。
pub enum FileReadBuf {
    /// 独立拥有字节的缓冲。
    Owned {
        /// 完整块字节;普通 Active 块长度等于其槽位大小。
        data: Vec<u8>,
        /// 精确保护来源路径的运行时 guard。
        _guard: FileReadGuard,
    },
    /// 共享只读映射中的一个有效字节范围。
    Mapped {
        /// 保持文件映射生命周期的共享句柄。
        map: Arc<Mmap>,
        /// 当前块在映射中的半开范围。
        range: Range<usize>,
        /// 精确保护来源路径的运行时 guard。
        _guard: FileReadGuard,
    },
}

impl FileReadBuf {
    /// 用独立 Vec 和精确路径 lease 构造读取缓冲,适用于仍会追加的 Active 段。
    pub(super) fn owned(data: Vec<u8>, lease: Arc<ReadLease>) -> Self {
        Self::Owned {
            data,
            _guard: FileReadGuard::new(lease),
        }
    }

    /// 用只读 Mmap、半开范围和精确路径 lease 构造稳定缓冲。
    ///
    /// # Panics
    ///
    /// 本构造器自身不索引映射;调用方必须保证
    /// range.start <= range.end <= map.len(),否则之后 AsRef 切片时会 panic。
    pub(super) fn mapped(map: Mmap, range: Range<usize>, lease: Arc<ReadLease>) -> Self {
        Self::Mapped {
            map: Arc::new(map),
            range,
            _guard: FileReadGuard::new(lease),
        }
    }
}

impl AsRef<[u8]> for FileReadBuf {
    /// 返回拥有字节或映射范围对应的只读切片。
    fn as_ref(&self) -> &[u8] {
        match self {
            Self::Owned { data, .. } => data,
            Self::Mapped { map, range, .. } => &map[range.clone()],
        }
    }
}