napi-rs/napi/src/js_values/buffer.rs

89 lines
1.9 KiB
Rust
Raw Normal View History

2020-09-28 01:27:37 +09:00
use std::mem;
use std::ops::Deref;
use std::ptr;
2020-09-28 01:27:37 +09:00
use super::Value;
#[cfg(feature = "serde-json")]
use super::ValueType;
use crate::error::check_status;
2020-09-28 01:27:37 +09:00
use crate::{sys, JsUnknown, Ref, Result};
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct JsBuffer(pub(crate) Value);
#[derive(Debug)]
2020-09-28 01:27:37 +09:00
pub struct JsBufferValue {
pub(crate) value: JsBuffer,
data: mem::ManuallyDrop<Vec<u8>>,
}
2020-09-28 01:27:37 +09:00
impl JsBuffer {
pub fn into_value(self) -> Result<JsBufferValue> {
let mut data = ptr::null_mut();
let mut len: u64 = 0;
check_status(unsafe {
2020-09-28 01:27:37 +09:00
sys::napi_get_buffer_info(self.0.env, self.0.value, &mut data, &mut len)
})?;
2020-09-28 01:27:37 +09:00
Ok(JsBufferValue {
data: mem::ManuallyDrop::new(unsafe {
Vec::from_raw_parts(data as *mut _, len as usize, len as usize)
}),
value: self,
})
}
#[inline]
2020-09-28 01:27:37 +09:00
pub fn into_ref(self) -> Result<Ref<JsBufferValue>> {
Ref::new(self.0, 1, self.into_value()?)
}
}
2020-09-28 01:27:37 +09:00
impl JsBufferValue {
#[cfg(feature = "serde-json")]
pub(crate) fn from_raw(env: sys::napi_env, value: sys::napi_value) -> Result<Self> {
let mut data = ptr::null_mut();
let mut len: u64 = 0;
2020-08-26 01:07:27 +09:00
check_status(unsafe { sys::napi_get_buffer_info(env, value, &mut data, &mut len) })?;
2020-09-28 01:27:37 +09:00
Ok(Self {
value: JsBuffer(Value {
env,
value,
value_type: ValueType::Object,
}),
2020-09-28 01:27:37 +09:00
data: mem::ManuallyDrop::new(unsafe {
Vec::from_raw_parts(data as *mut _, len as usize, len as usize)
}),
})
}
2020-09-28 01:27:37 +09:00
pub fn new(value: JsBuffer, data: Vec<u8>) -> Self {
JsBufferValue {
value,
data: mem::ManuallyDrop::new(data),
}
}
2020-09-28 01:27:37 +09:00
pub fn into_raw(self) -> JsBuffer {
self.value
}
pub fn into_unknown(self) -> Result<JsUnknown> {
self.value.into_unknown()
}
}
2020-09-28 01:27:37 +09:00
impl AsRef<[u8]> for JsBufferValue {
fn as_ref(&self) -> &[u8] {
2020-09-28 01:27:37 +09:00
self.data.as_slice()
}
}
2020-09-28 01:27:37 +09:00
impl Deref for JsBufferValue {
type Target = [u8];
fn deref(&self) -> &[u8] {
2020-09-28 01:27:37 +09:00
self.data.as_slice()
2020-08-26 01:07:27 +09:00
}
}