1 #ifndef MARISA_ALPHA_MAPPER_H_ 2 #define MARISA_ALPHA_MAPPER_H_ 3 4 #include <cstdio> 5 6 #include "base.h" 7 8 namespace marisa_alpha { 9 10 class Mapper { 11 public: 12 Mapper(); 13 Mapper(const void *ptr, std::size_t size); 14 ~Mapper(); 15 16 void open(const char *filename, long offset = 0, int whence = SEEK_SET); 17 18 template <typename T> 19 void map(T *obj) { 20 MARISA_ALPHA_THROW_IF(obj == NULL, MARISA_ALPHA_PARAM_ERROR); 21 *obj = *static_cast<const T *>(map_data(sizeof(T))); 22 } 23 24 template <typename T> 25 void map(const T **objs, std::size_t num_objs) { 26 MARISA_ALPHA_THROW_IF((objs == NULL) && (num_objs != 0), 27 MARISA_ALPHA_PARAM_ERROR); 28 MARISA_ALPHA_THROW_IF(num_objs > (MARISA_ALPHA_UINT32_MAX / sizeof(T)), 29 MARISA_ALPHA_SIZE_ERROR); 30 *objs = static_cast<const T *>(map_data(sizeof(T) * num_objs)); 31 } 32 33 bool is_open() const { 34 return ptr_ != NULL; 35 } 36 37 void clear(); 38 void swap(Mapper *rhs); 39 40 private: 41 const void *ptr_; 42 void *origin_; 43 std::size_t avail_; 44 std::size_t size_; 45 #if defined _WIN32 || defined _WIN64 46 void *file_; 47 void *map_; 48 #else // defined _WIN32 || defined _WIN64 49 int fd_; 50 #endif // defined _WIN32 || defined _WIN64 51 52 void seek(long offset, int whence); 53 54 const void *map_data(std::size_t size); 55 56 // Disallows copy and assignment. 57 Mapper(const Mapper &); 58 Mapper &operator=(const Mapper &); 59 }; 60 61 } // namespace marisa_alpha 62 63 #endif // MARISA_ALPHA_MAPPER_H_ 64