forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSValue.swift
100 lines (86 loc) · 2.64 KB
/
JSValue.swift
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
import _CJavaScriptKit
public enum JSValue: Equatable {
case boolean(Bool)
case string(String)
case number(Double)
case object(JSObjectRef)
case null
case undefined
case function(JSFunctionRef)
public var boolean: Bool? {
switch self {
case let .boolean(boolean): return boolean
default: return nil
}
}
public var string: String? {
switch self {
case let .string(string): return string
default: return nil
}
}
public var number: Double? {
switch self {
case let .number(number): return number
default: return nil
}
}
public var object: JSObjectRef? {
switch self {
case let .object(object): return object
default: return nil
}
}
public var array: JSArrayRef? {
object.flatMap { JSArrayRef($0) }
}
public var isNull: Bool { return self == .null }
public var isUndefined: Bool { return self == .undefined }
public var function: JSFunctionRef? {
switch self {
case let .function(function): return function
default: return nil
}
}
}
extension JSValue {
public static func function(_ body: @escaping ([JSValue]) -> JSValue) -> JSValue {
.function(JSClosure(body))
}
}
extension JSValue: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension JSValue: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Double) {
self = .number(value)
}
}
public func getJSValue(this: JSObjectRef, name: String) -> JSValue {
var rawValue = RawJSValue()
_get_prop(this.id, name, Int32(name.count),
&rawValue.kind,
&rawValue.payload1, &rawValue.payload2, &rawValue.payload3)
return rawValue.jsValue()
}
public func setJSValue(this: JSObjectRef, name: String, value: JSValue) {
value.withRawJSValue { rawValue in
_set_prop(this.id, name, Int32(name.count), rawValue.kind, rawValue.payload1, rawValue.payload2, rawValue.payload3)
}
}
public func getJSValue(this: JSObjectRef, index: Int32) -> JSValue {
var rawValue = RawJSValue()
_get_subscript(this.id, index,
&rawValue.kind,
&rawValue.payload1, &rawValue.payload2, &rawValue.payload3)
return rawValue.jsValue()
}
public func setJSValue(this: JSObjectRef, index: Int32, value: JSValue) {
value.withRawJSValue { rawValue in
_set_subscript(this.id, index,
rawValue.kind,
rawValue.payload1, rawValue.payload2, rawValue.payload3)
}
}