TorchCraftAI
A bot for machine learning research on StarCraft: Brood War
streaming_flatbuffers.h
1 /**
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
8  */
9 
10 #pragma once
11 
12 #include <iostream>
13 #include <memory>
14 
15 #include "flatbuffers.h"
16 
17 namespace torchcraft {
18 namespace replayer {
19 
20 // Methods to write/read Flatbuffer types to/from a stream.
21 //
22 // We need these because Flatbuffers don't have a fixed size;
23 // they just read from their input pointer until complete,
24 // an don't record the number of bytes consumed in the process.
25 //
26 // So you can't just read in a Flatbuffer from a stream, because you need
27 // to read a chunk the stream in advance; and the amount of stream you need
28 // to read is dynamic; so these methods reads/write metadata
29 // (the size of the stored Flatbuffer) to enable streaming.
30 
31 // Serialization format:
32 // {
33 // size_t The flatbuffer's size,
34 // t The flatbuffer
35 // }
36 
37 static void writeFlatBufferToStream(std::ostream& out, flatbuffers::FlatBufferBuilder& finishedFlatBufferBuilder) {
38  auto flatbufferPointer = finishedFlatBufferBuilder.GetBufferPointer();
39  size_t flatbufferSize = finishedFlatBufferBuilder.GetSize();
40  out.write(reinterpret_cast<char*>(&flatbufferSize), sizeof(size_t));
41  out.write(
42  reinterpret_cast<char*>(flatbufferPointer),
43  flatbufferSize);
44 }
45 
46 template <typename T>
47 static void readFlatBufferTableFromStream(
48  std::istream& in,
49  std::function<void(const T&)> tableReader) {
50  size_t bufferSize;
51  in.read(reinterpret_cast<char*>(&bufferSize), sizeof(size_t));
52 
53  std::vector<char> buffer(bufferSize);
54  in.read(buffer.data(), bufferSize);
55 
56  flatbuffers::Verifier verifier(reinterpret_cast<uint8_t*>(buffer.data()), bufferSize);
57  if ( ! verifier.VerifyBuffer<T>()) {
58  throw std::runtime_error("Streaming FlatBuffer table failed verification");
59  };
60 
61  auto table = flatbuffers::GetRoot<T>(buffer.data());
62 
63  tableReader(*table);
64 }
65 
66 } // namespace replayer
67 } // namespace torchcraft
Copyright (c) 2015-present, Facebook, Inc.
Definition: openbwprocess.h:17