Coverage Report

Created: 2026-10-16 22:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/bit_stream_utils.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/bit-stream-utils.h
19
// and modified by Doris
20
21
#pragma once
22
23
#include "util/bit_packing.h"
24
#include "util/bit_util.h"
25
#include "util/faststring.h"
26
27
using doris::BitUtil;
28
namespace doris {
29
30
// Utility class to write bit/byte streams.  This class can write data to either be
31
// bit packed or byte aligned (and a single stream that has a mix of both).
32
class BitWriter {
33
public:
34
    // buffer: buffer to write bits to.
35
11.0M
    explicit BitWriter(faststring* buffer) : buffer_(buffer) { Clear(); }
36
37
22.0M
    void Clear() {
38
22.0M
        buffered_values_ = 0;
39
22.0M
        byte_offset_ = 0;
40
22.0M
        bit_offset_ = 0;
41
22.0M
        buffer_->clear();
42
22.0M
    }
43
44
    // Returns a pointer to the underlying buffer
45
8.92k
    faststring* buffer() const { return buffer_; }
46
47
    // The number of current bytes written, including the current byte (i.e. may include a
48
    // fraction of a byte). Includes buffered values.
49
11.0M
    int bytes_written() const { return byte_offset_ + BitUtil::Ceil(bit_offset_, 8); }
50
51
    // Writes a value to buffered_values_, flushing to buffer_ if necessary.  This is bit
52
    // packed.
53
    void PutValue(uint64_t v, int num_bits);
54
55
    // Writes v to the next aligned byte using num_bits. If T is larger than num_bits, the
56
    // extra high-order bits will be ignored.
57
    template <typename T>
58
    void PutAligned(T v, int num_bits);
59
60
    // Write a Vlq encoded int to the buffer. The value is written byte aligned.
61
    // For more details on vlq: en.wikipedia.org/wiki/Variable-length_quantity
62
    // Takes an unsigned value on purpose: the encoding shifts `v` right until it
63
    // is exhausted, which only terminates for a logical shift.
64
    void PutVlqInt(uint32_t v);
65
66
    // Get the index to the next aligned byte and advance the underlying buffer by num_bytes.
67
8.92k
    size_t GetByteIndexAndAdvance(int num_bytes) {
68
8.92k
        uint8_t* ptr = GetNextBytePtr(num_bytes);
69
8.92k
        return ptr - buffer_->data();
70
8.92k
    }
71
72
    // Get a pointer to the next aligned byte and advance the underlying buffer by num_bytes.
73
    uint8_t* GetNextBytePtr(int num_bytes);
74
75
    // Flushes all buffered values to the buffer. Call this when done writing to the buffer.
76
    // If 'align' is true, buffered_values_ is reset and any future writes will be written
77
    // to the next byte boundary.
78
    void Flush(bool align = false);
79
80
private:
81
    // Bit-packed values are initially written to this variable before being memcpy'd to
82
    // buffer_. This is faster than writing values byte by byte directly to buffer_.
83
    uint64_t buffered_values_;
84
85
    faststring* buffer_ = nullptr;
86
    int byte_offset_; // Offset in buffer_
87
    int bit_offset_;  // Offset in buffered_values_
88
};
89
90
// Utility class to read bit/byte stream.  This class can read bits or bytes
91
// that are either byte aligned or not.  It also has utilities to read multiple
92
// bytes in one read (e.g. encoded int).
93
class BitReader {
94
public:
95
    // 'buffer' is the buffer to read from.  The buffer's length is 'buffer_len'.
96
    BitReader(const uint8_t* buffer, int buffer_len);
97
98
35.2k
    BitReader() : buffer_(nullptr), max_bytes_(0) {}
99
100
    // Gets the next value from the buffer.  Returns true if 'v' could be read or false if
101
    // there are not enough bytes left. num_bits must be <= 32.
102
    template <typename T>
103
    bool GetValue(int num_bits, T* v);
104
105
    // Reads a 'num_bytes'-sized value from the buffer and stores it in 'v'. T needs to be a
106
    // little-endian native type and big enough to store 'num_bytes'. The value is assumed
107
    // to be byte-aligned so the stream will be advanced to the start of the next byte
108
    // before 'v' is read. Returns false if there are not enough bytes left.
109
    template <typename T>
110
    bool GetAligned(int num_bytes, T* v);
111
112
    // Reads a vlq encoded int from the stream.  The encoded int must start at the
113
    // beginning of a byte. Return false if there were not enough bytes in the buffer.
114
    bool GetVlqInt(uint32_t* v);
115
    // Reads a zigzag encoded int `into` v.
116
    bool GetZigZagVlqInt(int32_t* v);
117
118
    // Reads a vlq encoded int from the stream.  The encoded int must start at the
119
    // beginning of a byte. Return false if there were not enough bytes in the buffer.
120
    bool GetVlqInt(uint64_t* v);
121
    // Reads a zigzag encoded int `into` v.
122
    bool GetZigZagVlqInt(int64_t* v);
123
124
    // Returns the number of bytes left in the stream, not including the current byte (i.e.,
125
    // there may be an additional fraction of a byte).
126
3.43k
    int bytes_left() { return max_bytes_ - (byte_offset_ + BitUtil::Ceil(bit_offset_, 8)); }
127
128
    // Current position in the stream, by bit.
129
3
    int position() const { return byte_offset_ * 8 + bit_offset_; }
130
131
    // Rewind the stream by 'num_bits' bits
132
    void Rewind(int num_bits);
133
134
    // Advance the stream by 'num_bits' bits
135
    bool Advance(int64_t num_bits);
136
137
    // Seek to a specific bit in the buffer
138
    void SeekToBit(unsigned int stream_position);
139
140
    // Maximum byte length of a vlq encoded int
141
    static const int MAX_VLQ_BYTE_LEN = 5;
142
143
    // Maximum byte length of a vlq encoded int64
144
    static const int MAX_VLQ_BYTE_LEN_FOR_INT64 = 10;
145
146
873k
    bool is_initialized() const { return buffer_ != nullptr; }
147
148
0
    const uint8_t* buffer() const { return buffer_; }
149
150
0
    int max_bytes() const { return max_bytes_; }
151
152
private:
153
    // Used by SeekToBit() and GetValue() to fetch the
154
    // the next word into buffer_.
155
    void BufferValues();
156
157
    const uint8_t* buffer_ = nullptr;
158
    int max_bytes_;
159
160
    // Bytes are memcpy'd from buffer_ and values are read from this variable. This is
161
    // faster than reading values byte by byte directly from buffer_.
162
    uint64_t buffered_values_;
163
164
    int byte_offset_; // Offset in buffer_
165
    int bit_offset_;  // Offset in buffered_values_
166
};
167
168
/// Utility class to read bit/byte stream. This class can read bits or bytes that are
169
/// either byte aligned or not. It also has utilities to read multiple bytes in one
170
/// read (e.g. encoded int). Exposes a batch-oriented interface to allow efficient
171
/// processing of multiple values at a time.
172
class BatchedBitReader {
173
public:
174
    /// 'buffer' is the buffer to read from.  The buffer's length is 'buffer_len'.
175
    /// Does not take ownership of the buffer.
176
0
    BatchedBitReader(const uint8_t* buffer, int64_t buffer_len) { Reset(buffer, buffer_len); }
177
178
3.59k
    BatchedBitReader() {}
179
180
    // The implicit copy constructor is left defined. If a BatchedBitReader is copied, the
181
    // two copies do not share any state. Invoking functions on either copy continues
182
    // reading from the current read position without modifying the state of the other
183
    // copy.
184
185
    /// Resets the read to start reading from the start of 'buffer'. The buffer's
186
    /// length is 'buffer_len'. Does not take ownership of the buffer.
187
1.39k
    void Reset(const uint8_t* buffer, int64_t buffer_len) {
188
1.39k
        DCHECK(buffer != nullptr);
189
1.39k
        DCHECK_GE(buffer_len, 0);
190
1.39k
        buffer_pos_ = buffer;
191
1.39k
        buffer_end_ = buffer + buffer_len;
192
1.39k
    }
193
194
    /// Gets up to 'num_values' bit-packed values, starting from the current byte in the
195
    /// buffer and advance the read position. 'bit_width' must be <= 64.
196
    /// If 'bit_width' * 'num_values' is not a multiple of 8, the trailing bytes are
197
    /// skipped and the next UnpackBatch() call will start reading from the next byte.
198
    ///
199
    /// If the caller does not want to drop trailing bits, 'num_values' must be exactly the
200
    /// total number of values the caller wants to read from a run of bit-packed values, or
201
    /// 'bit_width' * 'num_values' must be a multiple of 8. This condition is always
202
    /// satisfied if 'num_values' is a multiple of 32.
203
    ///
204
    /// The output type 'T' must be an unsigned integer.
205
    ///
206
    /// Returns the number of values read.
207
    template <typename T>
208
    int UnpackBatch(int bit_width, int num_values, T* v);
209
210
    /// Skip 'num_values_to_skip' bit-packed values.
211
    /// 'num_values_to_skip * bit_width' is either divisible by 8, or
212
    /// 'num_values_to_skip' equals to the count of the remaining bit-packed values.
213
    bool SkipBatch(int bit_width, int num_values_to_skip);
214
215
    /// Unpack bit-packed values in the same way as UnpackBatch() and decode them using the
216
    /// dictionary 'dict' with 'dict_len' entries. Return -1 if a decoding error is
217
    /// encountered, i.e. if the bit-packed values are not valid indices in 'dict'.
218
    /// Otherwise returns the number of values decoded. The values are written to 'v' with
219
    /// a stride of 'stride' bytes.
220
    template <typename T>
221
    int UnpackAndDecodeBatch(int bit_width, T* dict, int64_t dict_len, int num_values, T* v,
222
                             int64_t stride);
223
224
    /// Reads an unpacked 'num_bytes'-sized value from the buffer and stores it in 'v'. T
225
    /// needs to be a little-endian native type and big enough to store 'num_bytes'.
226
    /// Returns false if there are not enough bytes left.
227
    template <typename T>
228
    bool GetBytes(int num_bytes, T* v);
229
230
    /// Read an unsigned ULEB-128 encoded int from the stream. The encoded int must start
231
    /// at the beginning of a byte. Return false if there were not enough bytes in the
232
    /// buffer or the int is invalid. For more details on ULEB-128:
233
    /// https://en.wikipedia.org/wiki/LEB128
234
    /// UINT_T must be an unsigned integer type.
235
    template <typename UINT_T>
236
    bool GetUleb128(UINT_T* v);
237
238
    /// Returns the number of bytes left in the stream.
239
863
    int bytes_left() { return static_cast<int>(buffer_end_ - buffer_pos_); }
240
241
    /// Maximum byte length of a vlq encoded integer of type T.
242
    template <typename T>
243
1.55k
    static constexpr int max_vlq_byte_len() {
244
1.55k
        return BitUtil::Ceil(sizeof(T) * 8, 7);
245
1.55k
    }
246
247
    /// Maximum supported bitwidth for reader.
248
    static const int MAX_BITWIDTH = BitPacking::MAX_BITWIDTH;
249
250
private:
251
    /// Current read position in the buffer.
252
    const uint8_t* buffer_pos_ = nullptr;
253
254
    /// Pointer to the byte after the end of the buffer.
255
    const uint8_t* buffer_end_ = nullptr;
256
};
257
} // namespace doris