Skip to content

Commit 008889f

Browse files
nechaidoaqrln
authored andcommitted
feat(napi): implement NapiBuffer
1 parent 3b5c3d1 commit 008889f

File tree

3 files changed

+73
-2
lines changed

3 files changed

+73
-2
lines changed

napi/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ mod value;
66

77
pub use env::NapiEnv;
88
pub use result::{NapiError, NapiErrorKind, NapiResult};
9-
pub use value::{AsNapiObject, NapiAny, NapiArray, NapiBoolean, NapiNull,
10-
NapiObject, NapiString, NapiUndefined, NapiValue,
9+
pub use value::{AsNapiObject, NapiAny, NapiArray, NapiBoolean, NapiBuffer,
10+
NapiNull, NapiObject, NapiString, NapiUndefined, NapiValue,
1111
NapiValueType};
1212

1313
pub mod sys {

napi/src/value/buffer.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
use std::ptr;
2+
use std::slice;
3+
4+
use env::NapiEnv;
5+
use result::NapiResult;
6+
use sys;
7+
8+
use super::{AsNapiObject, NapiValue};
9+
10+
#[derive(Debug)]
11+
pub struct NapiBuffer<'env, 'buf> {
12+
value: sys::napi_value,
13+
data: &'buf mut [u8],
14+
env: &'env NapiEnv,
15+
}
16+
17+
impl<'env, 'buf> NapiBuffer<'env, 'buf> {
18+
pub fn new(env: &'env NapiEnv, len: usize) -> NapiResult<Self> {
19+
let mut value = ptr::null_mut();
20+
let mut data = ptr::null_mut();
21+
22+
env.handle_status(unsafe {
23+
sys::napi_create_buffer(
24+
env.as_sys_env(),
25+
len,
26+
&mut data,
27+
&mut value,
28+
)
29+
})?;
30+
31+
Ok(Self {
32+
value,
33+
data: unsafe { slice::from_raw_parts_mut(data as *mut u8, len) },
34+
env,
35+
})
36+
}
37+
38+
pub fn len(&self) -> usize {
39+
self.data.len()
40+
}
41+
42+
pub fn is_empty(&self) -> bool {
43+
self.data.is_empty()
44+
}
45+
}
46+
47+
impl<'env, 'buf> NapiValue<'env> for NapiBuffer<'env, 'buf> {
48+
fn as_sys_value(&self) -> sys::napi_value {
49+
self.value
50+
}
51+
52+
fn env(&self) -> &'env NapiEnv {
53+
self.env
54+
}
55+
}
56+
57+
impl<'env, 'buf> AsNapiObject<'env> for NapiBuffer<'env, 'buf> {}
58+
59+
impl<'env, 'buf> AsRef<[u8]> for NapiBuffer<'env, 'buf> {
60+
fn as_ref(&self) -> &[u8] {
61+
self.data
62+
}
63+
}
64+
65+
impl<'env, 'buf> AsMut<[u8]> for NapiBuffer<'env, 'buf> {
66+
fn as_mut(&mut self) -> &mut [u8] {
67+
self.data
68+
}
69+
}

napi/src/value/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use sys;
77
mod any;
88
mod array;
99
mod boolean;
10+
mod buffer;
1011
mod null;
1112
mod number;
1213
mod object;
@@ -16,6 +17,7 @@ mod undefined;
1617
pub use self::any::NapiAny;
1718
pub use self::array::NapiArray;
1819
pub use self::boolean::NapiBoolean;
20+
pub use self::buffer::NapiBuffer;
1921
pub use self::null::NapiNull;
2022
pub use self::number::NapiNumber;
2123
pub use self::object::NapiObject;

0 commit comments

Comments
 (0)