aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/compproto/bit.h
blob: 1800e255fc90767ed9ca9d64aa9db46c7ab74d89 (plain) (blame)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#pragma once

#include <util/generic/array_ref.h> 
#include <util/generic/vector.h>
#include <util/stream/output.h>
#include <util/stream/input.h>

#include "huff.h"
#include "compressor.h"
#include "metainfo.h"

namespace NCompProto {
    struct TBitBuffer {
        TVector<ui8> Out;
        ui64 Position;
        ui64 Size;
        ui8 Counter;
        TBitBuffer() {
            Clear();
        }

        static ui64 Read(const ui8* out, ui64 position, size_t size) {
            const ui8* dst = out + (size_t(position >> 3));
            ui64 outCode = *reinterpret_cast<const ui64*>(dst);
            ui8 shift = position & 7;
            return ((1ULL << size) - 1) & (outCode >> shift);
        }

        ui64 Read(ui64 position, size_t size) {
            return Read(&Out[0], position, size);
        }

        void Code(ui64 value, size_t size) {
            if (++Counter == 0) {
                Junk(257 * 64);
            }
            Position = Code(value, size, Position);
        }
        ui64 Code(ui64 value, size_t size, ui64 position) {
            ui8* dst = &Out[size_t(position >> 3)];
            ui64& outCode = *(ui64*)dst;
            ui8 shift = position & 7;
            ui64 mask = ((1ULL << size) - 1) << shift;
            outCode = ((value << shift) & mask) | (outCode & ~mask);
            return position + size;
        }
        void Junk(size_t junk = 1024) {
            size_t need = size_t(Position >> 3);
            if (Out.size() * 8 < Position + junk) {
                Out.resize(((need + junk) * 3) / 2);
                Size = Out.size();
            }
        }
        void Insert(ui64 value, ui64 position, size_t size) {
            ui64 newVal = Read(position, 56);
            position = Code(value, size, position);
            value = newVal;

            while (position < Position + 64) {
                newVal = Read(position + 56 - size, 56);
                position = Code(value, 56, position);
                value = newVal;
            }

            Position += size;
        }

        size_t ByteLength() const {
            return (Position + 7) / 8;
        }

        void ResetPosition() {
            Position = 0;
            Size = 0;
        }

        void Clear() {
            Counter = 0;
            Position = 0;
            Size = 0;
            Out.clear();
            Junk();
        }

        TArrayRef<const char> AsDataRegion() const { 
            return TArrayRef<const char>(reinterpret_cast<const char*>(Out.data()), ByteLength()); 
        }
    };

    struct THuff {
        TCoder Coder;
        ui64 Position;
        THuff() {
            Position = (ui64)(-1);
        }
        void Load(IInputStream& stream) {
            TString name;
            Coder.InitDefault();
            Coder.Entries.clear();
            while (1) {
                stream >> name;
                if (name == "end")
                    return;
                else if (name == "entry") {
                    TCoderEntry entry;
                    ui32 value;
                    stream >> value;
                    entry.MinValue = value;
                    stream >> value;
                    entry.Prefix = value;
                    stream >> value;
                    entry.PrefixBits = value;
                    stream >> value;
                    entry.AllBits = value;
                    Coder.Entries.push_back(entry);
                }
            }
        }

        void Save(IOutputStream& stream, TString offset) {
            TString step = "    ";
            for (size_t i = 0; i < Coder.Entries.size(); ++i) {
                stream << offset << step << "entry ";
                stream << (ui32)Coder.Entries[i].MinValue << " ";
                stream << (ui32)Coder.Entries[i].Prefix << " ";
                stream << (ui32)Coder.Entries[i].PrefixBits << " ";
                stream << (ui32)Coder.Entries[i].AllBits << " ";
                stream << Endl;
            }
            stream << offset << "end" << Endl;
        }

        void BeginElement(TBitBuffer& out) {
            Position = out.Position;
        }
        void Add(ui32 value, TBitBuffer& out) {
            size_t val = 0;
            ui64 code = Coder.Code(value, val);
            out.Code(code, val);
        }
        void AddDelayed(ui32 value, TBitBuffer& out) {
            size_t val = 0;
            ui64 code = Coder.Code(value, val);
            if (Position == (ui64)(-1)) {
                ythrow yexception() << "Position == (ui64)(-1)";
            }
            out.Insert(code, Position, val);
            out.Junk();
        }
    };

    struct THist {
        TAccum Accum;
        THist() {
        }

        void Load(IInputStream& stream) {
            TString name;
            while (1) {
                stream >> name;
                if (name == "end")
                    return;
            }
        }
        // TODO: why not const TString& ???
        void Save(IOutputStream& /*stream*/, TString /*offset*/) {
        }

        void Add(ui32 value, TEmpty& /*empty*/) {
            Accum.Add(value);
        }
        void AddDelayed(ui32 value, TEmpty& /*empty*/) {
            Accum.Add(value);
        }
        void BeginElement(TEmpty& /*empty*/) {
        }
    };

    struct THistToHuff {
        static THistToHuff Instance() {
            return THistToHuff();
        }
        TEmpty Build() const {
            return TEmpty();
        }
        void Build(THuff& info, const THist& hist) const {
            Analyze(hist.Accum, info.Coder.Entries);
            info.Coder.Normalize();
        }
    };

