rong_core 0.3.0

Core runtime types for RongJS
Documentation
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use crate::{
    FromJSValue, HostError, IntoJSValue, JSContext, JSObject, JSObjectOps, JSResult, JSTypeOf,
    JSValue, JSValueImpl, JSValueMapper,
};
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;

pub struct JSArray<V: JSValueImpl>(JSObject<V>);

impl<V: JSValueImpl> Deref for JSArray<V> {
    type Target = JSObject<V>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<V: JSValueImpl> Clone for JSArray<V> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<V> IntoJSValue<V> for JSArray<V>
where
    V: JSValueImpl,
{
    fn into_js_value(self, _ctx: &JSContext<V::Context>) -> JSValue<V> {
        self.0.into_js_value()
    }
}

impl<V> FromJSValue<V> for JSArray<V>
where
    V: JSTypeOf,
{
    fn from_js_value(ctx: &JSContext<V::Context>, value: JSValue<V>) -> JSResult<Self> {
        if value.is_array() {
            JSObject::from_js_value(ctx, value).map(Self)
        } else {
            Err(HostError::not_array().into())
        }
    }
}

/// Trait for primitive JavaScript array index operations.
pub trait JSArrayOps: JSValueImpl {
    /// Create a new empty array.
    fn new_array(ctx: &Self::Context) -> Self;

    /// Get element at index.
    ///
    /// Returns the element value or an exception.
    fn get_index(&self, index: u32) -> Self;

