|
| 1 | +public class JSRef { |
| 2 | + let id: UInt32 |
| 3 | + init(id: UInt32) { |
| 4 | + self.id = id |
| 5 | + } |
| 6 | + public static func global() -> JSRef { |
| 7 | + .init(id: _JS_Predef_Value_Global) |
| 8 | + } |
| 9 | + |
| 10 | + deinit { |
| 11 | + |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +public enum JSValue { |
| 16 | + case boolean(Bool) |
| 17 | + case string(String) |
| 18 | +} |
| 19 | + |
| 20 | +protocol JSValueConvertible { |
| 21 | + func jsValue() -> JSValue |
| 22 | +} |
| 23 | + |
| 24 | +extension Bool: JSValueConvertible { |
| 25 | + func jsValue() -> JSValue { |
| 26 | + .boolean(self) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +import _CJavaScriptKit |
| 31 | + |
| 32 | +public func getJSValue(this: JSRef, name: String) -> JSValue { |
| 33 | + var kind: JavaScriptValueKind = JavaScriptValueKind_Invalid |
| 34 | + var payload: JavaScriptPayload = 0 |
| 35 | + _get_js_value(this.id, name, Int32(name.count), &kind, &payload) |
| 36 | + switch kind { |
| 37 | + case JavaScriptValueKind_Invalid: |
| 38 | + fatalError() |
| 39 | + case JavaScriptValueKind_Boolean: |
| 40 | + return .boolean(payload != 0) |
| 41 | + case JavaScriptValueKind_String: |
| 42 | + let ptr = UnsafePointer<UInt8>(bitPattern: UInt(payload))! |
| 43 | + return .string(String(decodingCString: ptr, as: UTF8.self)) |
| 44 | + default: |
| 45 | + fatalError("unreachable") |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +public func setJSValue(this: JSRef, name: String, value: JSValue) { |
| 50 | + |
| 51 | + let kind: JavaScriptValueKind |
| 52 | + let payload: JavaScriptPayload |
| 53 | + switch value { |
| 54 | + case let .boolean(boolValue): |
| 55 | + kind = JavaScriptValueKind_Boolean |
| 56 | + payload = boolValue ? 1 : 0 |
| 57 | + case var .string(stringValue): |
| 58 | + kind = JavaScriptValueKind_String |
| 59 | + stringValue.withUTF8 { ptr in |
| 60 | + let ptrValue = unsafeBitCast(ptr, to: UInt32.self) |
| 61 | + _set_js_value(this.id, name, Int32(name.count), kind, ptrValue) |
| 62 | + } |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + print("\(#function) with prop name \"\(name)\" (length: \(name.count))") |
| 67 | + _set_js_value(this.id, name, Int32(name.count), kind, payload) |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | +#if Xcode |
| 72 | +func _set_js_value(_ _this: JavaScriptValueId, _ prop: UnsafePointer<Int8>!, _ length: Int32, _ kind: JavaScriptValueKind, _ value: JavaScriptPayload) { fatalError() } |
| 73 | +func _get_js_value(_ _this: JavaScriptValueId, _ prop: UnsafePointer<Int8>!, _ length: Int32, _ kind: UnsafeMutablePointer<JavaScriptValueKind>!, _ value: UnsafeMutablePointer<JavaScriptPayload>!) {} |
| 74 | +#endif |
0 commit comments