NAP
memorystream.h
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4 
5 #pragma once
6 
7 #include <string>
8 #include <memory>
9 #include <assert.h>
10 #include <cstring>
11 
12 namespace nap
13 {
14  namespace utility
15  {
20  {
21  public:
28  MemoryStream(const uint8_t* buffer, uint32_t length) :
29  mBuffer(buffer),
30  mLength(length),
31  mReadPos(buffer)
32  {
33  }
34 
40  bool isDone() const
41  {
42  return mReadPos >= (mBuffer + mLength);
43  }
44 
51  bool hasAvailable(uint32_t size)
52  {
53  return (mLength - (mReadPos - mBuffer)) >= size;
54  }
55 
62  void read(void* data, uint32_t length)
63  {
64  assert(hasAvailable(length));
65 
66  std::memcpy(data, mReadPos, length);
67  mReadPos += length;
68  }
69 
75  template<class T>
76  void read(T& data)
77  {
78  read(&data, sizeof(T));
79  }
80 
86  template<class T>
87  const T read()
88  {
89  T value;
90  read(value);
91 
92  return value;
93  }
94 
100  void readString(std::string& string)
101  {
102  // Read the length of the string
103  size_t length;
104  read(length);
105 
106  // Resize string and read data
107  string.resize(length);
108  read((void*)string.data(), length);
109  }
110 
111  private:
112  const uint8_t* mBuffer; // The buffer we're reading from
113  uint32_t mLength; // The length of the buffer
114  const uint8_t* mReadPos; // Current position in the buffer we're reading from
115  };
116  }
117 }
nap::utility::MemoryStream::read
void read(T &data)
Definition: memorystream.h:76
nap::utility::MemoryStream::isDone
bool isDone() const
Definition: memorystream.h:40
nap::utility::MemoryStream
Definition: memorystream.h:19
nap::utility::MemoryStream::readString
void readString(std::string &string)
Definition: memorystream.h:100
nap::utility::MemoryStream::hasAvailable
bool hasAvailable(uint32_t size)
Definition: memorystream.h:51
nap::utility::MemoryStream::read
void read(void *data, uint32_t length)
Definition: memorystream.h:62
nap::utility::MemoryStream::MemoryStream
MemoryStream(const uint8_t *buffer, uint32_t length)
Definition: memorystream.h:28
nap
Definition: templateapp.h:17
nap::utility::MemoryStream::read
const T read()
Definition: memorystream.h:87