1 #ifndef MARISA_GRIMOIRE_IO_READER_H_ 2 #define MARISA_GRIMOIRE_IO_READER_H_ 3 4 #include <cstdio> 5 #include <iostream> 6 7 #include "marisa/base.h" 8 9 namespace marisa { 10 namespace grimoire { 11 namespace io { 12 13 class Reader { 14 public: 15 Reader(); 16 ~Reader(); 17 18 void open(const char *filename); 19 void open(std::FILE *file); 20 void open(int fd); 21 void open(std::istream &stream); 22 23 template <typename T> read(T * obj)24 void read(T *obj) { 25 MARISA_THROW_IF(obj == NULL, MARISA_NULL_ERROR); 26 read_data(obj, sizeof(T)); 27 } 28 29 template <typename T> read(T * objs,std::size_t num_objs)30 void read(T *objs, std::size_t num_objs) { 31 MARISA_THROW_IF((objs == NULL) && (num_objs != 0), MARISA_NULL_ERROR); 32 MARISA_THROW_IF(num_objs > (MARISA_SIZE_MAX / sizeof(T)), 33 MARISA_SIZE_ERROR); 34 read_data(objs, sizeof(T) * num_objs); 35 } 36 37 void seek(std::size_t size); 38 39 bool is_open() const; 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 open_(const char *filename); 51 void open_(std::FILE *file); 52 void open_(int fd); 53 void open_(std::istream &stream); 54 55 void read_data(void *buf, std::size_t size); 56 57 // Disallows copy and assignment. 58 Reader(const Reader &); 59 Reader &operator=(const Reader &); 60 }; 61 62 } // namespace io 63 } // namespace grimoire 64 } // namespace marisa 65 66 #endif // MARISA_GRIMOIRE_IO_READER_H_ 67