Skip to content

Commit

Permalink
chore(avm): add SET serialize comments and simplify signature (#4476)
Browse files Browse the repository at this point in the history
  • Loading branch information
fcarreiro authored Feb 7, 2024
1 parent 92d0aa4 commit 84dbdd3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
17 changes: 10 additions & 7 deletions yarn-project/simulator/src/avm/opcodes/instruction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assert } from 'console';
import { strict as assert } from 'assert';

import type { AvmContext } from '../avm_context.js';
import { BufferCursor } from '../serialization/buffer_cursor.js';
Expand Down Expand Up @@ -39,7 +39,7 @@ export abstract class Instruction {
* @returns The serialized instruction.
*/
public serialize(this: any): Buffer {
assert(this instanceof Instruction);
assert(!!this.constructor.wireFormat, 'wireFormat must be defined on the class');
return serialize(this.constructor.wireFormat, this);
}

Expand All @@ -50,12 +50,15 @@ export abstract class Instruction {
* @param buf Buffer to read from.
* @returns Constructed instance of Class.
*/
public static deserialize<T extends { new (...args: any[]): InstanceType<T>; wireFormat: OperandType[] }>(
this: T,
buf: BufferCursor | Buffer,
): InstanceType<T> {
public static deserialize(this: InstructionConstructor, buf: BufferCursor | Buffer): Instruction {
assert(!!this.wireFormat, 'wireFormat must be defined on the instruction class');
const res = deserialize(buf, this.wireFormat);
const args = res.slice(1) as ConstructorParameters<T>; // Remove opcode.
const args = res.slice(1); // Remove opcode.
return new this(...args);
}
}

type InstructionConstructor = {
new (...args: any[]): Instruction;
wireFormat?: OperandType[];
};
7 changes: 3 additions & 4 deletions yarn-project/simulator/src/avm/opcodes/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class Set extends Instruction {
super();
}

/** We need to use a custom serialize function because of the variable length of the value. */
public serialize(): Buffer {
const format: OperandType[] = [
...Set.wireFormatBeforeConst,
Expand All @@ -52,10 +53,8 @@ export class Set extends Instruction {
return serialize(format, this);
}

public static deserialize<T extends { new (...args: any[]): InstanceType<T> }>(
this: T,
buf: BufferCursor | Buffer,
): InstanceType<T> {
/** We need to use a custom deserialize function because of the variable length of the value. */
public static deserialize(this: typeof Set, buf: BufferCursor | Buffer): Set {
if (buf instanceof Buffer) {
buf = new BufferCursor(buf);
}
Expand Down

0 comments on commit 84dbdd3

Please sign in to comment.