aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2023-10-21 23:23:37 +0100
committerAryadev Chavali <aryadev@aryadevchavali.com>2023-10-21 23:23:37 +0100
commit44a9a3ca464f0bf24b0da2c0a6f106678dc67d52 (patch)
treed11b0c92f71bda588dc1c5277b7286f8ef0922db
parent903ae3ab04eda63df286bbb32fe83603ffbbd0e0 (diff)
downloadovm-44a9a3ca464f0bf24b0da2c0a6f106678dc67d52.tar.gz
ovm-44a9a3ca464f0bf24b0da2c0a6f106678dc67d52.tar.bz2
ovm-44a9a3ca464f0bf24b0da2c0a6f106678dc67d52.zip
Helper functions for read/write instructions from darr or FILE*
-rw-r--r--src/inst.c37
-rw-r--r--src/inst.h5
2 files changed, 42 insertions, 0 deletions
diff --git a/src/inst.c b/src/inst.c
index d7edd94..a6347c0 100644
--- a/src/inst.c
+++ b/src/inst.c
@@ -168,6 +168,12 @@ void inst_write_bytecode(inst_t inst, darr_t *darr)
}
}
+void insts_write_bytecode(inst_t *insts, size_t size, darr_t *darr)
+{
+ for (size_t i = 0; i < size; ++i)
+ inst_write_bytecode(insts[i], darr);
+}
+
data_t read_type_from_darr(darr_t *darr, data_type_t type)
{
switch (type)
@@ -225,3 +231,34 @@ inst_t inst_read_bytecode(darr_t *darr)
return inst;
}
+
+inst_t *insts_read_bytecode(darr_t *bytes, size_t *ret_size)
+{
+ *ret_size = 0;
+ darr_t instructions = {0};
+ darr_init(&instructions, 0);
+ while (bytes->used < bytes->available)
+ {
+ inst_t instruction = inst_read_bytecode(bytes);
+ darr_append_bytes(&instructions, (byte *)&instruction, sizeof(instruction));
+ }
+ *ret_size = instructions.used / sizeof(inst_t);
+ return (inst_t *)instructions.data;
+}
+
+void insts_write_bytecode_file(inst_t *instructions, size_t size, FILE *fp)
+{
+ darr_t darr = {0};
+ darr_init(&darr, 0);
+ insts_write_bytecode(instructions, size, &darr);
+ darr_write_file(&darr, fp);
+ free(darr.data);
+}
+
+inst_t *insts_read_bytecode_file(FILE *fp, size_t *ret)
+{
+ darr_t darr = darr_read_file(fp);
+ inst_t *instructions = insts_read_bytecode(&darr, ret);
+ free(darr.data);
+ return instructions;
+}
diff --git a/src/inst.h b/src/inst.h
index f5ab4ae..f72470c 100644
--- a/src/inst.h
+++ b/src/inst.h
@@ -57,10 +57,15 @@ void inst_print(inst_t, FILE *);
size_t inst_bytecode_size(inst_t);
void inst_write_bytecode(inst_t, darr_t *);
+void insts_write_bytecode(inst_t *, size_t, darr_t *);
// Here the dynamic array is a preloaded buffer of bytes, where
// darr.available is the number of overall bytes and used is the
// cursor (where we are in the buffer).
inst_t inst_read_bytecode(darr_t *);
+inst_t *insts_read_bytecode(darr_t *, size_t *);
+
+void insts_write_bytecode_file(inst_t *, size_t, FILE *);
+inst_t *insts_read_bytecode_file(FILE *, size_t *);
#define INST_BPUSH(BYTE) \
((inst_t){.opcode = OP_PUSH_BYTE, .operand = DBYTE(BYTE)})