-
Notifications
You must be signed in to change notification settings - Fork 3
/
vli.h
102 lines (86 loc) · 1.74 KB
/
vli.h
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
/*
Variable length integer Rice coding
Copyright 2021 Ahmet Inan <[email protected]>
*/
#pragma once
#include "bits.h"
struct vli_reader {
struct bits_reader *bits;
int order;
};
struct vli_writer {
struct bits_writer *bits;
int order;
};
struct vli_reader *vli_reader(struct bits_reader *bits)
{
struct vli_reader *vli = malloc(sizeof(struct vli_reader));
vli->bits = bits;
vli->order = 0;
return vli;
}
struct vli_writer *vli_writer(struct bits_writer *bits)
{
struct vli_writer *vli = malloc(sizeof(struct vli_writer));
vli->bits = bits;
vli->order = 0;
return vli;
}
void delete_vli_reader(struct vli_reader *vli)
{
free(vli);
}
void delete_vli_writer(struct vli_writer *vli)
{
free(vli);
}
int vli_put_bit(struct vli_writer *vli, int bit)
{
return put_bit(vli->bits, bit);
}
int vli_get_bit(struct vli_reader *vli)
{
return get_bit(vli->bits);
}
int vli_write_bits(struct vli_writer *vli, int b, int n)
{
return write_bits(vli->bits, b, n);
}
int vli_read_bits(struct vli_reader *vli, int *b, int n)
{
return read_bits(vli->bits, b, n);
}
int put_vli(struct vli_writer *vli, int val)
{
int ret;
while (val >= 1 << vli->order) {
if ((ret = put_bit(vli->bits, 0)))
return ret;
val -= 1 << vli->order;
vli->order += 1;
}
if ((ret = put_bit(vli->bits, 1)))
return ret;
if ((ret = write_bits(vli->bits, val, vli->order)))
return ret;
vli->order -= 2;
if (vli->order < 0)
vli->order = 0;
return 0;
}
int get_vli(struct vli_reader *vli)
{
int val, sum = 0, ret;
while ((ret = get_bit(vli->bits)) == 0) {
sum += 1 << vli->order;
vli->order += 1;
}
if (ret < 0)
return ret;
if ((ret = read_bits(vli->bits, &val, vli->order)))
return ret;
vli->order -= 2;
if (vli->order < 0)
vli->order = 0;
return val + sum;
}