1 #pragma once
2
3 #ifdef HAVE_CONFIG_H
4 #include "config.h"
5 #endif
6
7 #include <cstdlib>
8 #include <unistd.h>
9
10 #ifdef HAVE_MMAP
11 #include <fcntl.h>
12 #include <sys/mman.h>
13 #include <sys/types.h>
14 #endif
15 #ifdef _WIN32
16 #include <windows.h>
17 #endif
18 #include <glib.h>
19
20 class MapFile
21 {
22 public:
MapFile()23 MapFile() {}
24 ~MapFile();
25 MapFile(const MapFile &) = delete;
26 MapFile &operator=(const MapFile &) = delete;
27 bool open(const char *file_name, unsigned long file_size);
begin()28 gchar *begin() { return data; }
29
30 private:
31 char *data = nullptr;
32 unsigned long size = 0ul;
33 #ifdef HAVE_MMAP
34 int mmap_fd = -1;
35 #elif defined(_WIN32)
36 HANDLE hFile = 0;
37 HANDLE hFileMap = 0;
38 #endif
39 };
40
open(const char * file_name,unsigned long file_size)41 inline bool MapFile::open(const char *file_name, unsigned long file_size)
42 {
43 size = file_size;
44 #ifdef HAVE_MMAP
45 if ((mmap_fd = ::open(file_name, O_RDONLY)) < 0) {
46 //g_print("Open file %s failed!\n",fullfilename);
47 return false;
48 }
49 data = (gchar *)mmap(nullptr, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
50 if ((void *)data == (void *)(-1)) {
51 //g_print("mmap file %s failed!\n",idxfilename);
52 data = nullptr;
53 return false;
54 }
55 #elif defined(_WIN32)
56 hFile = CreateFile(file_name, GENERIC_READ, 0, nullptr, OPEN_ALWAYS,
57 FILE_ATTRIBUTE_NORMAL, 0);
58 hFileMap = CreateFileMapping(hFile, nullptr, PAGE_READONLY, 0,
59 file_size, nullptr);
60 data = (gchar *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size);
61 #else
62 gsize read_len;
63 if (!g_file_get_contents(file_name, &data, &read_len, nullptr))
64 return false;
65
66 if (read_len != file_size)
67 return false;
68 #endif
69
70 return true;
71 }
72
~MapFile()73 inline MapFile::~MapFile()
74 {
75 if (!data)
76 return;
77 #ifdef HAVE_MMAP
78 munmap(data, size);
79 close(mmap_fd);
80 #else
81 #ifdef _WIN32
82 UnmapViewOfFile(data);
83 CloseHandle(hFileMap);
84 CloseHandle(hFile);
85 #else
86 g_free(data);
87 #endif
88 #endif
89 }
90