diff options
author | Peng Wu <alexepico@gmail.com> | 2015-04-08 16:09:32 +0800 |
---|---|---|
committer | Peng Wu <alexepico@gmail.com> | 2015-04-08 16:33:28 +0800 |
commit | 8f7571b2c5ac37e2741833e0e56567fac2ccd98f (patch) | |
tree | d1cd998fed744fbdd7d90c7e56856703ca3465f8 | |
parent | 41d3fd472f5290103927aae0966fbae40fa379e7 (diff) | |
download | libpinyin-8f7571b2c5ac37e2741833e0e56567fac2ccd98f.tar.gz libpinyin-8f7571b2c5ac37e2741833e0e56567fac2ccd98f.tar.xz libpinyin-8f7571b2c5ac37e2741833e0e56567fac2ccd98f.zip |
split load method into load and mmap of MemoryChunk
-rw-r--r-- | src/include/memory_chunk.h | 50 |
1 files changed, 38 insertions, 12 deletions
diff --git a/src/include/memory_chunk.h b/src/include/memory_chunk.h index 2792d5d..49b54f6 100644 --- a/src/include/memory_chunk.h +++ b/src/include/memory_chunk.h @@ -31,6 +31,7 @@ #include <stdlib.h> #ifdef HAVE_MMAP #include <sys/mman.h> +#define LIBPINYIN_USE_MMAP #endif #include "stl_lite.h" @@ -358,17 +359,6 @@ public: int data_len = file_size; -#ifdef HAVE_MMAP - void* data = mmap(NULL, data_len, PROT_READ|PROT_WRITE, MAP_PRIVATE, - fd, 0); - - if (MAP_FAILED == data) { - close(fd); - return false; - } - - set_chunk(data, data_len, (free_func_t)munmap); -#else void* data = malloc(data_len); if ( !data ){ close(fd); @@ -377,12 +367,48 @@ public: data_len = read(fd, data, data_len); set_chunk(data, data_len, (free_func_t)free); -#endif close(fd); return true; } +#ifdef LIBPINYIN_USE_MMAP + /** + * MemoryChunk::mmap: + * @filename: mmap the MemoryChunk from the filename. + * @returns: whether the mmap is successful. + * + * mmap the content from the filename. + * + */ + bool mmap(const char * filename){ + /* free old data */ + reset(); + + int fd = open(filename, O_RDONLY); + if (-1 == fd) + return false; + + off_t file_size = lseek(fd, 0, SEEK_END); + lseek(fd, 0, SEEK_SET); + + int data_len = file_size; + + void* data = ::mmap(NULL, data_len, PROT_READ|PROT_WRITE, MAP_PRIVATE, + fd, 0); + + if (MAP_FAILED == data) { + close(fd); + return false; + } + + set_chunk(data, data_len, (free_func_t)munmap); + + close(fd); + return true; + } +#endif + /** * MemoryChunk::save: * @filename: save this MemoryChunk to the filename. |