From 8f7571b2c5ac37e2741833e0e56567fac2ccd98f Mon Sep 17 00:00:00 2001 From: Peng Wu Date: Wed, 8 Apr 2015 16:09:32 +0800 Subject: split load method into load and mmap of MemoryChunk --- src/include/memory_chunk.h | 50 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 12 deletions(-) (limited to 'src/include') 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 #ifdef HAVE_MMAP #include +#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. -- cgit