1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Nicer, Rust-y APIs for structured cloning.
use glue;
use jsapi;
use rust::Runtime;
use std::ptr;
/// An RAII owned buffer for structured cloning into and out of.
pub struct StructuredCloneBuffer {
raw: *mut jsapi::JSAutoStructuredCloneBuffer,
}
impl StructuredCloneBuffer {
/// Construct a new `StructuredCloneBuffer`.
///
/// # Panics
///
/// Panics if the underlying JSAPI calls fail.
pub fn new(scope: jsapi::JS::StructuredCloneScope,
callbacks: &jsapi::JSStructuredCloneCallbacks)
-> StructuredCloneBuffer {
let raw = unsafe {
glue::NewJSAutoStructuredCloneBuffer(scope, callbacks)
};
assert!(!raw.is_null());
StructuredCloneBuffer {
raw: raw,
}
}
/// Get the raw `*mut JSStructuredCloneData` owned by this buffer.
pub fn data(&self) -> *mut jsapi::JSStructuredCloneData {
unsafe {
&mut (*self.raw).data_
}
}
/// Copy this buffer's data into a vec.
pub fn copy_to_vec(&self) -> Vec<u8> {
let len = unsafe {
glue::GetLengthOfJSStructuredCloneData(self.data())
};
let mut vec = Vec::with_capacity(len);
unsafe {
glue::CopyJSStructuredCloneData(self.data(), vec.as_mut_ptr());
}
vec
}
/// Read a JS value out of this buffer.
pub fn read(&mut self,
vp: jsapi::JS::MutableHandleValue,
callbacks: &jsapi::JSStructuredCloneCallbacks)
-> Result<(), ()> {
if unsafe {
(*self.raw).read(Runtime::get(), vp, callbacks, ptr::null_mut())
} {
Ok(())
} else {
Err(())
}
}
/// Write a JS value into this buffer.
pub fn write(&mut self,
v: jsapi::JS::HandleValue,
callbacks: &jsapi::JSStructuredCloneCallbacks)
-> Result<(), ()> {
if unsafe {
(*self.raw).write(Runtime::get(), v, callbacks, ptr::null_mut())
} {
Ok(())
} else {
Err(())
}
}
/// Copy the given slice into this buffer.
pub fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), ()> {
let len = bytes.len();
let src = bytes.as_ptr();
if unsafe {
glue::WriteBytesToJSStructuredCloneData(src, len, self.data())
} {
Ok(())
} else {
Err(())
}
}
}
impl Drop for StructuredCloneBuffer {
fn drop(&mut self) {
unsafe {
glue::DeleteJSAutoStructuredCloneBuffer(self.raw);
}
}
}