#![no_std]
extern crate alloc;
use alloc::vec::Vec;
use bytes::Bytes;
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum LogisticsError {
#[error("Cannot refine empty data: buffer must contain at least one byte")]
EmptyBuffer,
}
#[doc(alias = "PinnedBuffer")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawResource {
inner: Bytes,
}
unsafe impl Send for RawResource {}
unsafe impl Sync for RawResource {}
impl RawResource {
pub fn refine(data: Vec<u8>) -> Result<Self, LogisticsError> {
if data.is_empty() {
return Err(LogisticsError::EmptyBuffer);
}
Ok(Self {
inner: Bytes::from(data),
})
}
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.inner.as_ptr()
}
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub unsafe fn as_slice(&self) -> &[u8] {
&self.inner
}
pub fn as_bytes(&self) -> &[u8] {
&self.inner
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_refine_success() {
let data = alloc::vec![1, 2, 3, 4, 5];
let resource = RawResource::refine(data).expect("should succeed");
assert_eq!(resource.len(), 5);
assert!(!resource.is_empty());
}
#[test]
fn test_refine_empty_fails() {
let data: Vec<u8> = alloc::vec![];
let result = RawResource::refine(data);
assert!(result.is_err());
}
#[test]
fn test_as_slice() {
let data = alloc::vec![10, 20, 30];
let resource = RawResource::refine(data).expect("should succeed");
let slice = unsafe { resource.as_slice() };
assert_eq!(slice, &[10, 20, 30]);
}
#[test]
fn test_drop_is_called() {
let data = alloc::vec![1, 2, 3, 4, 5];
let resource = RawResource::refine(data).expect("should succeed");
drop(resource);
}
}