//! 零拷贝优化模块
//!
//! 提供零拷贝数据结构和工具函数，避免不必要的内存分配和数据拷贝

use std::ops::Deref;

/// 零拷贝字节数据包装器
///
/// 使用 `Bytes` 替代 `String` 和 `Vec<u8>`，实现零拷贝数据传递
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ZeroCopyBytes(pub bytes::Bytes);

impl ZeroCopyBytes {
    /// 创建新的零拷贝字节数据
    #[inline]
    pub fn new<B: Into<bytes::Bytes>>(bytes: B) -> Self {
        Self(bytes.into())
    }

    /// 获取字节切片引用
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl Deref for ZeroCopyBytes {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

impl<'a> From<&'a str> for ZeroCopyBytes {
    #[inline]
    fn from(s: &'a str) -> Self {
        Self(bytes::Bytes::copy_from_slice(s.as_bytes()))
    }
}

impl From<String> for ZeroCopyBytes {
    #[inline]
    fn from(s: String) -> Self {
        Self(bytes::Bytes::from(s.into_bytes()))
    }
}

impl<'a> From<&'a [u8]> for ZeroCopyBytes {
    #[inline]
    fn from(bytes: &'a [u8]) -> Self {
        Self(bytes::Bytes::copy_from_slice(bytes))
    }
}

impl From<Vec<u8>> for ZeroCopyBytes {
    #[inline]
    fn from(bytes: Vec<u8>) -> Self {
        Self(bytes::Bytes::from(bytes))
    }
}

impl AsRef<[u8]> for ZeroCopyBytes {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}
