1 #ifndef MARISA_GRIMOIRE_IO_WRITER_H_ 2 #define MARISA_GRIMOIRE_IO_WRITER_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 Writer { 14 public: 15 Writer(); 16 ~Writer(); 17 18 void open(const char *filename); 19 void open(std::FILE *file); 20 void open(int fd); 21 void open(std::ostream &stream); 22 23 template <typename T> write(const T & obj)24 void write(const T &obj) { 25 write_data(&obj, sizeof(T)); 26 } 27 28 template <typename T> write(const T * objs,std::size_t num_objs)29 void write(const T *objs, std::size_t num_objs) { 30 MARISA_THROW_IF((objs == NULL) && (num_objs != 0), MARISA_NULL_ERROR); 31 MARISA_THROW_IF(num_objs > (MARISA_SIZE_MAX / sizeof(T)), 32 MARISA_SIZE_ERROR); 33 write_data(objs, sizeof(T) * num_objs); 34 } 35 36 void seek(std::size_t size); 37 38 bool is_open() const; 39 40 void clear(); 41 void swap(Writer &rhs); 42 43 private: 44 std::FILE *file_; 45 int fd_; 46 std::ostream *stream_; 47 bool needs_fclose_; 48 49 void open_(const char *filename); 50 void open_(std::FILE *file); 51 void open_(int fd); 52 void open_(std::ostream &stream); 53 54 void write_data(const void *data, std::size_t size); 55 56 // Disallows copy and assignment. 57 Writer(const Writer &); 58 Writer &operator=(const Writer &); 59 }; 60 61 } // namespace io 62 } // namespace grimoire 63 } // namespace marisa 64 65 #endif // MARISA_GRIMOIRE_IO_WRITER_H_ 66