use std::fmt;
use std::ops;
use std::slice;
use rocks_sys as ll;
use crate::to_raw::ToRaw;
pub struct PinnableSlice {
raw: *mut ll::rocks_pinnable_slice_t,
}
impl ToRaw<ll::rocks_pinnable_slice_t> for PinnableSlice {
fn raw(&self) -> *mut ll::rocks_pinnable_slice_t {
self.raw
}
}
impl Drop for PinnableSlice {
fn drop(&mut self) {
unsafe {
ll::rocks_pinnable_slice_destroy(self.raw);
}
}
}
impl PinnableSlice {
pub fn new() -> PinnableSlice {
PinnableSlice {
raw: unsafe { ll::rocks_pinnable_slice_create() },
}
}
#[inline]
pub fn data(&self) -> *const u8 {
unsafe { ll::rocks_pinnable_slice_data(self.raw) as *const u8 }
}
#[inline]
pub fn size(&self) -> usize {
unsafe { ll::rocks_pinnable_slice_size(self.raw) as usize }
}
}
impl fmt::Debug for PinnableSlice {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = unsafe { slice::from_raw_parts(self.data(), self.len()) };
write!(f, "{:?}", String::from_utf8_lossy(s))
}
}
impl Default for PinnableSlice {
fn default() -> Self {
PinnableSlice::new()
}
}
impl ops::Deref for PinnableSlice {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.data(), self.size()) }
}
}
impl AsRef<[u8]> for PinnableSlice {
fn as_ref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.data(), self.len()) }
}
}
impl<'a> PartialEq<&'a [u8]> for PinnableSlice {
fn eq(&self, rhs: &&[u8]) -> bool {
&self.as_ref() == rhs
}
}
impl<'a, 'b> PartialEq<&'b [u8]> for &'a PinnableSlice {
fn eq(&self, rhs: &&[u8]) -> bool {
&self.as_ref() == rhs
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pinnable_slice() {
let s = PinnableSlice::new();
assert_eq!(s, b"");
assert_eq!(&format!("{:?}", s), "\"\"");
}
}