init
[qstardict] / plugins / stardict / mapfile.hpp
1 #ifndef _MAPFILE_HPP_
2 #define _MAPFILE_HPP_
3
4 #ifdef HAVE_CONFIG_H
5 #  include "config.h"
6 #endif
7
8 #ifdef HAVE_MMAP
9 #  include <sys/types.h>
10 #  include <fcntl.h>
11 #  include <sys/mman.h>
12 #endif
13 #ifdef _WIN32
14 #  include <windows.h>
15 #endif
16 #include <glib.h>
17
18 class MapFile
19 {
20     public:
21         MapFile(void) :
22                 data(NULL),
23 #ifdef HAVE_MMAP
24                 mmap_fd( -1)
25 #elif defined(_WIN32)
26                 hFile(0),
27                 hFileMap(0)
28 #endif
29         {
30         }
31         ~MapFile();
32         bool open(const char *file_name, unsigned long file_size);
33         inline gchar *begin(void)
34         {
35             return data;
36         }
37     private:
38         char *data;
39         unsigned long size;
40 #ifdef HAVE_MMAP
41
42         int mmap_fd;
43 #elif defined(_WIN32)
44
45         HANDLE hFile;
46         HANDLE hFileMap;
47 #endif
48 };
49
50 inline bool MapFile::open(const char *file_name, unsigned long file_size)
51 {
52     size = file_size;
53 #ifdef HAVE_MMAP
54
55     if ((mmap_fd = ::open(file_name, O_RDONLY)) < 0)
56     {
57         //g_print("Open file %s failed!\n",fullfilename);
58         return false;
59     }
60     data = (gchar *)mmap( NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
61     if ((void *)data == (void *)( -1))
62     {
63         //g_print("mmap file %s failed!\n",idxfilename);
64         data = NULL;
65         return false;
66     }
67 #elif defined( _WIN32)
68 #ifdef UNICODE
69     gunichar2 *fn = g_utf8_to_utf16(file_name, -1, NULL, NULL, NULL);
70 #else // UNICODE
71     gchar *fn = file_name;
72 #endif // UNICODE
73     hFile = CreateFile(fn, GENERIC_READ, 0, NULL, OPEN_ALWAYS,
74                        FILE_ATTRIBUTE_NORMAL, 0);
75 #ifdef UNICODE
76     g_free(fn);
77 #endif // UNICODE
78     hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0,
79                                  file_size, NULL);
80     data = (gchar *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size);
81 #else // defined( _WIN32)
82
83     gsize read_len;
84     if (!g_file_get_contents(file_name, &data, &read_len, NULL))
85         return false;
86
87     if (read_len != file_size)
88         return false;
89 #endif
90
91     return true;
92 }
93
94 inline MapFile::~MapFile()
95 {
96     if (!data)
97         return ;
98 #ifdef HAVE_MMAP
99
100     munmap(data, size);
101     close(mmap_fd);
102 #else
103 #  ifdef _WIN32
104
105     UnmapViewOfFile(data);
106     CloseHandle(hFileMap);
107     CloseHandle(hFile);
108 #  else
109
110     g_free(data);
111 #  endif
112 #endif
113 }
114
115 #endif//!_MAPFILE_HPP_