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
|
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static inline void check(bool cond, char const *msg) {
if (!cond) {
perror(msg);
exit(EXIT_FAILURE);
}
}
static inline void ensure(bool cond, char const *msg) {
if (!cond) {
fprintf(stderr, "error: %s.\n", msg);
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[argc + 1]) {
if (argc != 3) {
printf("Usage: %s <pico8.js> <data.pod>\n", argv[0]);
return EXIT_FAILURE;
}
FILE *f = fopen(argv[1], "r");
check(f, "fopen(input)");
// 1 MiB is quite large for the stack, we also assume that the data.pod
// lives entirely within the first part of the file. This is true for the
// current version, and we can change this if it ever changes.
static char buffer[1024 * 1024];
size_t n = fread(buffer, 1, sizeof(buffer) - 1, f);
check(n, "fread(input)");
buffer[n] = '\0';
uint8_t data[32 * 1024];
uint8_t *dataptr = data;
char *pos = buffer;
char *start = NULL, *end = NULL;
char stag[] = "fileData0.push.apply(fileData0,[", etag[] = "]);", sep[] = ",";
while ((start = strstr(pos, stag))) {
start += sizeof(stag) - 1;
ensure((end = strstr(start, etag)), "can't find end of file data");
pos = end + sizeof(etag) - 1;
*end = '\0';
for (char *s = strtok(start, sep); s; s = strtok(NULL, sep)) {
long b = strtol(s, &s, 10);
ensure(b >= 0 && b < 256 && *s == '\0', "failed to read byte");
ensure((size_t)(dataptr - data) < sizeof(data), "data pod too large");
*(dataptr++) = (uint8_t)b;
}
}
size_t datalen = (size_t)(dataptr - data);
ensure(datalen, "failed to decode data.pod");
FILE *o = fopen(argv[2], "wb");
check(o, "fopen(output)");
check(datalen == fwrite(data, 1, datalen, o), "fwrite(output)");
check(!fclose(o), "fclose(output)");
return EXIT_SUCCESS;
}
|