forked from jacquesf/COBS-Consistent-Overhead-Byte-Stuffing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cobs_jf.c
87 lines (77 loc) · 2.18 KB
/
cobs_jf.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
/* Copyright 2011, Jacques Fortier. All rights reserved.
*
* Redistribution and use in source and binary forms are permitted, with or without modification.
*/
#include <stdint.h>
#include <stddef.h>
/* Stuffs "length" bytes of data at the location pointed to by
* "input", writing the output to the location pointed to by
* "output". Returns the number of bytes written to "output".
*
* Remove the "restrict" qualifiers if compiling with a
* pre-C99 C dialect.
*/
size_t cobs_encode(const uint8_t * restrict input, size_t length, uint8_t * restrict output)
{
size_t read_index = 0;
size_t write_index = 1;
size_t code_index = 0;
uint8_t code = 1;
while(read_index < length)
{
if(input[read_index] == 0)
{
output[code_index] = code;
code = 1;
code_index = write_index++;
read_index++;
}
else
{
output[write_index++] = input[read_index++];
code++;
if(code == 0xFF)
{
output[code_index] = code;
code = 1;
code_index = write_index++;
}
}
}
output[code_index] = code;
return write_index;
}
/* Unstuffs "length" bytes of data at the location pointed to by
* "input", writing the output * to the location pointed to by
* "output". Returns the number of bytes written to "output" if
* "input" was successfully unstuffed, and 0 if there was an
* error unstuffing "input".
*
* Remove the "restrict" qualifiers if compiling with a
* pre-C99 C dialect.
*/
size_t cobs_decode(const uint8_t * restrict input, size_t length, uint8_t * restrict output)
{
size_t read_index = 0;
size_t write_index = 0;
uint8_t code;
uint8_t i;
while(read_index < length)
{
code = input[read_index];
if(read_index + code > length && code != 1)
{
return 0;
}
read_index++;
for(i = 1; i < code; i++)
{
output[write_index++] = input[read_index++];
}
if(code != 0xFF && read_index != length)
{
output[write_index++] = '\0';
}
}
return write_index;
}