2020-08-26 01:07:27 +09:00
|
|
|
use std::convert::TryFrom;
|
2020-08-10 13:37:58 +09:00
|
|
|
use std::ops::Deref;
|
2020-06-21 20:10:06 +09:00
|
|
|
use std::ptr;
|
|
|
|
use std::slice;
|
|
|
|
|
2020-07-03 01:36:45 +09:00
|
|
|
use super::{JsObject, JsUnknown, NapiValue, Value, ValueType};
|
2020-06-21 20:10:06 +09:00
|
|
|
use crate::error::check_status;
|
2020-08-26 01:07:27 +09:00
|
|
|
use crate::{sys, Error, Result};
|
2020-06-21 20:10:06 +09:00
|
|
|
|
2020-08-10 13:37:58 +09:00
|
|
|
#[derive(Debug)]
|
2020-06-21 20:10:06 +09:00
|
|
|
pub struct JsBuffer {
|
|
|
|
pub value: JsObject,
|
2020-08-10 13:37:58 +09:00
|
|
|
pub data: &'static [u8],
|
2020-06-21 20:10:06 +09:00
|
|
|
}
|
|
|
|
|
2020-07-03 01:36:45 +09:00
|
|
|
impl JsBuffer {
|
2020-08-10 13:37:58 +09:00
|
|
|
pub(crate) fn from_raw_unchecked(
|
|
|
|
env: sys::napi_env,
|
|
|
|
value: sys::napi_value,
|
|
|
|
data: *mut u8,
|
|
|
|
len: usize,
|
|
|
|
) -> Self {
|
2020-07-18 03:00:48 +09:00
|
|
|
Self {
|
|
|
|
value: JsObject(Value {
|
|
|
|
env,
|
|
|
|
value,
|
|
|
|
value_type: ValueType::Object,
|
|
|
|
}),
|
2020-08-10 13:37:58 +09:00
|
|
|
data: unsafe { slice::from_raw_parts_mut(data, len) },
|
2020-07-18 03:00:48 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-03 01:36:45 +09:00
|
|
|
pub fn into_unknown(self) -> Result<JsUnknown> {
|
|
|
|
self.value.into_unknown()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-21 20:10:06 +09:00
|
|
|
impl NapiValue for JsBuffer {
|
|
|
|
fn raw_value(&self) -> sys::napi_value {
|
|
|
|
self.value.0.value
|
|
|
|
}
|
|
|
|
|
|
|
|
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-06-21 20:10:06 +09:00
|
|
|
Ok(JsBuffer {
|
|
|
|
value: JsObject(Value {
|
|
|
|
env,
|
|
|
|
value,
|
|
|
|
value_type: ValueType::Object,
|
|
|
|
}),
|
2020-08-10 13:37:58 +09:00
|
|
|
data: unsafe { slice::from_raw_parts_mut(data as *mut _, len as usize) },
|
2020-06-21 20:10:06 +09:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsRef<[u8]> for JsBuffer {
|
|
|
|
fn as_ref(&self) -> &[u8] {
|
2020-08-10 13:37:58 +09:00
|
|
|
self.data
|
2020-06-21 20:10:06 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for JsBuffer {
|
|
|
|
type Target = [u8];
|
|
|
|
|
|
|
|
fn deref(&self) -> &[u8] {
|
2020-08-10 13:37:58 +09:00
|
|
|
self.data
|
2020-06-21 20:10:06 +09:00
|
|
|
}
|
|
|
|
}
|
2020-08-26 01:07:27 +09:00
|
|
|
|
|
|
|
impl TryFrom<JsUnknown> for JsBuffer {
|
|
|
|
type Error = Error;
|
|
|
|
fn try_from(value: JsUnknown) -> Result<JsBuffer> {
|
|
|
|
JsBuffer::from_raw(value.0.env, value.0.value)
|
|
|
|
}
|
|
|
|
}
|