Skip to content

Instantly share code, notes, and snippets.

@hyperandroid
Created September 16, 2018 13:16
Show Gist options
  • Save hyperandroid/52f8198347d61c3fa62c75c72c31deb6 to your computer and use it in GitHub Desktop.
Save hyperandroid/52f8198347d61c3fa62c75c72c31deb6 to your computer and use it in GitHub Desktop.
JavascriptCore ArrayBuffer from Data
// allocate a pointer to hold contents
let ptr: UnsafeMutableBufferPointer<UInt8> = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: contents!.count)
// copy Data into ptr
contents?.withUnsafeBytes { (contentsPtr: UnsafePointer<UInt8>) -> Void in
let _ = ptr.initialize(from: UnsafeBufferPointer(start: contentsPtr, count: contents!.count))
}
var exception : JSValueRef?
let deallocator: JSTypedArrayBytesDeallocator = { ptr, deallocatorContext in
// deallocate previous allocated ptr.
ptr?.deallocate()
}
let arrayBufferRef = JSObjectMakeArrayBufferWithBytesNoCopy(
ctx.jsGlobalContextRef,
ptr.baseAddress,
contents!.count,
deallocator,
nil,
&exception)
if exception != nil {
ctx.exception = JSValue(jsValueRef: exception, in: ctx)
return nil
}
return JSValue(jsValueRef: arrayBufferRef, in: ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment