Skip to content

Commit

Permalink
Add WasmInterpreter.heap()
Browse files Browse the repository at this point in the history
  • Loading branch information
atdrendel committed Aug 13, 2020
1 parent 6dc932e commit 9f07c12
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
6 changes: 6 additions & 0 deletions Sources/WasmInterpreter/Heap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Foundation

public struct Heap {
public let pointer: UnsafeMutablePointer<UInt8>
public let size: Int
}
12 changes: 9 additions & 3 deletions Sources/WasmInterpreter/WasmInterpreter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,22 @@ public final class WasmInterpreter {
removeImportedFunctions(for: _importedFunctionContexts)
}

public func dataFromHeap(offset: Int, length: Int) throws -> Data {
public func heap() throws -> Heap {
let totalBytes = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
defer { totalBytes.deallocate() }

guard let bytesPointer = m3_GetMemory(_runtime, totalBytes, 0) else {
throw WasmInterpreterError.invalidMemoryAccess
}
guard offset + length < totalBytes.pointee else { throw WasmInterpreterError.invalidMemoryAccess }

return Data(bytes: bytesPointer.advanced(by: offset), count: length)
return Heap(pointer: bytesPointer, size: Int(totalBytes.pointee))
}

public func dataFromHeap(offset: Int, length: Int) throws -> Data {
let heap = try self.heap()
guard offset + length < heap.size else { throw WasmInterpreterError.invalidMemoryAccess }

return Data(bytes: heap.pointer.advanced(by: offset), count: length)
}

public func stringFromHeap(offset: Int, length: Int) throws -> String {
Expand Down

0 comments on commit 9f07c12

Please sign in to comment.