forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSValue.swift
More file actions
111 lines (92 loc) · 2.75 KB
/
JSValue.swift
File metadata and controls
111 lines (92 loc) · 2.75 KB
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
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)
}
// MARK: - Accessors
public extension JSValue {
var boolean: Bool? {
switch self {
case let .boolean(boolean): return boolean
default: return nil
}
}
var string: String? {
switch self {
case let .string(string): return string
default: return nil
}
}
var number: Double? {
switch self {
case let .number(number): return number
default: return nil
}
}
var object: JSObjectRef? {
switch self {
case let .object(object): return object
default: return nil
}
}
var array: JSArrayRef? {
object.flatMap { JSArrayRef($0) }
}
var isNull: Bool { return self == .null }
var isUndefined: Bool { return self == .undefined }
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))
}
}
// MARK: - ExpressibleByStringLiteral
extension JSValue: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .string(value)
}
}
// MARK: - ExpressibleByFloatLiteral
extension JSValue: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = .number(value)
}
}
// MARK: - Functions
internal 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()
}
internal 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)
}
}
internal 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()
}
internal 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)
}
}