rust_jsc 0.5.0

High-level bindings to JavaScriptCore
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use rust_jsc_sys::{
    kJSClassAttributeNoAutomaticPrototype, kJSClassAttributeNone,
    kJSPropertyAttributeDontDelete, kJSPropertyAttributeDontEnum,
    kJSPropertyAttributeNone, kJSPropertyAttributeReadOnly, JSClassAttributes,
    JSClassRef, JSContextGroupRef, JSContextRef, JSGlobalContextRef, JSObjectRef,
    JSPropertyAttributes, JSStringRef, JSType, JSType_kJSTypeBoolean, JSType_kJSTypeNull,
    JSType_kJSTypeNumber, JSType_kJSTypeObject, JSType_kJSTypeString,
    JSType_kJSTypeSymbol, JSType_kJSTypeUndefined, JSTypedArrayType as MJSTypedArrayType,
    JSTypedArrayType_kJSTypedArrayTypeArrayBuffer,
    JSTypedArrayType_kJSTypedArrayTypeBigInt64Array,
    JSTypedArrayType_kJSTypedArrayTypeBigUint64Array,
    JSTypedArrayType_kJSTypedArrayTypeFloat32Array,
    JSTypedArrayType_kJSTypedArrayTypeFloat64Array,
    JSTypedArrayType_kJSTypedArrayTypeInt16Array,
    JSTypedArrayType_kJSTypedArrayTypeInt32Array,
    JSTypedArrayType_kJSTypedArrayTypeInt8Array, JSTypedArrayType_kJSTypedArrayTypeNone,
    JSTypedArrayType_kJSTypedArrayTypeUint16Array,
    JSTypedArrayType_kJSTypedArrayTypeUint32Array,
    JSTypedArrayType_kJSTypedArrayTypeUint8Array,
    JSTypedArrayType_kJSTypedArrayTypeUint8ClampedArray, JSValueRef,
};

use std::any::TypeId;

pub mod array;
pub mod class;
pub mod context;
pub mod date;
pub mod error;
pub mod function;
pub mod object;
pub mod promise;
pub mod reg_exp;
pub mod string;
pub mod typed_array;
pub mod value;

pub use rust_jsc_macros::*;

#[doc(hidden)]
pub use rust_jsc_sys as internal;

// re export JSAPIModuleLoader from rust_jsc_sys as JSModuleLoader
pub use rust_jsc_sys::JSAPIModuleLoader as JSModuleLoader;

/// A JavaScript context.
pub struct JSContext {
    pub(crate) inner: JSGlobalContextRef,
}

pub type PrivateData = *mut ::std::os::raw::c_void;

/// Header-only view of a `TypedData<T>` allocation.
///
/// Because `TypedData<T>` is `#[repr(C)]` with `type_id` as its first field,
/// casting any `*mut TypedData<T>` to `*const PrivateDataHeader` is valid and
/// lets us inspect the `TypeId` without knowing `T`.
#[repr(C)]
struct PrivateDataHeader {
    type_id: TypeId,
}

/// Single-allocation, cache-friendly, type-safe wrapper for `*mut c_void`.
///
/// Layout (with `#[repr(C)]`):
/// ```text
/// [ TypeId (8 bytes) | T data (sizeof T, aligned) ]
/// ```
///
/// Benefits:
/// - **One indirection** to reach the data (pointer → contiguous header+data).
/// - **Cache-friendly**: `TypeId` and small `T` share the same cache line.
/// - **No vtable dispatch**: type checking is a direct `TypeId` comparison.
#[repr(C)]
struct TypedData<T> {
    type_id: TypeId,
    data: T,
}

/// Zero-sized namespace for type-safe `*mut c_void` operations.
pub struct PrivateDataWrapper;

