Created
December 12, 2016 16:50
-
-
Save KingOfBrian/c06ffbc6f4e553a548a9a9d5ec7d02b4 to your computer and use it in GitHub Desktop.
Help Computr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct Computr { | |
typealias Integer = Int | |
typealias Address = UnsafeMutablePointer<Integer> | |
var ic: Address = Address.allocate(capacity: 1) | |
var eax: Integer = 0 | |
var memory = Address.allocate(capacity: 10) | |
mutating func addr(at index: Int) -> Address { | |
return memory.advanced(by: index) | |
} | |
struct Instruction { | |
enum Operation: Integer { | |
case move, add | |
} | |
let op: Operation | |
let from: Address | |
let to: Address | |
func execute() { | |
switch op { | |
case .move: | |
to.pointee = from.pointee | |
case .add: | |
to.pointee = to.pointee + from.pointee | |
} | |
} | |
} | |
mutating func execute(count: Int) { | |
for _ in 0..<count { | |
ic.withMemoryRebound(to: Instruction.self, capacity: 1) { buff in | |
buff.pointee.execute() | |
} | |
ic = ic.advanced(by: MemoryLayout<Instruction>.size) | |
} | |
} | |
} | |
var computr = Computr() | |
var ONE: Int = 1 | |
var TEN: Int = 10 | |
var addInstructions: [Computr.Instruction] = [ | |
.init(op: .move, from: &TEN, to: &computr.eax), | |
.init(op: .add, from: &ONE, to: &computr.eax), | |
.init(op: .move, from: &computr.eax, to: computr.addr(at: 0)), | |
] | |
computr.ic = addInstructions.withUnsafeMutableBufferPointer { buffer in | |
let address = buffer.baseAddress?.withMemoryRebound(to: Computr.Integer.self, capacity: addInstructions.capacity) { $0 } | |
return address! | |
} | |
computr.execute(count: 2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment