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
|
#pragma once
#include "coding/bit_streams.hpp"
#include "base/assert.hpp"
#include "base/bits.hpp"
#include "std/cstdint.hpp"
namespace coding
{
class GammaCoder
{
public:
template <typename TWriter>
static bool Encode(BitWriter<TWriter> & writer, uint64_t value)
{
if (value == 0)
return false;
uint8_t const n = bits::FloorLog(value);
ASSERT_LESS_OR_EQUAL(n, 63, ());
uint64_t const msb = static_cast<uint64_t>(1) << n;
writer.WriteAtMost64Bits(msb, n + 1);
writer.WriteAtMost64Bits(value, n);
return true;
}
template <typename TReader>
static uint64_t Decode(BitReader<TReader> & reader)
{
uint8_t n = 0;
while (reader.Read(1) == 0)
++n;
ASSERT_LESS_OR_EQUAL(n, 63, ());
uint64_t const msb = static_cast<uint64_t>(1) << n;
return msb | reader.ReadAtMost64Bits(n);
}
};
class DeltaCoder
{
public:
template <typename TWriter>
static bool Encode(BitWriter<TWriter> & writer, uint64_t value)
{
if (value == 0)
return false;
uint8_t const n = bits::FloorLog(value);
ASSERT_LESS_OR_EQUAL(n, 63, ());
if (!GammaCoder::Encode(writer, n + 1))
return false;
writer.WriteAtMost64Bits(value, n);
return true;
}
template <typename TReader>
static uint64_t Decode(BitReader<TReader> & reader)
{
uint8_t n = GammaCoder::Decode(reader);
ASSERT_GREATER(n, 0, ());
--n;
ASSERT_LESS_OR_EQUAL(n, 63, ());
uint64_t const msb = static_cast<uint64_t>(1) << n;
return msb | reader.ReadAtMost64Bits(n);
}
};
} // namespace coding
|