]> mj.ucw.cz Git - libucw.git/blob - ucw/ff-varint.h
New module: variable-length integer encoding
[libucw.git] / ucw / ff-varint.h
1 /*
2  *      UCW Library: Reading and writing Varints on Fastbuf Streams
3  *
4  *      (c) 2013 Tomas Valla <tom@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #ifndef _UCW_FF_VARINT_H
11 #define _UCW_FF_VARINT_H
12
13 #include <ucw/fastbuf.h>
14 #include <ucw/varint.h>
15
16 u64 bget_varint_slow(struct fastbuf *b, u64 repl);
17 void bput_varint_slow(struct fastbuf *b, u64 u);
18
19 /**
20  * Reads u64 encoded as varint from the fastbuf b.
21  * If the read is unsuccessful, returns repl.
22  **/
23 static inline u64 bget_varint_repl(struct fastbuf *b, u64 repl)
24 {
25         uns l;
26         if (bavailr(b) >= 1) {
27                 l = varint_len(*b->bptr);
28                 if (bavailr(b) >= l) {
29                         b->bptr += l;
30                         varint_get(b->bptr, &repl);
31                         return repl;
32                 }
33         }
34         return bget_varint_slow(b, repl);
35 }
36
37 /**
38  * Reads u64 encoded as varint from the fastbuf b.
39  * If the read is unsuccessful, returns ~0LLU.
40  **/
41 static inline int bget_varint(struct fastbuf *b)
42 {
43         return bget_varint_repl(b, ~0LLU);
44 }
45
46 /** Writes u64 u encoded as varint to the fastbuf b. **/
47 static inline void bput_varint(struct fastbuf *b, u64 u)
48 {
49         uns l = varint_space(u);
50         if (bavailw(b) >= l)
51                 b->bptr += varint_put(b->bptr, u);
52         else
53                 bput_varint_slow(b, u);
54 }
55
56 #endif