-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathData+JSValue.swift
More file actions
42 lines (38 loc) · 1.61 KB
/
Data+JSValue.swift
File metadata and controls
42 lines (38 loc) · 1.61 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
import Foundation
import JavaScriptKit
/// Data <-> Uint8Array conversion. The conversion is lossless and copies the bytes at most once per conversion
extension Data: ConvertibleToJSValue, ConstructibleFromJSValue {
/// Convert a Data to a JSTypedArray<UInt8>.
///
/// - Returns: A Uint8Array that contains the bytes of the Data.
public var jsTypedArray: JSTypedArray<UInt8> {
self.withUnsafeBytes { buffer in
return JSTypedArray<UInt8>(buffer: buffer.bindMemory(to: UInt8.self))
}
}
/// Convert a Data to a JSValue.
///
/// - Returns: A JSValue that contains the bytes of the Data as a Uint8Array.
public var jsValue: JSValue { jsTypedArray.jsValue }
/// Construct a Data from a JSTypedArray<UInt8>.
public static func construct(from uint8Array: JSTypedArray<UInt8>) -> Data? {
// First, allocate the data storage
var data = Data(count: uint8Array.lengthInBytes)
// Then, copy the byte contents into the Data buffer
data.withUnsafeMutableBytes { destinationBuffer in
uint8Array.copyMemory(to: destinationBuffer.bindMemory(to: UInt8.self))
}
return data
}
/// Construct a Data from a JSValue.
///
/// - Parameter jsValue: The JSValue to construct a Data from.
/// - Returns: A Data, if the JSValue is a Uint8Array.
public static func construct(from jsValue: JSValue) -> Data? {
guard let uint8Array = JSTypedArray<UInt8>(from: jsValue) else {
// If the JSValue is not a Uint8Array, fail.
return nil
}
return construct(from: uint8Array)
}
}