aboutsummaryrefslogtreecommitdiff
path: root/memory.c
blob: c32f2aba5c6df310c8d8c52e13d2cae343921fc5 (plain)
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
// synacor challenge ([email protected])
#include "memory.h"

void mem_init(Memory *m) {
  m->size = INT16_MAX;
  m->mem = malloc(sizeof(u16) * m->size);
  memset(m->mem, 0, sizeof(u16) * m->size);
}

void mem_free(Memory *m) {
  free(m->mem);
  m->size = 0;
}

void mem_set(Memory *m, u16 addr, u16 value) {
  addr = addr * 2;
  m->mem[addr] = value;
  m->mem[addr + 1] = value >> 8;
}

u16 mem_get(Memory *m, u16 addr) {
  u16 pair;
  addr = addr * 2;
  get_next_pair(m->mem + addr, &pair);
  return pair;
}

u8 *get_next_pair(u8 *buffer, u16 *pair) {
  *pair = (*(buffer + 1) << 8) + *buffer;
  return buffer + 2;
}