Skip to content

Commit 9769d65

Browse files
committed
+ SharedArrayBuffer
1 parent 7ca0d4e commit 9769d65

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed

Sources/ECMAScript/ArrayBuffer.swift

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,63 @@ public class ArrayBuffer: JSBridgedClass {
3333
}
3434
}
3535

36+
public class SharedArrayBuffer: JSBridgedClass {
37+
public class var constructor: JSFunction? { JSObject.global.SharedArrayBuffer.function }
38+
39+
public let jsObject: JSObject
40+
41+
public required init(unsafelyWrapping jsObject: JSObject) {
42+
self.jsObject = jsObject
43+
}
44+
45+
public convenience init(length: Int) {
46+
self.init(unsafelyWrapping: Self.constructor!.new(length))
47+
}
48+
49+
public convenience init(length: Int, maxByteLength: Int) {
50+
self.init(unsafelyWrapping: Self.constructor!.new(length, ["maxByteLength": maxByteLength]))
51+
}
52+
53+
public var byteLength: Int {
54+
Int(jsObject.byteLength.number!)
55+
}
56+
57+
public var growable: Bool {
58+
jsObject.growable.boolean!
59+
}
60+
61+
public var maxByteLength: Int {
62+
Int(jsObject.maxByteLength.number!)
63+
}
64+
65+
public func grow(newLength: Int) {
66+
_ = jsObject.grow!(newLength)
67+
}
68+
69+
public func slice(begin: Int) -> SharedArrayBuffer {
70+
jsObject.slice!(begin).fromJSValue()!
71+
}
72+
public func slice(begin: Int, end: Int) -> SharedArrayBuffer {
73+
jsObject.slice!(begin, end).fromJSValue()!
74+
}
75+
}
76+
77+
public protocol ArrayBuffer_or_SharedArrayBuffer: JSValueCompatible {}
78+
extension ArrayBuffer: ArrayBuffer_or_SharedArrayBuffer {}
79+
extension SharedArrayBuffer: ArrayBuffer_or_SharedArrayBuffer {}
80+
3681
public extension JSTypedArray {
3782
convenience init(_ arrayBuffer: ArrayBuffer) {
3883
self.init(unsafelyWrapping: Self.constructor!.new(arrayBuffer))
3984
}
4085

86+
convenience init(_ sharedArrayBuffer: SharedArrayBuffer) {
87+
self.init(unsafelyWrapping: Self.constructor!.new(sharedArrayBuffer))
88+
}
89+
4190
@inlinable
42-
var buffer: ArrayBuffer {
43-
ArrayBuffer(unsafelyWrapping: jsObject.buffer.object!)
91+
var buffer: ArrayBuffer_or_SharedArrayBuffer {
92+
(ArrayBuffer(from: jsObject.buffer) ?? SharedArrayBuffer(from: jsObject.buffer))!
4493
}
4594
}
4695

@@ -53,5 +102,11 @@ public extension JSTypedArray {
53102
Data(buffer: $0)
54103
}
55104
}
105+
106+
init(_ sharedArrayBuffer: SharedArrayBuffer) {
107+
self = JSTypedArray<UInt8>(sharedArrayBuffer).withUnsafeBytes {
108+
Data(buffer: $0)
109+
}
110+
}
56111
}
57112
#endif

0 commit comments

Comments
 (0)