    struct IDecompressor {
        // sequentially decompresses whole structure according to metainfo, starts at position offset
        virtual void Decompress(const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset) = 0;
        // decompresses one record of outer repeated structure starting at position offset
        virtual void DecompressOne(const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset, ui32 prevIndex = -1) = 0;
        virtual ~IDecompressor() = default;
    };

    template <class X>
    struct TMetaIterator: public IDecompressor {
        X Self;
        TMetaIterator() {
            Self.Parent = this;
        }

    private:
        inline void DecompressSingle(ui32 repeatedIndex, const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset) {
            Self.BeginElement(repeatedIndex);
            ui32 mask = table->Mask.Decompress(codes, offset);
            size_t index = 0;
            ui32 scalarMask = table->ScalarMask;
            while (mask || scalarMask) {
                if (mask & 1) {
                    if (scalarMask & 1) {
                        ui32 val = table->Scalar[index].Decompress(codes, offset);
                        Self.SetScalar(index, val);
                    } else {
                        Self.GetDecompressor(index).Decompress(table->Repeated[index].Get(), codes, offset);
                    }
                } else if ((scalarMask & 1) && table->Default[index].Type == TScalarDefaultValue::Fixed) {
                    Self.SetScalar(index, table->Default[index].Value);
                }
                scalarMask = scalarMask >> 1;
                mask = mask >> 1;
                ++index;
            }
            Self.EndElement();
        }

        inline void DecompressSingleScalarsOnly(ui32 repeatedIndex, const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset) {
            Self.BeginElement(repeatedIndex);
            ui32 mask = table->Mask.Decompress(codes, offset);
            ui32 scalarMask = table->ScalarMask;
            size_t index = 0;
            while (scalarMask) {
                if (mask & 1) {
                    ui32 val = table->Scalar[index].Decompress(codes, offset);
                    Self.SetScalar(index, val);
                } else if (table->Default[index].Type == TScalarDefaultValue::Fixed) {
                    Self.SetScalar(index, table->Default[index].Value);
                }
                mask = mask >> 1;
                scalarMask = scalarMask >> 1;
                ++index;
            }
            Self.EndElement();
        }

    public:
        void Decompress(const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset) override {
            ui64 locOffset = offset;
            ui32 count = table->Count.Decompress(codes, locOffset);
            ui32 repeatedIndex = (ui32)(-1);
            Self.BeginSelf(count, table->Id);
            if (table->RepeatedMask) {
                for (ui32 i = 0; i < count; ++i) {
                    repeatedIndex += table->Index.Decompress(codes, locOffset);
                    DecompressSingle(repeatedIndex, table, codes, locOffset);
                }
            } else {
                for (ui32 i = 0; i < count; ++i) {
                    repeatedIndex += table->Index.Decompress(codes, locOffset);
                    DecompressSingleScalarsOnly(repeatedIndex, table, codes, locOffset);
                }
            }
            offset = locOffset;
            Self.EndSelf();
        }

        // XXX: iterator needed?
        //
        // Following two functions serves the purpose of decompressing outer repeated-structure(such structure is mandatory now).
        // They can work for inner repeated structures too, if you supply correct table, codes and offset parameters.
        void DecompressOne(const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset, ui32 prevIndex = -1) override {
            table->Index.Decompress(codes, offset);
            DecompressSingle(prevIndex, table, codes, offset);
        }

        ui32 DecompressCount(const TMetaInfo<TTable>* table, const ui8* codes, ui64& offset) {
            return table->Count.Decompress(codes, offset);
        }
    };

    template <class X>
    struct TParentHold {
        TMetaIterator<X>* Parent;
        TParentHold()
            : Parent(nullptr)
        {
        }
    };

    struct TEmptyDecompressor: public TParentHold<TEmptyDecompressor> {
        void BeginSelf(ui32 /*count*/, ui32 /*id*/) {
        }
        void EndSelf() {
        }
        void BeginElement(ui32 /*element*/) {
        }
        void EndElement() {
        }
        void SetScalar(size_t /*index*/, ui32 /*val*/) {
        }
        TMetaIterator<TEmptyDecompressor>& GetDecompressor(size_t index) {
            Y_UNUSED(index);
            return *Parent;
        }
    };

    inline TMetaIterator<TEmptyDecompressor>& GetEmptyDecompressor() {
        static TMetaIterator<TEmptyDecompressor> empty;
        return empty;
    }

    struct THuffToTable {
        static THuffToTable Instance() {
            return THuffToTable();
        }
        void Build(TTable& table, const THuff& huff) const {
            // can happen if a field was never serialized across whole structure
            if (huff.Coder.Entries.empty())
                return;
            for (ui32 i = 0; i < 64; ++i) {
                const TCoderEntry& entry = huff.Coder.GetEntry(i, table.Id[i]);
                table.CodeBase[i] = entry.MinValue;
                table.PrefLength[i] = entry.PrefixBits;
                table.CodeMask[i] = (1ULL << (entry.AllBits - entry.PrefixBits)) - 1ULL;
                table.Length[i] = entry.AllBits;
            }
        }
    };

    struct THuffToTableWithDecompressor: private THuffToTable {
        TSimpleSharedPtr<IDecompressor> Decompressor;
        THuffToTableWithDecompressor(TSimpleSharedPtr<IDecompressor> decompressor)
            : Decompressor(decompressor)
        {
        }
        TSimpleSharedPtr<IDecompressor> Build() const {
            return Decompressor;
        }
        void Build(TTable& table, const THuff& huff) const {
            THuffToTable::Build(table, huff);
        }
    };

}