1#ifndef MARISA_ALPHA_READER_H_
2#define MARISA_ALPHA_READER_H_
3
4#include <cstdio>
5#include <iostream>
6
7#include "base.h"
8
9namespace marisa_alpha {
10
11class 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_ALPHA_THROW_IF(obj == NULL, MARISA_ALPHA_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_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      read_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(Reader *rhs);
44
45 private:
46  std::FILE *file_;
47  int fd_;
48  std::istream *stream_;
49  bool needs_fclose_;
50
51  void read_data(void *buf, std::size_t size);
52
53  // Disallows copy and assignment.
54  Reader(const Reader &);
55  Reader &operator=(const Reader &);
56};
57
58}  // namespace marisa_alpha
59
60#endif  // MARISA_ALPHA_READER_H_
61