1#include <unistd.h>
2#include <fcntl.h>
3
4#include <Common/ProfileEvents.h>
5#include <Common/formatReadable.h>
6#include <IO/MMapReadBufferFromFile.h>
7
8
9namespace ProfileEvents
10{
11 extern const Event FileOpen;
12}
13
14namespace DB
15{
16
17namespace ErrorCodes
18{
19 extern const int FILE_DOESNT_EXIST;
20 extern const int CANNOT_OPEN_FILE;
21 extern const int CANNOT_CLOSE_FILE;
22}
23
24
25void MMapReadBufferFromFile::open(const std::string & file_name)
26{
27 ProfileEvents::increment(ProfileEvents::FileOpen);
28
29 fd = ::open(file_name.c_str(), O_RDONLY);
30
31 if (-1 == fd)
32 throwFromErrnoWithPath("Cannot open file " + file_name, file_name,
33 errno == ENOENT ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE);
34}
35
36
37MMapReadBufferFromFile::MMapReadBufferFromFile(const std::string & file_name, size_t offset, size_t length_)
38{
39 open(file_name);
40 init(fd, offset, length_);
41}
42
43
44MMapReadBufferFromFile::MMapReadBufferFromFile(const std::string & file_name, size_t offset)
45{
46 open(file_name);
47 init(fd, offset);
48}
49
50
51MMapReadBufferFromFile::~MMapReadBufferFromFile()
52{
53 if (fd != -1)
54 close(); /// Exceptions will lead to std::terminate and that's Ok.
55}
56
57
58void MMapReadBufferFromFile::close()
59{
60 finish();
61
62 if (0 != ::close(fd))
63 throw Exception("Cannot close file", ErrorCodes::CANNOT_CLOSE_FILE);
64
65 fd = -1;
66 metric_increment.destroy();
67}
68
69}
70