aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/on_disk/chunks/writer.h
blob: fbd02eef4bb32299cb07e710c146d284442ab579 (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
#pragma once

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

template <typename T>
inline void WriteBin(IOutputStream* out, typename TTypeTraits<T>::TFuncParam t) {
    out->Write(&t, sizeof(T));
}

class TChunkedDataWriter: public IOutputStream {
public: 
    TChunkedDataWriter(IOutputStream& slave); 
    ~TChunkedDataWriter() override; 

    void NewBlock(); 

    template <typename T> 
    inline void WriteBinary(typename TTypeTraits<T>::TFuncParam t) { 
        this->Write(&t, sizeof(T)); 
    } 

    void WriteFooter(); 

    size_t GetCurrentBlockOffset() const; 
    size_t GetBlockCount() const; 

protected: 
    void DoWrite(const void* buf, size_t len) override { 
        Slave.Write(buf, len); 
        Offset += len; 
    } 

private: 
    static inline size_t PaddingSize(size_t size, size_t boundary) noexcept { 
        const size_t boundaryViolation = size % boundary; 

        return boundaryViolation == 0 ? 0 : boundary - boundaryViolation; 
    } 

    inline void Pad(size_t boundary) { 
        const size_t newOffset = Offset + PaddingSize(Offset, boundary); 

        while (Offset < newOffset) { 
            Write('\0'); 
        }
    } 

private: 
    static const ui64 Version = 1; 

    IOutputStream& Slave; 

    size_t Offset; 
    TVector<ui64> Offsets; 
    TVector<ui64> Lengths; 
};