Scanner C++ API
storehouse.h
1 /* Copyright 2016 Carnegie Mellon University
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #pragma once
17 
18 #include "scanner/util/common.h"
19 #include "storehouse/storage_backend.h"
20 
21 #include <cassert>
22 #include <string>
23 
24 namespace scanner {
25 
26 inline void s_write(storehouse::WriteFile* file, const u8* buffer,
27  size_t size) {
28  storehouse::StoreResult result;
29  EXP_BACKOFF(file->append(size, buffer), result);
30  exit_on_error(result);
31 }
32 
33 template <typename T>
34 inline void s_write(storehouse::WriteFile* file, const T& value) {
35  s_write(file, reinterpret_cast<const u8*>(&value), sizeof(T));
36 }
37 
38 template <>
39 inline void s_write(storehouse::WriteFile* file, const std::string& s) {
40  s_write(file, reinterpret_cast<const u8*>(s.c_str()), s.size() + 1);
41 }
42 
43 inline void s_read(storehouse::RandomReadFile* file, u8* buffer, size_t size,
44  u64& pos) {
45  VLOG(2) << "Reading " << file->path() << " (size " << size << ", pos " << pos
46  << ")";
47  storehouse::StoreResult result;
48  size_t size_read;
49  EXP_BACKOFF(file->read(pos, size, buffer, size_read), result);
50  if (result != storehouse::StoreResult::EndOfFile) {
51  exit_on_error(result);
52  }
53  assert(size_read == size);
54  pos += size_read;
55 }
56 
57 template <typename T>
58 inline T s_read(storehouse::RandomReadFile* file, u64& pos) {
59  T var;
60  s_read(file, reinterpret_cast<u8*>(&var), sizeof(T), pos);
61  return var;
62 }
63 
64 template <>
65 inline std::string s_read(storehouse::RandomReadFile* file, u64& pos) {
66  u64 curr_pos = pos;
67 
68  std::string var;
69  while (true) {
70  const size_t buf_size = 256;
71  u8 buf[buf_size];
72 
73  storehouse::StoreResult result;
74  size_t size_read;
75  EXP_BACKOFF(file->read(pos, buf_size, buf, size_read), result);
76  if (result != storehouse::StoreResult::EndOfFile) {
77  exit_on_error(result);
78  assert(size_read == buf_size);
79  }
80 
81  size_t buf_pos = 0;
82  while (buf_pos < buf_size) {
83  if (buf[buf_pos] == '\0') break;
84  var += buf[buf_pos];
85  buf_pos++;
86  }
87  if (buf_pos < buf_size && buf[buf_pos] == '\0') break;
88 
89  curr_pos += buf_size;
90  }
91  pos += var.size() + 1;
92  return var;
93 }
94 }
Definition: database.cpp:36