-
Notifications
You must be signed in to change notification settings - Fork 37
/
adc.c
114 lines (106 loc) · 2.31 KB
/
adc.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
#include "adc.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int adc_decompress(int in_size, unsigned char *input, int avail_size, unsigned char *output, int *bytes_written)
{
if (in_size == 0)
return 0;
bool output_full = false;
unsigned char *inp = input;
unsigned char *outp = output;
int chunk_type;
int chunk_size;
int offset;
int i;
while (inp - input < in_size) {
chunk_type = adc_chunk_type(*inp);
switch (chunk_type) {
case ADC_PLAIN:
chunk_size = adc_chunk_size(*inp);
if (outp + chunk_size - output > avail_size) {
output_full = true;
break;
}
memcpy(outp, inp + 1, chunk_size);
inp += chunk_size + 1;
outp += chunk_size;
break;
case ADC_2BYTE:
chunk_size = adc_chunk_size(*inp);
offset = adc_chunk_offset(inp);
if (outp + chunk_size - output > avail_size) {
output_full = true;
break;
}
if (offset == 0) {
memset(outp, *(outp - offset - 1), chunk_size);
outp += chunk_size;
inp += 2;
} else {
for (i = 0; i < chunk_size; i++) {
memcpy(outp, outp - offset - 1, 1);
outp++;
}
inp += 2;
}
break;
case ADC_3BYTE:
chunk_size = adc_chunk_size(*inp);
offset = adc_chunk_offset(inp);
if (outp + chunk_size - output > avail_size) {
output_full = true;
break;
}
if (offset == 0) {
memset(outp, *(outp - offset - 1), chunk_size);
outp += chunk_size;
inp += 3;
} else {
for (i = 0; i < chunk_size; i++) {
memcpy(outp, outp - offset - 1, 1);
outp++;
}
inp += 3;
}
break;
}
if (output_full)
break;
}
*bytes_written = outp - output;
return inp - input;
}
int adc_chunk_type(char _byte)
{
if (_byte & 0x80)
return ADC_PLAIN;
if (_byte & 0x40)
return ADC_3BYTE;
return ADC_2BYTE;
}
int adc_chunk_size(char _byte)
{
switch (adc_chunk_type(_byte)) {
case ADC_PLAIN:
return (_byte & 0x7F) + 1;
case ADC_2BYTE:
return ((_byte & 0x3F) >> 2) + 3;
case ADC_3BYTE:
return (_byte & 0x3F) + 4;
}
return -1;
}
int adc_chunk_offset(unsigned char *chunk_start)
{
unsigned char *c = chunk_start;
switch (adc_chunk_type(*c)) {
case ADC_PLAIN:
return 0;
case ADC_2BYTE:
return ((((unsigned char)*c & 0x03)) << 8) + (unsigned char)*(c + 1);
case ADC_3BYTE:
return (((unsigned char)*(c + 1)) << 8) + (unsigned char)*(c + 2);
}
return -1;
}