impl PrivateDataWrapper {
    /// Create a new wrapper and return a thin `*mut c_void` pointer to it.
    ///
    /// Performs a heap allocation containing `[TypeId | T]`.
    #[inline]
    pub fn into_raw<T: 'static>(data: T) -> *mut std::ffi::c_void {
        let typed = Box::new(TypedData {
            type_id: TypeId::of::<T>(),
            data,
        });
        Box::into_raw(typed) as *mut std::ffi::c_void
    }

    /// Recover a shared reference to the stored data, checking the type at runtime.
    /// Returns `None` if the pointer is null or the type doesn't match.
    ///
    /// # Safety
    /// The pointer must have been created by `PrivateDataWrapper::into_raw` and must
    /// not have been freed.
    #[inline]
    pub unsafe fn downcast_ref<'a, T: 'static>(
        ptr: *mut std::ffi::c_void,
    ) -> Option<&'a T> {
        if ptr.is_null() {
            return None;
        }
        let header = &*(ptr as *const PrivateDataHeader);
        if header.type_id != TypeId::of::<T>() {
            return None;
        }
        let typed = &*(ptr as *const TypedData<T>);
        Some(&typed.data)
    }

    /// Recover a mutable reference to the stored data, checking the type at runtime.
    /// Returns `None` if the pointer is null or the type doesn't match.
    ///
    /// # Safety
    /// The pointer must have been created by `PrivateDataWrapper::into_raw`, must
    /// not have been freed, and the caller must ensure exclusive access.
    #[inline]
    pub unsafe fn downcast_mut<'a, T: 'static>(
        ptr: *mut std::ffi::c_void,
    ) -> Option<&'a mut T> {
        if ptr.is_null() {
            return None;
        }
        let header = &*(ptr as *const PrivateDataHeader);
        if header.type_id != TypeId::of::<T>() {
            return None;
        }
        let typed = &mut *(ptr as *mut TypedData<T>);
        Some(&mut typed.data)
    }

    /// Take ownership of the stored data, consuming the allocation.
    /// Returns `None` if the pointer is null or the type doesn't match.
    ///
    /// On type mismatch the allocation is **not** freed — the data remains
    /// valid and can be retrieved later with the correct type.
    ///
    /// # Safety
    /// The pointer must have been created by `PrivateDataWrapper::into_raw` and must
    /// not have been previously freed. On success the pointer becomes invalid.
    #[inline]
    pub unsafe fn take<T: 'static>(ptr: *mut std::ffi::c_void) -> Option<T> {
        if ptr.is_null() {
            return None;
        }
        let header = &*(ptr as *const PrivateDataHeader);
        if header.type_id != TypeId::of::<T>() {
            return None;
        }
        let typed = Box::from_raw(ptr as *mut TypedData<T>);
        Some(typed.data)
    }

    /// Drop the allocation, freeing both the header and the contained `T`.
    ///
    /// The caller must supply the same `T` that was passed to `into_raw`.
    /// If `T` doesn't match, the call is a no-op (the data is not freed).
    ///
    /// # Safety
    /// The pointer must have been created by `PrivateDataWrapper::into_raw` and must
    /// not have been previously freed.
    #[allow(dead_code)]
    pub unsafe fn drop_raw<T: 'static>(ptr: *mut std::ffi::c_void) {
        if !ptr.is_null() {
            let header = &*(ptr as *const PrivateDataHeader);
            if header.type_id == TypeId::of::<T>() {
                let _ = Box::from_raw(ptr as *mut TypedData<T>);
            }
        }
    }
}

/// A JavaScript execution context group.
pub struct JSContextGroup {
    context_group: JSContextGroupRef,
}

/// A JavaScript class.
pub struct JSClass {
    // pub(crate) ctx: JSContextRef,
    pub(crate) inner: JSClassRef,
    pub(crate) name: String,
    pub(crate) type_id: TypeId,
}

/// A JavaScript object.
#[derive(Clone)]
pub struct JSObject {
    inner: JSObjectRef,
    value: JSValue,
}

/// A JavaScript function object.
#[derive(Clone)]
pub struct JSFunction {
    pub(crate) object: JSObject,
}

/// A JavaScript date object.
pub struct JSDate {
    pub(crate) object: JSObject,
}

/// A JavaScript regular expression object.
pub struct JSRegExp {
    pub(crate) object: JSObject,
}

/// A JavaScript typed array.
#[derive(Debug, Clone)]
pub struct JSTypedArray {
    pub(crate) object: JSObject,
}

/// A JavaScript array buffer.
#[derive(Debug, Clone)]
pub struct JSArrayBuffer {
    pub(crate) object: JSObject,
}

/// A JavaScript array.
pub struct JSArray {
    pub(crate) object: JSObject,
}

/// A JavaScript promise.
pub struct JSPromise {
    this: JSObject,
    resolver: JSPromiseResolvingFunctions,
}

/// A JavaScript promise resolving functions.
#[derive(Debug, Clone)]
pub struct JSPromiseResolvingFunctions {
    resolve: JSObject,
    reject: JSObject,
}

/// A JavaScript value.
#[derive(Debug, Clone)]
pub struct JSValue {
    pub(crate) inner: JSValueRef,
    pub(crate) ctx: JSContextRef,
}

