1 //===- BinaryStreamReader.h - Reads objects from a binary stream *- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_SUPPORT_BINARYSTREAMREADER_H
11 #define LLVM_SUPPORT_BINARYSTREAMREADER_H
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/Support/BinaryStreamArray.h"
16 #include "llvm/Support/BinaryStreamRef.h"
17 #include "llvm/Support/Endian.h"
18 #include "llvm/Support/Error.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/type_traits.h"
23 #include <type_traits>
27 /// \brief Provides read only access to a subclass of `BinaryStream`. Provides
28 /// bounds checking and helpers for writing certain common data types such as
29 /// null-terminated strings, integers in various flavors of endianness, etc.
30 /// Can be subclassed to provide reading of custom datatypes, although no
32 class BinaryStreamReader {
34 BinaryStreamReader() = default;
35 explicit BinaryStreamReader(BinaryStreamRef Stream);
36 virtual ~BinaryStreamReader() {}
38 /// Read as much as possible from the underlying string at the current offset
39 /// without invoking a copy, and set \p Buffer to the resulting data slice.
40 /// Updates the stream's offset to point after the newly read data.
42 /// \returns a success error code if the data was successfully read, otherwise
43 /// returns an appropriate error code.
44 Error readLongestContiguousChunk(ArrayRef<uint8_t> &Buffer);
46 /// Read \p Size bytes from the underlying stream at the current offset and
47 /// and set \p Buffer to the resulting data slice. Whether a copy occurs
48 /// depends on the implementation of the underlying stream. Updates the
49 /// stream's offset to point after the newly read data.
51 /// \returns a success error code if the data was successfully read, otherwise
52 /// returns an appropriate error code.
53 Error readBytes(ArrayRef<uint8_t> &Buffer, uint32_t Size);
55 /// Read an integer of the specified endianness into \p Dest and update the
56 /// stream's offset. The data is always copied from the stream's underlying
57 /// buffer into \p Dest. Updates the stream's offset to point after the newly
60 /// \returns a success error code if the data was successfully read, otherwise
61 /// returns an appropriate error code.
62 template <typename T> Error readInteger(T &Dest) {
63 static_assert(std::is_integral<T>::value,
64 "Cannot call readInteger with non-integral value!");
66 ArrayRef<uint8_t> Bytes;
67 if (auto EC = readBytes(Bytes, sizeof(T)))
70 Dest = llvm::support::endian::read<T, llvm::support::unaligned>(
71 Bytes.data(), Stream.getEndian());
72 return Error::success();
75 /// Similar to readInteger.
76 template <typename T> Error readEnum(T &Dest) {
77 static_assert(std::is_enum<T>::value,
78 "Cannot call readEnum with non-enum value!");
79 typename std::underlying_type<T>::type N;
80 if (auto EC = readInteger(N))
82 Dest = static_cast<T>(N);
83 return Error::success();
86 /// Read a null terminated string from \p Dest. Whether a copy occurs depends
87 /// on the implementation of the underlying stream. Updates the stream's
88 /// offset to point after the newly read data.
90 /// \returns a success error code if the data was successfully read, otherwise
91 /// returns an appropriate error code.
92 Error readCString(StringRef &Dest);
94 /// Read a \p Length byte string into \p Dest. Whether a copy occurs depends
95 /// on the implementation of the underlying stream. Updates the stream's
96 /// offset to point after the newly read data.
98 /// \returns a success error code if the data was successfully read, otherwise
99 /// returns an appropriate error code.
100 Error readFixedString(StringRef &Dest, uint32_t Length);
102 /// Read the entire remainder of the underlying stream into \p Ref. This is
103 /// equivalent to calling getUnderlyingStream().slice(Offset). Updates the
104 /// stream's offset to point to the end of the stream. Never causes a copy.
106 /// \returns a success error code if the data was successfully read, otherwise
107 /// returns an appropriate error code.
108 Error readStreamRef(BinaryStreamRef &Ref);
110 /// Read \p Length bytes from the underlying stream into \p Ref. This is
111 /// equivalent to calling getUnderlyingStream().slice(Offset, Length).
112 /// Updates the stream's offset to point after the newly read object. Never
115 /// \returns a success error code if the data was successfully read, otherwise
116 /// returns an appropriate error code.
117 Error readStreamRef(BinaryStreamRef &Ref, uint32_t Length);
119 /// Get a pointer to an object of type T from the underlying stream, as if by
120 /// memcpy, and store the result into \p Dest. It is up to the caller to
121 /// ensure that objects of type T can be safely treated in this manner.
122 /// Updates the stream's offset to point after the newly read object. Whether
123 /// a copy occurs depends upon the implementation of the underlying
126 /// \returns a success error code if the data was successfully read, otherwise
127 /// returns an appropriate error code.
128 template <typename T> Error readObject(const T *&Dest) {
129 ArrayRef<uint8_t> Buffer;
130 if (auto EC = readBytes(Buffer, sizeof(T)))
132 Dest = reinterpret_cast<const T *>(Buffer.data());
133 return Error::success();
136 /// Get a reference to a \p NumElements element array of objects of type T
137 /// from the underlying stream as if by memcpy, and store the resulting array
138 /// slice into \p array. It is up to the caller to ensure that objects of
139 /// type T can be safely treated in this manner. Updates the stream's offset
140 /// to point after the newly read object. Whether a copy occurs depends upon
141 /// the implementation of the underlying stream.
143 /// \returns a success error code if the data was successfully read, otherwise
144 /// returns an appropriate error code.
145 template <typename T>
146 Error readArray(ArrayRef<T> &Array, uint32_t NumElements) {
147 ArrayRef<uint8_t> Bytes;
148 if (NumElements == 0) {
149 Array = ArrayRef<T>();
150 return Error::success();
153 if (NumElements > UINT32_MAX / sizeof(T))
154 return make_error<BinaryStreamError>(
155 stream_error_code::invalid_array_size);
157 if (auto EC = readBytes(Bytes, NumElements * sizeof(T)))
160 assert(alignmentAdjustment(Bytes.data(), alignof(T)) == 0 &&
161 "Reading at invalid alignment!");
163 Array = ArrayRef<T>(reinterpret_cast<const T *>(Bytes.data()), NumElements);
164 return Error::success();
167 /// Read a VarStreamArray of size \p Size bytes and store the result into
168 /// \p Array. Updates the stream's offset to point after the newly read
169 /// array. Never causes a copy (although iterating the elements of the
170 /// VarStreamArray may, depending upon the implementation of the underlying
173 /// \returns a success error code if the data was successfully read, otherwise
174 /// returns an appropriate error code.
175 template <typename T, typename U>
176 Error readArray(VarStreamArray<T, U> &Array, uint32_t Size) {
178 if (auto EC = readStreamRef(S, Size))
180 Array = VarStreamArray<T, U>(S);
181 return Error::success();
184 /// Read a VarStreamArray of size \p Size bytes and store the result into
185 /// \p Array. Updates the stream's offset to point after the newly read
186 /// array. Never causes a copy (although iterating the elements of the
187 /// VarStreamArray may, depending upon the implementation of the underlying
190 /// \returns a success error code if the data was successfully read, otherwise
191 /// returns an appropriate error code.
192 template <typename T, typename U, typename ContextType>
193 Error readArray(VarStreamArray<T, U> &Array, uint32_t Size,
194 ContextType &&Context) {
196 if (auto EC = readStreamRef(S, Size))
198 Array = VarStreamArray<T, U>(S, std::move(Context));
199 return Error::success();
202 /// Read a FixedStreamArray of \p NumItems elements and store the result into
203 /// \p Array. Updates the stream's offset to point after the newly read
204 /// array. Never causes a copy (although iterating the elements of the
205 /// FixedStreamArray may, depending upon the implementation of the underlying
208 /// \returns a success error code if the data was successfully read, otherwise
209 /// returns an appropriate error code.
210 template <typename T>
211 Error readArray(FixedStreamArray<T> &Array, uint32_t NumItems) {
213 Array = FixedStreamArray<T>();
214 return Error::success();
217 if (NumItems > UINT32_MAX / sizeof(T))
218 return make_error<BinaryStreamError>(
219 stream_error_code::invalid_array_size);
221 BinaryStreamRef View;
222 if (auto EC = readStreamRef(View, NumItems * sizeof(T)))
225 Array = FixedStreamArray<T>(View);
226 return Error::success();
229 bool empty() const { return bytesRemaining() == 0; }
230 void setOffset(uint32_t Off) { Offset = Off; }
231 uint32_t getOffset() const { return Offset; }
232 uint32_t getLength() const { return Stream.getLength(); }
233 uint32_t bytesRemaining() const { return getLength() - getOffset(); }
235 /// Advance the stream's offset by \p Amount bytes.
237 /// \returns a success error code if at least \p Amount bytes remain in the
238 /// stream, otherwise returns an appropriate error code.
239 Error skip(uint32_t Amount);
241 /// Examine the next byte of the underlying stream without advancing the
242 /// stream's offset. If the stream is empty the behavior is undefined.
244 /// \returns the next byte in the stream.
245 uint8_t peek() const;
247 std::pair<BinaryStreamReader, BinaryStreamReader>
248 split(uint32_t Offset) const;
251 BinaryStreamRef Stream;
256 #endif // LLVM_SUPPORT_BINARYSTREAMREADER_H