-
Notifications
You must be signed in to change notification settings - Fork 2
/
bytebuffer.c
86 lines (70 loc) · 2.23 KB
/
bytebuffer.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
#include <stdlib.h>
#include "bytebuffer.h"
struct bytebuffer* new_bytebuffer() {
struct bytebuffer* b = (struct bytebuffer*)malloc(sizeof(struct bytebuffer));
if (b == NULL) {
return NULL;
}
b->bytes = (u_int8_t*)malloc(32);
if (b->bytes == NULL) {
free(b);
return NULL;
}
b->capacity = 32;
b->n_bytes = 0;
return b;
}
void free_bytebuffer(struct bytebuffer* buffer) {
free(buffer->bytes);
free(buffer);
}
int write_byte(struct bytebuffer* buffer, uint8_t value) {
if (buffer->n_bytes == buffer->capacity) {
u_int8_t* tmp = (u_int8_t*)realloc(buffer->bytes, 2 * buffer->capacity);
if (tmp == NULL) {
return MEMORY_ERROR;
}
buffer->bytes = tmp;
buffer->capacity = 2 * buffer->capacity;
}
buffer->bytes[buffer->n_bytes++] = value;
return SUCCESS;
}
int write_unicode_as_utf8(struct bytebuffer* buffer, u_int32_t value) {
if (value <= 0x7F) {
return write_byte(buffer, value);
}
if (value <= 0x7FF) {
u_int8_t a = (128 + 64) | (value >> 6);
u_int8_t b = 128 | (value & 63);
return write_byte(buffer, a) && write_byte(buffer, b);
}
if (value <= 0xFFFF) {
u_int8_t a = (128 + 64 + 32) | (value >> 12);
u_int8_t b = 128 | ((value >> 6) & 63);
u_int8_t c = 128 | (value & 63);
return write_byte(buffer, a) && write_byte(buffer, b) && write_byte(buffer, c);
}
if (value <= 0x10FFFF) {
u_int8_t a = (128 + 64 + 32 + 16) | (value >> 18);
u_int8_t b = 128 | ((value >> 12) & 63);
u_int8_t c = 128 | ((value >> 6) & 63);
u_int8_t d = 128 | (value & 63);
return write_byte(buffer, a) && write_byte(buffer, b) && write_byte(buffer, c) && write_byte(buffer, d);
}
return DECODING_ERROR;
}
int contains_text_data(struct bytebuffer* buffer) {
// The buffer may be padded at the end with multiple \0
int len = buffer->n_bytes - 1;
while (len >= 0 && buffer->bytes[len] == '\0') {
len--;
}
for (int i = 0 ; i < len ; i++) {
u_int8_t c = buffer->bytes[i];
if (c <= 0x1F && c != '\t' && c != '\r' && c != '\n') {
return 0;
}
}
return 1;
}