-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblob.c
executable file
·115 lines (89 loc) · 2.18 KB
/
blob.c
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <assert.h>
#include <gc.h>
#include "error.h"
#include "util.h"
#include "type.h"
#include "number.h"
#include "symbol.h"
#include "blob.h"
int
is_blob(const TYPE* sexp)
{
return sexp->type == BLOB;
}
TYPE*
mk_blob(const TYPE* k)
{
TYPE* result = mloc(sizeof(TYPE));
if (result == NULL)
{
fprintf(stderr, "MAKE_BLOB: could not allocate memory for type");
exit(1);
}
result->type = BLOB;
result->d.bl = mloc(sizeof(BLOB_DATA));
if (result->d.bl == NULL)
{
fprintf(stderr, "MAKE_BLOB: could not allocate memory for data");
exit(1);
}
unsigned int length = as_integer(k);
result->d.bl->data = mloc(sizeof(unsigned char) * length);
if (result->d.bl->data == NULL)
{
fprintf(stderr, "MAKE_BLOB: could not allocate memory for array");
exit(1);
}
result->d.bl->length = length;
return result;
}
TYPE*
blob_length(const TYPE* blob)
{
return mk_number_from_int(blob->d.bl->length);
}
TYPE*
blob_u8_ref(const TYPE* blob, const TYPE* k)
{
unsigned int index = as_integer(k);
if (index >= blob->d.bl->length)
{
throw_error(CONSTRAINT_ERROR, "BLOB_U8_REF: k is out of range");
}
unsigned char* a = blob->d.bl->data;
return mk_number_from_int(a[index]);
}
void
blob_u8_set(const TYPE* blob, const TYPE* k, const TYPE* u8)
{
unsigned int index = as_integer(k);
if (index >= blob->d.bl->length)
{
throw_error(CONSTRAINT_ERROR, "BLOB_U8_REF: k is out of range");
}
blob->d.bl->data[index] = u8->d.i;
}
void
display_blob(const TYPE* blob, FILE* file)
{
assert(is_blob(blob));
unsigned int length = blob->d.bl->length;
unsigned char* a = blob->d.bl->data;
unsigned int i;
fprintf(file, "<");
for(i = 0; i < length; i++)
{
if (i == (length -1))
{
fprintf(file, "%xd", a[i]);
}
else
{
fprintf(file, "%xd ", a[i]);
}
}
fprintf(file, ">");
}