aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/netliba/v6/ib_memstream.h
blob: 67eb2386dec80c0a9877f50300496cfc3d5ffb89 (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
#pragma once

#include "ib_mem.h"
#include <library/cpp/binsaver/bin_saver.h>
#include <library/cpp/binsaver/buffered_io.h>

namespace NNetliba {
    class TIBMemStream: public IBinaryStream {
        struct TBlock {
            TIntrusivePtr<TIBMemBlock> Mem;
            i64 StartOffset;
            int BufSize, DataSize;

            TBlock()
                : StartOffset(0)
                , BufSize(0)
                , DataSize(0)
            {
            }
            TBlock(const TBlock& x) {
                Copy(x);
            }
            void operator=(const TBlock& x) {
                Copy(x);
            }
            void Copy(const TBlock& x) {
                if (x.BufSize > 0) {
                    Mem = GetIBMemPool()->Alloc(x.BufSize);
                    memcpy(Mem->GetData(), x.Mem->GetData(), x.DataSize);
                    StartOffset = x.StartOffset;
                    BufSize = x.BufSize;
                    DataSize = x.DataSize;
                } else {
                    Mem = nullptr;
                    StartOffset = 0;
                    BufSize = 0;
                    DataSize = 0;
                }
            }
        };

        TIntrusivePtr<TIBMemPool> MemPool;
        TVector<TBlock> Blocks;
        int CurBlock;
        int CurBlockOffset;

    public:
        struct TBlockDescr {
            ui64 Addr;
            int BufSize, DataSize;
            ui32 RemoteKey, LocalKey;
        };
        struct TBlockSizes {
            int BufSize, DataSize;
        };

    public:
        TIBMemStream()
            : MemPool(GetIBMemPool())
            , CurBlock(0)
            , CurBlockOffset(0)
        {
        }
        ~TIBMemStream() override {
        } // keep gcc happy

        bool IsValid() const override {
            return true;
        }
        bool IsFailed() const override {
            return false;
        }
        void Flush() {
        }

        i64 GetLength();
        i64 Seek(i64 pos);

        void GetBlocks(TVector<TBlockDescr>* res) const;
        void CreateBlocks(const TVector<TBlockSizes>& arr);

        void Clear();

    private:
        int WriteImpl(const void* userBuffer, int size) override;
        int ReadImpl(void* userBuffer, int size) override;
    };

    template <class T>
    inline void Serialize(bool bRead, TIBMemStream& ms, T& c) {
        IBinSaver bs(ms, bRead);
        bs.Add(1, &c);
    }

}