You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ops.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package intcode
  2. // OpcodeFunc is a function that describes an opcode implemented in the VM.
  3. type OpcodeFunc = func(vm *VirtualMachine)
  4. // AddOpcode takes the values specified by args 1 and 2, adds them together, and stores at the memory address given
  5. // by arg 3.
  6. func AddOpcode(vm *VirtualMachine) {
  7. vm.Memory[vm.Memory[vm.ip+3]] = vm.arg(0) + vm.arg(1)
  8. vm.ip += 4
  9. }
  10. // MulOpcode takes the values specified by args 1 and 2, multiplies them together, and stores at the memory address
  11. // given by arg 3.
  12. func MulOpcode(vm *VirtualMachine) {
  13. vm.Memory[vm.Memory[vm.ip+3]] = vm.arg(0) * vm.arg(1)
  14. vm.ip += 4
  15. }
  16. // ReadOpCode reads a value from the input stream and stores it at the memory address given by arg 1.
  17. func ReadOpCode(vm *VirtualMachine) {
  18. vm.Memory[vm.Memory[vm.ip+1]] = <-vm.Input
  19. vm.ip += 2
  20. }
  21. // WriteOpCode writes the value specified by the first argument to the output stream.
  22. func WriteOpCode(vm *VirtualMachine) {
  23. vm.Output <- vm.arg(0)
  24. vm.ip += 2
  25. }
  26. // JumpIfTrueOpCode checks if the first argument is not zero, and if so jumps to the second argument.
  27. func JumpIfTrueOpCode(vm *VirtualMachine) {
  28. if vm.arg(0) != 0 {
  29. vm.ip = vm.arg(1)
  30. } else {
  31. vm.ip += 3
  32. }
  33. }
  34. // JumpIfFalseOpCode checks if the first argument is zero, and if so jumps to the second argument.
  35. func JumpIfFalseOpCode(vm *VirtualMachine) {
  36. if vm.arg(0) == 0 {
  37. vm.ip = vm.arg(1)
  38. } else {
  39. vm.ip += 3
  40. }
  41. }
  42. // LessThanOpCode checks if the first argument is less than the second, and stores the result at the address given
  43. // by the third argument.
  44. func LessThanOpCode(vm *VirtualMachine) {
  45. if vm.arg(0) < vm.arg(1) {
  46. vm.Memory[vm.Memory[vm.ip+3]] = 1
  47. } else {
  48. vm.Memory[vm.Memory[vm.ip+3]] = 0
  49. }
  50. vm.ip += 4
  51. }
  52. // EqualsOpCode checks if the first argument is equal to the second, and stores the result at the address given
  53. // by the third argument.
  54. func EqualsOpCode(vm *VirtualMachine) {
  55. if vm.arg(0) == vm.arg(1) {
  56. vm.Memory[vm.Memory[vm.ip+3]] = 1
  57. } else {
  58. vm.Memory[vm.Memory[vm.ip+3]] = 0
  59. }
  60. vm.ip += 4
  61. }
  62. // HaltOpcode halts the VM and takes no arguments.
  63. func HaltOpcode(vm *VirtualMachine) {
  64. vm.Halted = true
  65. }