1#ifndef MARISA_WRITER_H_
2#define MARISA_WRITER_H_
3
4#include <cstdio>
5#include <iostream>
6
7#include "base.h"
8
9namespace marisa {
10
11class Writer {
12 public:
13  Writer();
14  explicit Writer(std::FILE *file);
15  explicit Writer(int fd);
16  explicit Writer(std::ostream *stream);
17  ~Writer();
18
19  void open(const char *filename, bool trunc_flag = true,
20      long offset = 0, int whence = SEEK_SET);
21
22  template <typename T>
23  void write(const T &obj) {
24    write_data(&obj, sizeof(T));
25  }
26
27  template <typename T>
28  void write(const 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      write_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(Writer *rhs);
43
44 private:
45  std::FILE *file_;
46  int fd_;
47  std::ostream *stream_;
48  bool needs_fclose_;
49
50  void write_data(const void *data, std::size_t size);
51
52  // Disallows copy and assignment.
53  Writer(const Writer &);
54  Writer &operator=(const Writer &);
55};
56
57}  // namespace marisa
58
59#endif  // MARISA_WRITER_H_
60