    /// Set element at index.
    ///
    /// Returns `undefined` on success or an exception.
    fn set_index(&self, index: u32, value: Self) -> Self;
}

impl<V> JSArray<V>
where
    V: JSObjectOps + JSArrayOps,
{
    /// Create a new empty JavaScript array.
    pub fn new(ctx: &JSContext<V::Context>) -> JSResult<Self> {
        let value = V::new_array(ctx.as_ref());
        value.try_map(|value| Self::from_js_value(ctx, JSValue::from_raw(ctx, value)))?
    }

    /// Get the JavaScript `length` property.
    pub fn len(&self) -> JSResult<u32> {
        self.0.get::<_, u32>("length")
    }

    /// Check whether the array is empty.
    pub fn is_empty(&self) -> JSResult<bool> {
        self.len().map(|len| len == 0)
    }

    /// Get the raw JS value at the given index.
    pub fn get_value(&self, index: u32) -> JSResult<JSValue<V>> {
        let ctx = self.context();
        self.as_value()
            .get_index(index)
            .try_map(|value| JSValue::from_raw(&ctx, value))
    }

    /// Set the raw JS value at the given index.
    pub fn set_value(&self, index: u32, value: JSValue<V>) -> JSResult<()> {
        self.as_value()
            .set_index(index, value.into_value())
            .try_map(|_| ())
    }

    /// Get an optionally-present element with Rust conversion semantics.
    pub fn get_opt<T>(&self, index: u32) -> JSResult<Option<T>>
    where
        T: FromJSValue<V>,
    {
        if !self.has_index(index)? {
            return Ok(None);
        }

        let ctx = self.context();
        let value = self.get_value(index)?;
        T::from_js_value(&ctx, value).map(Some)
    }

    /// Set an element after Rust-to-JS conversion.
    pub fn set<T>(&self, index: u32, value: T) -> JSResult<()>
    where
        T: IntoJSValue<V>,
    {
        let ctx = self.context();
        self.set_value(index, value.into_js_value(&ctx))
    }

    /// Delete an array index using primitive object semantics.
    pub fn delete(&self, index: u32) -> JSResult<bool> {
        self.0.delete(index)
    }

    /// Check whether an index is present using primitive object semantics.
    pub fn has_index(&self, index: u32) -> JSResult<bool> {
        self.0.has_property(index)
    }

    /// Push a raw JS value using primitive index writes.
    pub fn push_value(&self, value: JSValue<V>) -> JSResult<u32> {
        let index = self.len()?;
        self.set_value(index, value)?;
        Ok(index + 1)
    }

    /// Push a Rust value and return the new array length.
    pub fn push<T>(&self, value: T) -> JSResult<u32>
    where
        T: IntoJSValue<V>,
    {
        let ctx = self.context();
        self.push_value(value.into_js_value(&ctx))
    }

    /// Pop a raw JS value using primitive index operations.
    pub fn pop_value(&self) -> JSResult<JSValue<V>> {
        let len = self.len()?;
        let ctx = self.context();
        if len == 0 {
            return Ok(JSValue::undefined(&ctx));
        }

        let index = len - 1;
        let value = self.get_value(index)?;
        self.delete(index)?;
        self.0.set("length", index)?;
        Ok(value)
    }

    /// Pop an optionally-present element with Rust conversion semantics.
    pub fn pop_opt<T>(&self) -> JSResult<Option<T>>
    where
        T: FromJSValue<V>,
    {
        if self.is_empty()? {
            return Ok(None);
        }

        let ctx = self.context();
        let value = self.pop_value()?;
        T::from_js_value(&ctx, value).map(Some)
    }

    /// Iterate over typed values in `[0, length)`.
    pub fn iter<T>(&self) -> JSResult<ArrayIter<V, T>>
    where
        T: FromJSValue<V>,
    {
        Ok(ArrayIter {
            array: self.clone(),
            index: 0,
            count: self.len()?,
            marker: PhantomData,
        })
    }

    /// Iterate over raw values in `[0, length)`.
    pub fn iter_values(&self) -> JSResult<ArrayValueIter<V>> {
        Ok(ArrayValueIter {
            array: self.clone(),
            index: 0,
            count: self.len()?,
        })
    }

    /// Iterate over present values only, skipping holes.
    pub fn iter_present<T>(&self) -> JSResult<ArrayPresentIter<V, T>>
    where
        T: FromJSValue<V>,
    {
        Ok(ArrayPresentIter {
            array: self.clone(),
            index: 0,
            count: self.len()?,
            marker: PhantomData,
        })
    }

    /// Construct a JSArray from a JSObject if it is an array.
    pub fn from_object(obj: JSObject<V>) -> Option<Self> {
        if obj.as_value().is_array() {
            Some(Self(obj))
        } else {
            None
        }
    }
}

/// Iterator over typed JavaScript values in an array.
pub struct ArrayIter<V, T>
where
    V: JSObjectOps + JSArrayOps,
    T: FromJSValue<V>,
{
    array: JSArray<V>,
    index: u32,
    count: u32,
    marker: PhantomData<T>,
}

impl<V, T> Iterator for ArrayIter<V, T>
where
    V: JSObjectOps + JSArrayOps,
    T: FromJSValue<V>,
{
    type Item = JSResult<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let ctx = self.array.context();
            let result = self
                .array
                .get_value(self.index)
                .and_then(|value| T::from_js_value(&ctx, value));
            self.index += 1;
            Some(result)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

impl<V, T> ExactSizeIterator for ArrayIter<V, T>
where
    V: JSObjectOps + JSArrayOps,
    T: FromJSValue<V>,
{
    fn len(&self) -> usize {
        (self.count - self.index) as usize
    }
}

/// Iterator over raw JavaScript values in an array.
pub struct ArrayValueIter<V>
where
    V: JSObjectOps + JSArrayOps,
{
    array: JSArray<V>,
    index: u32,
    count: u32,
}

impl<V> Iterator for ArrayValueIter<V>
where
    V: JSObjectOps + JSArrayOps,
{
    type Item = JSResult<JSValue<V>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let result = self.array.get_value(self.index);
            self.index += 1;
            Some(result)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

impl<V> ExactSizeIterator for ArrayValueIter<V>
where
    V: JSObjectOps + JSArrayOps,
{
    fn len(&self) -> usize {
        (self.count - self.index) as usize
    }
}

/// Iterator over present JavaScript array entries converted into Rust values.
pub struct ArrayPresentIter<V, T>
where
    V: JSObjectOps + JSArrayOps,
    T: FromJSValue<V>,
{
    array: JSArray<V>,
    index: u32,
    count: u32,
    marker: PhantomData<T>,
}

impl<V, T> Iterator for ArrayPresentIter<V, T>
where
    V: JSObjectOps + JSArrayOps,
    T: FromJSValue<V>,
{
    type Item = JSResult<T>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.count {
            let index = self.index;
            self.index += 1;

            let has_index = match self.array.has_index(index) {
                Ok(has_index) => has_index,
                Err(err) => return Some(Err(err)),
            };

            if has_index {
                let ctx = self.array.context();
                let value = match self.array.get_value(index) {
                    Ok(value) => value,
                    Err(err) => return Some(Err(err)),
                };
                return Some(T::from_js_value(&ctx, value));
            }
        }

        None
    }
}

/// Converts a Rust Vec into a JavaScript array.
impl<V, T> IntoJSValue<V> for Vec<T>
where
    V: JSObjectOps + JSArrayOps,
    T: IntoJSValue<V>,
{
    fn into_js_value(self, ctx: &JSContext<V::Context>) -> JSValue<V> {
        let array = JSArray::new(ctx).unwrap();
        for item in self {
            array.push(item).expect("Failed to push value into array");
        }
        <JSArray<V> as IntoJSValue<V>>::into_js_value(array, ctx)
    }
}

/// Converts a JavaScript array to a Rust Vec using dense array semantics.
impl<V, T> FromJSValue<V> for Vec<T>
where
    V: JSTypeOf,
    V: JSObjectOps + JSArrayOps,
    T: FromJSValue<V>,
{
    fn from_js_value(ctx: &JSContext<V::Context>, value: JSValue<V>) -> JSResult<Self> {
        if value.is_array() {
            let array = JSArray::from_js_value(ctx, value)?;
            array.iter::<T>()?.collect::<JSResult<Vec<_>>>()
        } else {
            Err(HostError::not_array().into())
        }
    }
}

// blanket implementing.
impl<V: JSValueImpl> crate::function::JSParameterType for JSArray<V> {}

impl<V> fmt::Display for JSArray<V>
where
    V: JSTypeOf + crate::JSValueConversion,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.deref().fmt(f)
    }
}

impl<V> fmt::Debug for JSArray<V>
where
    V: JSTypeOf + crate::JSValueConversion,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "JSArray({})", self)
    }
}