Debian Codegraph @

terps/taylor/utility.c

raw symbols SCIP
1 //
2 // utility.c
3 // Part of TaylorMade, an interpreter for Adventure Soft UK games
4 //
5 // Created by Petter Sjölund on 2022-03-10.
6 //
7
8 #include <stdlib.h>
9
10 #include "glk.h"
11 #include "taylor.h"
12
13 #include "utility.h"
14
15 strid_t Transcript = NULL;
16
17 extern winid_t Bottom, Top;
18
19 void CleanupAndExit(void)
20 {
21 if (Transcript)
22 glk_stream_close(Transcript, NULL);
23 glk_exit();
24 }
25
26 void Fatal(const char *x)
27 {
28 if (Bottom)
29 Display(Bottom, "%s!\n", x);
30 fprintf(stderr, "%s!\n", x);
31 CleanupAndExit();
32 }
33
34 void *MemAlloc(size_t size)
35 {
36 void *t = (void *)malloc(size);
37 if (t == NULL)
38 Fatal("Out of memory");
39 return (t);
40 }
41
42 uint8_t *SeekToPos(uint8_t *buf, size_t offset)
43 {
44 if (offset > FileImageLen)
45 return 0;
46 return buf + offset;
47 }
48
49 void print_memory(int address, int length)
50 {
51 unsigned char *p = FileImage + address;
52 for (int i = address; i <= address + length; i += 16) {
53 fprintf(stderr, "\n%04X: ", i);
54 for (int j = 0; j < 16; j++) {
55 fprintf(stderr, "%02X ", *p++);
56 }
57 }
58 }
59
60 uint8_t *readFile(const char *name, size_t *size)
61 {
62 FILE *f = fopen(name, "r");
63 if (f == NULL)
64 return NULL;
65
66 fseek(f, 0, SEEK_END);
67 *size = ftell(f);
68 if (*size == -1)
69 return NULL;
70
71 uint8_t *data = MemAlloc(*size);
72
73 size_t origsize = *size;
74
75 fseek(f, 0, SEEK_SET);
76 *size = fread(data, 1, origsize, f);
77 if (*size != origsize) {
78 fprintf(stderr, "File read error on file %s! Wanted %zu bytes, got %zu\n", name, origsize, *size);
79 }
80
81 fclose(f);
82 return data;
83 }
84
85 int rotate_left_with_carry(uint8_t *byte, int last_carry)
86 {
87 int carry = ((*byte & 0x80) > 0);
88 *byte = *byte << 1;
89 if (last_carry)
90 *byte = *byte | 0x01;
91 return carry;
92 }
93
94 int rotate_right_with_carry(uint8_t *byte, int last_carry)
95 {
96 int carry = ((*byte & 0x01) > 0);
97 *byte = *byte >> 1;
98 if (last_carry)
99 *byte = *byte | 0x80;
100 return carry;
101 }