Skip to content

Commit

Permalink
Feature: fast biased to 2's complement (#30)
Browse files Browse the repository at this point in the history
Feature: converting biased representation into 2's complement in one instruction
  • Loading branch information
ElijahVlasov authored Aug 29, 2023
1 parent b6cf751 commit f0a851d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
17 changes: 9 additions & 8 deletions pkg/vm/instruction.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ func DecodeInstruction(rawInstruction *f.Element) (*Instruction, error) {
instruction := new(Instruction)

// Add unsigned offsets as signed ones
instruction.OffDest = int16(int(off0Enc) - (1 << (offsetBits - 1)))
instruction.OffOp0 = int16(int(off1Enc) - (1 << (offsetBits - 1)))
instruction.OffOp1 = int16(int(off2Enc) - (1 << (offsetBits - 1)))
instruction.OffDest = off0Enc
instruction.OffOp0 = off1Enc
instruction.OffOp1 = off2Enc

err := decodeInstructionFlags(instruction, flags)
if err != nil {
Expand All @@ -132,14 +132,15 @@ func DecodeInstruction(rawInstruction *f.Element) (*Instruction, error) {
// | off2 |
// | flags |
func decodeInstructionValues(encoding uint64) (
off0Enc uint16, off1Enc uint16, off2Enc uint16, flags uint16,
off0Enc int16, off1Enc int16, off2Enc int16, flags uint16,
) {
encodingWith2sComplement := encoding ^ 0x0000800080008000
// first, second and third 16 bits of the instruction encoding respectively
off0Enc = uint16(encoding & (1<<offsetBits - 1))
off1Enc = uint16((encoding >> offsetBits) & (1<<offsetBits - 1))
off2Enc = uint16((encoding >> (2 * offsetBits)) & (1<<offsetBits - 1))
off0Enc = int16(encodingWith2sComplement & (1<<offsetBits - 1))
off1Enc = int16((encodingWith2sComplement >> offsetBits) & (1<<offsetBits - 1))
off2Enc = int16((encodingWith2sComplement >> (2 * offsetBits)) & (1<<offsetBits - 1))
// bits 48..63
flags = uint16(encoding >> (3 * offsetBits))
flags = uint16(encodingWith2sComplement >> (3 * offsetBits))
return
}

Expand Down
9 changes: 5 additions & 4 deletions pkg/vm/instruction_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package vm

import (
"github.com/stretchr/testify/require"
"testing"

"github.com/stretchr/testify/require"

f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp"
"github.com/stretchr/testify/assert"
)
Expand All @@ -12,9 +13,9 @@ func TestDecodeInstructionValues(t *testing.T) {
offDest, offOp0, offOp1, flags := decodeInstructionValues(
new(f.Element).SetBytes([]byte{0x48, 0x06, 0x80, 0x01, 0x7f, 0xff, 0x80, 0x10}).Uint64(),
)
assert.Equal(t, uint16(0x8010), offDest)
assert.Equal(t, uint16(0x7fff), offOp0)
assert.Equal(t, uint16(0x8001), offOp1)
assert.Equal(t, int16(16), offDest)
assert.Equal(t, int16(-1), offOp0)
assert.Equal(t, int16(1), offOp1)
assert.Equal(t, uint16(0x4806), flags)
}

Expand Down

0 comments on commit f0a851d

Please sign in to comment.