1 #ifndef MARISA_READER_H_ 2 #define MARISA_READER_H_ 3 4 #include <cstdio> 5 #include <iostream> 6 7 #include "base.h" 8 9 namespace marisa { 10 11 class Reader { 12 public: 13 Reader(); 14 explicit Reader(std::FILE *file); 15 explicit Reader(int fd); 16 explicit Reader(std::istream *stream); 17 ~Reader(); 18 19 void open(const char *filename, long offset = 0, int whence = SEEK_SET); 20 21 template <typename T> 22 void read(T *obj) { 23 MARISA_THROW_IF(obj == NULL, MARISA_PARAM_ERROR); 24 read_data(obj, sizeof(T)); 25 } 26 27 template <typename T> 28 void read(T *objs, std::size_t num_objs) { 29 MARISA_THROW_IF((objs == NULL) && (num_objs != 0), MARISA_PARAM_ERROR); 30 MARISA_THROW_IF(num_objs > (MARISA_UINT32_MAX / sizeof(T)), 31 MARISA_SIZE_ERROR); 32 if (num_objs != 0) { 33 read_data(objs, sizeof(T) * num_objs); 34 } 35 } 36 37 bool is_open() const { 38 return (file_ != NULL) || (fd_ != -1) || (stream_ != NULL); 39 } 40 41 void clear(); 42 void swap(Reader *rhs); 43 44 private: 45 std::FILE *file_; 46 int fd_; 47 std::istream *stream_; 48 bool needs_fclose_; 49 50 void read_data(void *buf, std::size_t size); 51 52 // Disallows copy and assignment. 53 Reader(const Reader &); 54 Reader &operator=(const Reader &); 55 }; 56 57 } // namespace marisa 58 59 #endif // MARISA_READER_H_ 60