aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/IO/MMappedFileDescriptor.h
blob: 2611093643fc6902111a7f76a224b64d4f75af2a (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
#pragma once

#include <cstddef>
#include <Common/CurrentMetrics.h>

namespace CurrentMetrics
{
    extern const Metric MMappedFiles;
    extern const Metric MMappedFileBytes;
}


namespace DB
{

/// MMaps a region in file (or a whole file) into memory. Unmaps in destructor.
/// Does not open or close file.
class MMappedFileDescriptor
{
public:
    MMappedFileDescriptor(int fd_, size_t offset_, size_t length_);
    MMappedFileDescriptor(int fd_, size_t offset_);

    /// Makes empty object that can be initialized with `set`.
    MMappedFileDescriptor() = default;

    virtual ~MMappedFileDescriptor();

    char * getData() { return data; }
    const char * getData() const { return data; }

    int getFD() const { return fd; }
    size_t getOffset() const { return offset; }
    size_t getLength() const { return length; }

    /// Unmap memory before call to destructor
    void finish();

    /// Initialize or reset to another fd.
    void set(int fd_, size_t offset_, size_t length_);
    void set(int fd_, size_t offset_);

    MMappedFileDescriptor(const MMappedFileDescriptor &) = delete;
    MMappedFileDescriptor(MMappedFileDescriptor &&) = delete;

protected:

    void init();

    int fd = -1;
    size_t offset = 0;
    size_t length = 0;
    char * data = nullptr;

    CurrentMetrics::Increment files_metric_increment{CurrentMetrics::MMappedFiles, 0};
    CurrentMetrics::Increment bytes_metric_increment{CurrentMetrics::MMappedFileBytes, 0};
};

}