blob: f16b8f816b89450fd60a34a8b149488158fa22f3 [file] [log] [blame]
apatrick@chromium.org8963ec22012-07-09 22:34:06 +00001//
2// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7// BinaryStream.h: Provides binary serialization of simple types.
8
9#ifndef LIBGLESV2_BINARYSTREAM_H_
10#define LIBGLESV2_BINARYSTREAM_H_
11
12#include <string>
13#include <vector>
14
15#include "common/angleutils.h"
16
17namespace gl
18{
19
20class BinaryInputStream
21{
22 public:
23 BinaryInputStream(const void *data, size_t length)
24 {
25 mError = false;
26 mOffset = 0;
27 mData = static_cast<const char*>(data);
28 mLength = length;
29 }
30
31 template <typename T>
32 void read(T *v, size_t num)
33 {
34 union
35 {
36 T dummy; // Compilation error for non-trivial types
37 } dummy;
38 (void) dummy;
39
40 if (mError)
41 {
42 return;
43 }
44
45 size_t length = num * sizeof(T);
46
47 if (mOffset + length > mLength)
48 {
49 mError = true;
50 return;
51 }
52
53 memcpy(v, mData + mOffset, length);
54 mOffset += length;
55 }
56
57 template <typename T>
58 void read(T * v)
59 {
60 read(v, 1);
61 }
62
63 void read(std::string *v)
64 {
65 size_t length;
66 read(&length);
67
68 if (mError)
69 {
70 return;
71 }
72
73 if (mOffset + length > mLength)
74 {
75 mError = true;
76 return;
77 }
78
79 v->assign(mData + mOffset, length);
80 mOffset += length;
81 }
82
83 bool error() const
84 {
85 return mError;
86 }
87
88 bool endOfStream() const
89 {
90 return mOffset == mLength;
91 }
92
93 private:
94 DISALLOW_COPY_AND_ASSIGN(BinaryInputStream);
95 bool mError;
96 size_t mOffset;
97 const char *mData;
98 size_t mLength;
99};
100
101class BinaryOutputStream
102{
103 public:
104 BinaryOutputStream()
105 {
106 }
107
108 template <typename T>
109 void write(const T *v, size_t num)
110 {
111 union
112 {
113 T dummy; // Compilation error for non-trivial types
114 } dummy;
115 (void) dummy;
116
117 const char *asBytes = reinterpret_cast<const char*>(v);
118 mData.insert(mData.end(), asBytes, asBytes + num * sizeof(T));
119 }
120
121 template <typename T>
122 void write(const T &v)
123 {
124 write(&v, 1);
125 }
126
127 void write(const std::string &v)
128 {
129 size_t length = v.length();
130 write(length);
131
132 write(v.c_str(), length);
133 }
134
135 bool getData(void *buffer, size_t bufSize, size_t *length)
136 {
137 if (bufSize < mData.size())
138 {
139 if (length)
140 {
141 *length = 0;
142 }
143
144 return false;
145 }
146
147 if (length)
148 {
149 *length = mData.size();
150 }
151
152 if (mData.size())
153 {
154 memcpy(buffer, &mData[0], mData.size());
155 }
156
157 return true;
158 }
159
160 private:
161 DISALLOW_COPY_AND_ASSIGN(BinaryOutputStream);
162 std::vector<char> mData;
163};
164}
165
166#endif // LIBGLESV2_BINARYSTREAM_H_