author | František Kučera <franta-hg@frantovo.cz> |
Fri, 12 Jan 2024 00:45:40 +0100 | |
branch | v_0 |
changeset 40 | df1376ef9f6d |
parent 29 | dc3c102e1264 |
permissions | -rw-r--r-- |
0 | 1 |
/** |
29
dc3c102e1264
derive OHP3D from ShaderShark
František Kučera <franta-hg@frantovo.cz>
parents:
0
diff
changeset
|
2 |
* OHP3D |
0 | 3 |
* Copyright © 2023 František Kučera (Frantovo.cz, GlobalCode.info) |
4 |
* |
|
5 |
* This program is free software: you can redistribute it and/or modify |
|
6 |
* it under the terms of the GNU General Public License as published by |
|
7 |
* the Free Software Foundation, version 3 of the License. |
|
8 |
* |
|
9 |
* This program is distributed in the hope that it will be useful, |
|
10 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 |
* GNU General Public License for more details. |
|
13 |
* |
|
14 |
* You should have received a copy of the GNU General Public License |
|
15 |
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 |
*/ |
|
17 |
||
18 |
#pragma once |
|
19 |
||
20 |
#include <sys/mman.h> |
|
21 |
#include <unistd.h> |
|
22 |
#include <sys/stat.h> |
|
23 |
#include <fcntl.h> |
|
24 |
||
25 |
#include "Buffer.h" |
|
26 |
||
27 |
class MappedFile : public Buffer { |
|
28 |
private: |
|
29 |
int fd = -1; |
|
30 |
public: |
|
31 |
||
32 |
MappedFile(const std::string& fileName) { |
|
33 |
struct stat stat; |
|
34 |
fd = open(fileName.c_str(), O_RDONLY); |
|
35 |
if (fd < 0) throw std::invalid_argument("unable to open file"); |
|
36 |
||
37 |
int result = fstat(fd, &stat); |
|
38 |
if (result) throw std::invalid_argument("unable to stat file"); |
|
39 |
||
40 |
size = stat.st_size; |
|
41 |
data = static_cast<char*> ( |
|
42 |
mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0)); |
|
43 |
if (data == MAP_FAILED) throw std::invalid_argument("unable to mmap"); |
|
44 |
// std::cerr << "MappedFile() / mmap()" << std::endl; |
|
45 |
} |
|
46 |
||
47 |
virtual ~MappedFile() { |
|
48 |
int result = munmap(data, size); |
|
49 |
// std::cerr << "~MappedFile() / munmap() = " << result << std::endl; |
|
50 |
result = close(fd); |
|
51 |
// std::cerr << "~MappedFile() / close() = " << result << std::endl; |
|
52 |
} |
|
53 |
||
54 |
MappedFile(const MappedFile&) = delete; |
|
55 |
MappedFile& operator=(const MappedFile&) = delete; |
|
56 |
||
57 |
}; |