DISPLACE  1.0
A spatial model of fisheries to help sustainable fishing and maritime spatial planning
binarygraphfilereader.h
Go to the documentation of this file.
1 #ifndef BINARYGRAPHFILEREADER_H
2 #define BINARYGRAPHFILEREADER_H
3 
4 #include <formats_globals.h>
5 
6 #include <utils/endian.h>
7 
8 #include <string>
9 #include <functional>
10 #include <system_error>
11 
12 #include <cstdio>
13 
14 #ifndef ATTRIBUTE_PACKED
15 #if !defined(_MSC_BUILD)
16 #define ATTRIBUTE_PACKED __attribute__ ((__packed__))
17 #else
18 #define ATTRIBUTE_PACKED
19 #endif
20 
21 #endif
22 
23 namespace displace {
24 namespace formats {
25 namespace legacy {
26 
28 public:
30  }
31 
32  template <typename Key, typename Value>
33  using LoaderFunction = std::function<bool(Key, Value)>;
34 
35  template <typename Key, typename Value>
36  bool importFromStream(const std::string &filename, LoaderFunction<Key,Value> use) {
37  using namespace displace::formats::helpers;
38 
39  FILE *file = fopen(filename.c_str(), "rb");
40  if (file == nullptr) {
41  throw std::system_error(errno,std::generic_category());
42  }
43 
44  #pragma pack(push,1)
45  struct ATTRIBUTE_PACKED {
46  uint32_t signature;
47  uint8_t keysize, valuesize;
48  } header;
49  #pragma pack(pop)
50 
51  size_t res;
52  if ((res = fread(&header, sizeof(header), 1, file)) != 1) {
53  throw std::system_error(errno,std::generic_category());
54  }
55 
56  if (fromLittleEndian( header.signature ) != 0x01020304 || header.keysize != sizeof(Key) || header.valuesize != sizeof(Value)) {
57  throw std::system_error(0,std::generic_category(), "Bad header or sizes");
58  }
59 
60  while (!feof(file)) {
61  #pragma pack(push,1)
62  struct ATTRIBUTE_PACKED {
63  Key k;
64  Value v;
65  } rec;
66  #pragma pack(pop)
67 
68  if ((res = fread(&rec, sizeof(rec), 1, file )) != 1) {
69  if (feof(file))
70  break;
71 
72  throw std::system_error(errno,std::generic_category());
73  }
74 
75  if (!use(fromLittleEndian(rec.k), fromLittleEndian(rec.v)))
76  throw std::system_error(0,std::generic_category(), "cannot insert data");
77  }
78 
79  fclose(file);
80  return true;
81  }
82 
83 };
84 
85 } // ns
86 }
87 }
88 
89 
90 #endif // BINARYGRAPHFILEREADER_H
uint16_t fromLittleEndian(uint16_t v)
Definition: endian.h:65
Definition: decisiontreemanager.h:13
BinaryGraphFileReader()
Definition: binarygraphfilereader.h:29
bool importFromStream(const std::string &filename, LoaderFunction< Key, Value > use)
Definition: binarygraphfilereader.h:36
#define ATTRIBUTE_PACKED
Definition: binarygraphfilereader.h:16
Definition: endian.h:10
std::function< bool(Key, Value)> LoaderFunction
Definition: binarygraphfilereader.h:33
Definition: binarygraphfilereader.h:27