R-Type
R-Type project
NetworkReader.hpp
1 #pragma once
2 
3 #include "Array.hpp"
4 #include "ArraySegment.hpp"
5 #include "Platform.hpp"
6 #include <string>
7 #include <memory>
8 
9 namespace KapMirror {
10  class NetworkReader {
11  private:
12  byte* buffer = nullptr;
13  int position;
14 
15  public:
16  explicit NetworkReader(byte* _buffer) : buffer(_buffer) { position = 0; }
17 
18  explicit NetworkReader(const ArraySegment<byte>& segment) {
19  buffer = segment.toArray();
20  position = 0;
21  }
22 
23  explicit NetworkReader(const std::shared_ptr<ArraySegment<byte>>& segment) {
24  buffer = segment->toArray();
25  position = 0;
26  }
27 
28  ~NetworkReader() = default;
29 
33  inline void reset() { position = 0; }
34 
40  template <typename T>
41  inline T read() {
42  T value = *(T*)(buffer + position);
43  position += sizeof(T);
44  return value;
45  }
46 
51  byte* readBytes(int count) {
52  byte* array = new byte[count];
53  std::copy(buffer + position, buffer + position + count, array);
54  position += count;
55  return array;
56  }
57 
62  std::string readString() {
63  auto length = read<short>();
64  byte* array = readBytes(length);
65  std::string str((char*)array, length);
66  delete[] array;
67  return str;
68  }
69  };
70 } // namespace KapMirror
KapMirror::NetworkReader::readString
std::string readString()
Read a string from the buffer.
Definition: NetworkReader.hpp:62
KapMirror::ArraySegment::toArray
T * toArray() const
Get the array.
Definition: ArraySegment.hpp:40
KapMirror::NetworkReader
Definition: NetworkReader.hpp:10
KapMirror::NetworkReader::readBytes
byte * readBytes(int count)
Read a byte array from the buffer.
Definition: NetworkReader.hpp:51
KapMirror::NetworkReader::read
T read()
Read a value from the buffer.
Definition: NetworkReader.hpp:41
KapMirror::NetworkReader::reset
void reset()
Reset the position to 0.
Definition: NetworkReader.hpp:33
KapMirror::ArraySegment
Definition: ArraySegment.hpp:9