1#ifndef MARISA_ALPHA_WRITER_H_
2#define MARISA_ALPHA_WRITER_H_
3
4#include <cstdio>
5#include <iostream>
6
7#include "base.h"
8
9namespace marisa_alpha {
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_ALPHA_THROW_IF((objs == NULL) && (num_objs != 0),
30        MARISA_ALPHA_PARAM_ERROR);
31    MARISA_ALPHA_THROW_IF(num_objs > (MARISA_ALPHA_UINT32_MAX / sizeof(T)),
32        MARISA_ALPHA_SIZE_ERROR);
33    if (num_objs != 0) {
34      write_data(objs, sizeof(T) * num_objs);
35    }
36  }
37
38  bool is_open() const {
39    return (file_ != NULL) || (fd_ != -1) || (stream_ != NULL);
40  }
41
42  void clear();
43  void swap(Writer *rhs);
44
45 private:
46  std::FILE *file_;
47  int fd_;
48  std::ostream *stream_;
49  bool needs_fclose_;
50
51  void write_data(const void *data, std::size_t size);
52
53  // Disallows copy and assignment.
54  Writer(const Writer &);
55  Writer &operator=(const Writer &);
56};
57
58}  // namespace marisa_alpha
59
60#endif  // MARISA_ALPHA_WRITER_H_
61