Skip to content

Commit a87af4e

Browse files
committed
Update JSTypedArray.swift
1 parent 8c493be commit a87af4e

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

Sources/JavaScriptKit/JSTypedArray.swift

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,43 +9,36 @@ public protocol TypedArrayElement: JSValueConvertible, JSValueConstructible {
99
static var typedArrayClass: JSFunctionRef { get }
1010
}
1111

12-
public class JSTypedArray<Element>: JSObjectRef, ExpressibleByArrayLiteral where Element: TypedArrayElement {
12+
public class JSTypedArray<Element>: JSBridgedClass, ExpressibleByArrayLiteral where Element: TypedArrayElement {
13+
public static var classRef: JSFunctionRef { Element.typedArrayClass }
14+
public var objectRef: JSObjectRef
1315
public subscript(_ index: Int) -> Element {
1416
get {
15-
return Element.construct(from: getJSValue(this: self, index: Int32(index)))!
17+
return Element.construct(from: objectRef[index])!
1618
}
1719
set {
18-
setJSValue(this: self, index: Int32(index), value: newValue.jsValue())
20+
self.objectRef[index] = newValue.jsValue()
1921
}
2022
}
2123

2224
public init(length: Int) {
23-
let jsObject = Element.typedArrayClass.new(length)
24-
// _retain is necessary here because the JSObjectRef we used to create the array
25-
// goes out of scope and is deinitialized when this init() returns, causing
26-
// the JS side to decrement the object's reference count. JSTypedArray will also
27-
// call _release() when deinitialized because it inherits from JSObjectRef, so this
28-
// will not leak memory.
29-
_retain(jsObject.id)
30-
super.init(id: jsObject.id)
25+
objectRef = Element.typedArrayClass.new(length)
3126
}
3227

33-
public init?(objectRef jsObject: JSObjectRef) {
34-
guard jsObject.isInstanceOf(Element.typedArrayClass) else { return nil }
35-
_retain(jsObject.id)
36-
super.init(id: jsObject.id)
28+
required public init(withCompatibleObject jsObject: JSObjectRef) {
29+
objectRef = jsObject
3730
}
3831

3932
required public convenience init(arrayLiteral elements: Element...) {
4033
self.init(elements)
4134
}
4235

43-
public init(_ array: [Element]) {
36+
public convenience init(_ array: [Element]) {
4437
var resultObj = JavaScriptObjectRef()
4538
array.withUnsafeBufferPointer { ptr in
4639
_create_typed_array(Element.typedArrayKind, ptr.baseAddress!, Int32(array.count), &resultObj)
4740
}
48-
super.init(id: resultObj)
41+
self.init(withCompatibleObject: JSObjectRef(id: resultObj))
4942
}
5043

5144
public convenience init(_ stride: StrideTo<Element>) where Element: Strideable {

0 commit comments

Comments
 (0)