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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use crate::{Ctx, Value};
use rquickjs_sys as qjs;
use std::{
iter::{ExactSizeIterator, FusedIterator},
mem,
};
pub struct ValueIter<'js> {
value: mem::ManuallyDrop<MultiValue<'js>>,
current: usize,
}
impl<'js> Iterator for ValueIter<'js> {
type Item = Value<'js>;
fn next(&mut self) -> Option<Self::Item> {
if self.value.len == self.current {
return None;
}
unsafe {
let ptr = self.value.ptr.add(self.current);
self.current += 1;
if self.value.ownership {
Some(Value::from_js_value(self.value.ctx, *ptr).unwrap())
} else {
Some(Value::from_js_value_const(self.value.ctx, *ptr).unwrap())
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.value.len, Some(self.value.len))
}
}
impl<'js> FusedIterator for ValueIter<'js> {}
impl<'js> ExactSizeIterator for ValueIter<'js> {
fn len(&self) -> usize {
self.value.len - self.current
}
}
impl<'js> Drop for ValueIter<'js> {
fn drop(&mut self) {
unsafe {
if self.value.ownership {
self.current += 1;
for v in self.current..self.value.len {
let ptr = self.value.ptr.add(v);
Value::from_js_value(self.value.ctx, *ptr).ok();
}
}
}
}
}
pub struct MultiValue<'js> {
ctx: Ctx<'js>,
len: usize,
ptr: *mut qjs::JSValue,
ownership: bool,
}
impl<'js> Clone for MultiValue<'js> {
fn clone(&self) -> Self {
MultiValue {
ctx: self.ctx,
len: self.len,
ptr: self.ptr,
ownership: false,
}
}
}
impl<'js> MultiValue<'js> {
#[allow(dead_code)]
pub(crate) unsafe fn from_value_count(
ctx: Ctx<'js>,
len: usize,
ptr: *mut qjs::JSValue,
) -> Self {
MultiValue {
ctx,
len,
ptr,
ownership: true,
}
}
#[allow(dead_code)]
pub(crate) unsafe fn from_value_count_const(
ctx: Ctx<'js>,
len: usize,
ptr: *mut qjs::JSValue,
) -> Self {
MultiValue {
ctx,
len,
ptr,
ownership: false,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn into_vec(mut self) -> Vec<Value<'js>> {
self.iter().collect()
}
pub fn iter(&mut self) -> ValueIter<'js> {
let res = ValueIter {
value: mem::ManuallyDrop::new(MultiValue {
ctx: self.ctx,
len: self.len,
ptr: self.ptr,
ownership: self.ownership,
}),
current: 0,
};
self.ownership = false;
res
}
}
impl<'js> Drop for MultiValue<'js> {
fn drop(&mut self) {
mem::drop(self.iter())
}
}