-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcomputer.go
91 lines (76 loc) · 1.63 KB
/
computer.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// Copyright (c) 2020-2023 Markku Rossi
//
// All rights reserved.
//
package circuit
import (
"fmt"
"math/big"
)
// Compute evaluates the circuit with the given input values.
func (c *Circuit) Compute(inputs []*big.Int) ([]*big.Int, error) {
// Flatten circuit arguments.
var args IO
for _, io := range c.Inputs {
if len(io.Compound) > 0 {
args = append(args, io.Compound...)
} else {
args = append(args, io)
}
}
if len(inputs) != len(args) {
return nil, fmt.Errorf("invalid inputs: got %d, expected %d",
len(inputs), len(args))
}
// Flatten inputs and arguments.
wires := make([]byte, c.NumWires)
var w int
for idx, io := range args {
for bit := 0; bit < int(io.Type.Bits); bit++ {
wires[w] = byte(inputs[idx].Bit(bit))
w++
}
}
// Evaluate circuit.
for _, gate := range c.Gates {
var result byte
switch gate.Op {
case XOR:
result = wires[gate.Input0] ^ wires[gate.Input1]
case XNOR:
if wires[gate.Input0]^wires[gate.Input1] == 0 {
result = 1
} else {
result = 0
}
case AND:
result = wires[gate.Input0] & wires[gate.Input1]
case OR:
result = wires[gate.Input0] | wires[gate.Input1]
case INV:
if wires[gate.Input0] == 0 {
result = 1
} else {
result = 0
}
default:
return nil, fmt.Errorf("invalid gate %s", gate.Op)
}
wires[gate.Output] = result
}
// Construct outputs
w = c.NumWires - c.Outputs.Size()
var result []*big.Int
for _, io := range c.Outputs {
r := new(big.Int)
for bit := 0; bit < int(io.Type.Bits); bit++ {
if wires[w] != 0 {
r.SetBit(r, bit, 1)
}
w++
}
result = append(result, r)
}
return result, nil
}