1 #ifndef MARISA_MAPPER_H_ 2 #define MARISA_MAPPER_H_ 3 4 #include <cstdio> 5 6 #include "base.h" 7 8 namespace marisa { 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> map(T * obj)19 void map(T *obj) { 20 MARISA_THROW_IF(obj == NULL, MARISA_PARAM_ERROR); 21 *obj = *static_cast<const T *>(map_data(sizeof(T))); 22 } 23 24 template <typename T> map(const T ** objs,std::size_t num_objs)25 void map(const T **objs, std::size_t num_objs) { 26 MARISA_THROW_IF((objs == NULL) && (num_objs != 0), MARISA_PARAM_ERROR); 27 MARISA_THROW_IF(num_objs > (MARISA_UINT32_MAX / sizeof(T)), 28 MARISA_SIZE_ERROR); 29 *objs = static_cast<const T *>(map_data(sizeof(T) * num_objs)); 30 } 31 is_open()32 bool is_open() const { 33 return ptr_ != NULL; 34 } 35 36 void clear(); 37 void swap(Mapper *rhs); 38 39 private: 40 const void *ptr_; 41 void *origin_; 42 std::size_t avail_; 43 std::size_t size_; 44 #if defined _WIN32 || defined _WIN64 45 void *file_; 46 void *map_; 47 #else // defined _WIN32 || defined _WIN64 48 int fd_; 49 #endif // defined _WIN32 || defined _WIN64 50 51 void seek(long offset, int whence); 52 53 const void *map_data(std::size_t size); 54 55 // Disallows copy and assignment. 56 Mapper(const Mapper &); 57 Mapper &operator=(const Mapper &); 58 }; 59 60 } // namespace marisa 61 62 #endif // MARISA_MAPPER_H_ 63