/// A JavaScript class attribute.
pub enum JSClassAttribute {
    /// Specifies that a class has no special attributes.
    None = kJSClassAttributeNone as isize,
    /// Specifies that a class should not automatically generate a shared prototype for its instance objects.
    /// Use it in combination with set_prototype to manage prototypes manually.
    NoAutomaticPrototype = kJSClassAttributeNoAutomaticPrototype as isize,
}

impl Default for JSClassAttribute {
    fn default() -> Self {
        JSClassAttribute::None
    }
}

impl Into<JSClassAttributes> for JSClassAttribute {
    fn into(self) -> JSClassAttributes {
        self as JSClassAttributes
    }
}

/// A JavaScript value type.
#[derive(Debug, PartialEq)]
pub enum JSValueType {
    Undefined = JSType_kJSTypeUndefined as isize,
    Null = JSType_kJSTypeNull as isize,
    Boolean = JSType_kJSTypeBoolean as isize,
    Number = JSType_kJSTypeNumber as isize,
    String = JSType_kJSTypeString as isize,
    Object = JSType_kJSTypeObject as isize,
    Symbol = JSType_kJSTypeSymbol as isize,
}

impl JSValueType {
    pub(crate) fn from_js_type(value: JSType) -> JSValueType {
        match value {
            x if x == JSType_kJSTypeUndefined => JSValueType::Undefined,
            x if x == JSType_kJSTypeNull => JSValueType::Null,
            x if x == JSType_kJSTypeBoolean => JSValueType::Boolean,
            x if x == JSType_kJSTypeNumber => JSValueType::Number,
            x if x == JSType_kJSTypeString => JSValueType::String,
            x if x == JSType_kJSTypeObject => JSValueType::Object,
            x if x == JSType_kJSTypeSymbol => JSValueType::Symbol,
            x => unreachable!("Unknown JSValue type: {}", x),
        }
    }
}

/// A JavaScript typed array type.
#[derive(Debug, PartialEq)]
pub enum JSTypedArrayType {
    Int8Array = JSTypedArrayType_kJSTypedArrayTypeInt8Array as isize,
    Int16Array = JSTypedArrayType_kJSTypedArrayTypeInt16Array as isize,
    Int32Array = JSTypedArrayType_kJSTypedArrayTypeInt32Array as isize,
    Uint8Array = JSTypedArrayType_kJSTypedArrayTypeUint8Array as isize,
    Uint8ClampedArray = JSTypedArrayType_kJSTypedArrayTypeUint8ClampedArray as isize,
    Uint16Array = JSTypedArrayType_kJSTypedArrayTypeUint16Array as isize,
    Uint32Array = JSTypedArrayType_kJSTypedArrayTypeUint32Array as isize,
    Float32Array = JSTypedArrayType_kJSTypedArrayTypeFloat32Array as isize,
    Float64Array = JSTypedArrayType_kJSTypedArrayTypeFloat64Array as isize,
    ArrayBuffer = JSTypedArrayType_kJSTypedArrayTypeArrayBuffer as isize,
    None = JSTypedArrayType_kJSTypedArrayTypeNone as isize,
    BigInt64Array = JSTypedArrayType_kJSTypedArrayTypeBigInt64Array as isize,
    BigUint64Array = JSTypedArrayType_kJSTypedArrayTypeBigUint64Array as isize,
}

impl Default for JSTypedArrayType {
    fn default() -> Self {
        JSTypedArrayType::None
    }
}

impl Into<MJSTypedArrayType> for JSTypedArrayType {
    fn into(self) -> MJSTypedArrayType {
        self as MJSTypedArrayType
    }
}

