]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/varint.c
Update bcachefs sources to 1d669389f7 bcachefs: use a radix tree for inum bitmap...
[bcachefs-tools-debian] / libbcachefs / varint.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/bitops.h>
4 #include <asm/unaligned.h>
5
6 #include "varint.h"
7
8 int bch2_varint_encode(u8 *out, u64 v)
9 {
10         unsigned bits = fls64(v|1);
11         unsigned bytes = DIV_ROUND_UP(bits, 7);
12
13         if (likely(bytes < 9)) {
14                 v <<= bytes;
15                 v |= ~(~0 << (bytes - 1));
16         } else {
17                 *out++ = 255;
18                 bytes = 9;
19         }
20
21         put_unaligned_le64(v, out);
22         return bytes;
23 }
24
25 int bch2_varint_decode(const u8 *in, const u8 *end, u64 *out)
26 {
27         u64 v = get_unaligned_le64(in);
28         unsigned bytes = ffz(v & 255) + 1;
29
30         if (unlikely(in + bytes > end))
31                 return -1;
32
33         if (likely(bytes < 9)) {
34                 v >>= bytes;
35                 v &= ~(~0ULL << (7 * bytes));
36         } else {
37                 v = get_unaligned_le64(++in);
38         }
39
40         *out = v;
41         return bytes;
42 }