impl JSTypedArrayType {
    #[allow(dead_code)]
    pub(crate) fn from_type(value: std::os::raw::c_uint) -> JSTypedArrayType {
        match value {
            x if x == JSTypedArrayType_kJSTypedArrayTypeInt8Array => {
                JSTypedArrayType::Int8Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeInt16Array => {
                JSTypedArrayType::Int16Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeInt32Array => {
                JSTypedArrayType::Int32Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeUint8Array => {
                JSTypedArrayType::Uint8Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeUint8ClampedArray => {
                JSTypedArrayType::Uint8ClampedArray
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeUint16Array => {
                JSTypedArrayType::Uint16Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeUint32Array => {
                JSTypedArrayType::Uint32Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeFloat32Array => {
                JSTypedArrayType::Float32Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeFloat64Array => {
                JSTypedArrayType::Float64Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeArrayBuffer => {
                JSTypedArrayType::ArrayBuffer
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeNone => JSTypedArrayType::None,
            x if x == JSTypedArrayType_kJSTypedArrayTypeBigInt64Array => {
                JSTypedArrayType::BigInt64Array
            }
            x if x == JSTypedArrayType_kJSTypedArrayTypeBigUint64Array => {
                JSTypedArrayType::BigUint64Array
            }
            x => unreachable!("Unknown JSTypedArrayType type: {}", x),
        }
    }
}

/// A JavaScript error.
#[derive(Debug)]
pub struct JSError {
    object: JSObject,
}

/// A JavaScript string.
/// This struct is used to retain a reference to a JavaScript string.
/// It will release the string when it goes out of scope.
pub struct JSString {
    pub(crate) inner: JSStringRef,
}

/// A JavaScript string reference.
/// This struct is used to retain a reference to a JavaScript string.
/// It won't release the string when it goes out of scope.
/// To release the string, use the `release` method.
pub struct JSStringProctected(JSStringRef);

pub type JSResult<T> = Result<T, JSError>;

// A struct to represent a JavaScript property descriptor
#[derive(Debug, Clone, Copy)]
pub struct PropertyDescriptor {
    attributes: JSPropertyAttributes,
}

impl PropertyDescriptor {
    // Constructor to create a new PropertyDescriptor with specified attributes
    pub fn new(attributes: JSPropertyAttributes) -> Self {
        Self { attributes }
    }

    // Check if the property is writable
    pub fn is_writable(&self) -> bool {
        (self.attributes & kJSPropertyAttributeReadOnly) == 0
    }

    /// Check if the property is enumerable
    ///
    /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#enumerable
    pub fn is_enumerable(&self) -> bool {
        (self.attributes & kJSPropertyAttributeDontEnum) == 0
    }

    // Check if the property is configurable
    pub fn is_configurable(&self) -> bool {
        (self.attributes & kJSPropertyAttributeDontDelete) == 0
    }
}

impl Default for PropertyDescriptor {
    fn default() -> Self {
        Self {
            attributes: kJSPropertyAttributeNone,
        }
    }
}

// A builder for constructing a set of JavaScript property attributes
pub struct PropertyDescriptorBuilder {
    attributes: JSPropertyAttributes,
}

impl PropertyDescriptorBuilder {
    // Constructor to create a new builder instance
    pub fn new() -> Self {
        Self {
            attributes: kJSPropertyAttributeNone,
        }
    }

    pub fn writable(self, value: bool) -> Self {
        self.set_attribute(kJSPropertyAttributeReadOnly, value)
    }

    pub fn enumerable(self, value: bool) -> Self {
        self.set_attribute(kJSPropertyAttributeDontEnum, value)
    }

    pub fn configurable(self, value: bool) -> Self {
        self.set_attribute(kJSPropertyAttributeDontDelete, value)
    }

    // disable specific attributes could be implemented
    fn set_attribute(mut self, attribute: JSPropertyAttributes, value: bool) -> Self {
        if value {
            self.attributes &= !attribute;
        } else {
            self.attributes |= attribute;
        }
        self
    }

    // Build and retrieve the final attributes
    pub fn build(self) -> PropertyDescriptor {
        PropertyDescriptor {
            attributes: self.attributes,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_property_descriptor_builder() {
        let builder = PropertyDescriptorBuilder::new();
        let descriptor = builder
            .writable(true)
            .enumerable(true)
            .configurable(true)
            .build();
        assert_eq!(descriptor.is_writable(), true);
        assert_eq!(descriptor.is_enumerable(), true);
        assert_eq!(descriptor.is_configurable(), true);

        let builder = PropertyDescriptorBuilder::new();
        let descriptor = builder
            .writable(false)
            .enumerable(false)
            .configurable(false)
            .build();
        assert_eq!(descriptor.is_writable(), false);
        assert_eq!(descriptor.is_enumerable(), false);
        assert_eq!(descriptor.is_configurable(), false);

        let builder = PropertyDescriptorBuilder::new();
        let descriptor = builder
            .writable(true)
            .enumerable(false)
            .configurable(true)
            .build();
        assert_eq!(descriptor.is_writable(), true);
        assert_eq!(descriptor.is_enumerable(), false);
        assert_eq!(descriptor.is_configurable(), true);

        let builder = PropertyDescriptorBuilder::new();
        let descriptor = builder.build();
        assert_eq!(descriptor.is_writable(), true);
        assert_eq!(descriptor.is_enumerable(), true);
        assert_eq!(descriptor.is_configurable(), true);
    }
}