]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Support/BinaryStreamReader.h
Merge ^/head r317971 through r318379.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Support / BinaryStreamReader.h
1 //===- BinaryStreamReader.h - Reads objects from a binary stream *- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_SUPPORT_BINARYSTREAMREADER_H
11 #define LLVM_SUPPORT_BINARYSTREAMREADER_H
12
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"
21
22 #include <string>
23 #include <type_traits>
24
25 namespace llvm {
26
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
31 /// are overridable.
32 class BinaryStreamReader {
33 public:
34   BinaryStreamReader() = default;
35   explicit BinaryStreamReader(BinaryStreamRef Stream);
36   virtual ~BinaryStreamReader() {}
37
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.
41   ///
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);
45
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.
50   ///
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);
54
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
58   /// read data.
59   ///
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!");
65
66     ArrayRef<uint8_t> Bytes;
67     if (auto EC = readBytes(Bytes, sizeof(T)))
68       return EC;
69
70     Dest = llvm::support::endian::read<T, llvm::support::unaligned>(
71         Bytes.data(), Stream.getEndian());
72     return Error::success();
73   }
74
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))
81       return EC;
82     Dest = static_cast<T>(N);
83     return Error::success();
84   }
85
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.
89   ///
90   /// \returns a success error code if the data was successfully read, otherwise
91   /// returns an appropriate error code.
92   Error readCString(StringRef &Dest);
93
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.
97   ///
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);
101
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.
105   ///
106   /// \returns a success error code if the data was successfully read, otherwise
107   /// returns an appropriate error code.
108   Error readStreamRef(BinaryStreamRef &Ref);
109
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
113   /// causes a copy.
114   ///
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);
118
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
124   /// stream.
125   ///
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)))
131       return EC;
132     Dest = reinterpret_cast<const T *>(Buffer.data());
133     return Error::success();
134   }
135
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.
142   ///
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();
151     }
152
153     if (NumElements > UINT32_MAX / sizeof(T))
154       return make_error<BinaryStreamError>(
155           stream_error_code::invalid_array_size);
156
157     if (auto EC = readBytes(Bytes, NumElements * sizeof(T)))
158       return EC;
159
160     assert(alignmentAdjustment(Bytes.data(), alignof(T)) == 0 &&
161            "Reading at invalid alignment!");
162
163     Array = ArrayRef<T>(reinterpret_cast<const T *>(Bytes.data()), NumElements);
164     return Error::success();
165   }
166
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
171   /// stream).
172   ///
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) {
177     BinaryStreamRef S;
178     if (auto EC = readStreamRef(S, Size))
179       return EC;
180     Array = VarStreamArray<T, U>(S);
181     return Error::success();
182   }
183
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
188   /// stream).
189   ///
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) {
195     BinaryStreamRef S;
196     if (auto EC = readStreamRef(S, Size))
197       return EC;
198     Array = VarStreamArray<T, U>(S, std::move(Context));
199     return Error::success();
200   }
201
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
206   /// stream).
207   ///
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) {
212     if (NumItems == 0) {
213       Array = FixedStreamArray<T>();
214       return Error::success();
215     }
216
217     if (NumItems > UINT32_MAX / sizeof(T))
218       return make_error<BinaryStreamError>(
219           stream_error_code::invalid_array_size);
220
221     BinaryStreamRef View;
222     if (auto EC = readStreamRef(View, NumItems * sizeof(T)))
223       return EC;
224
225     Array = FixedStreamArray<T>(View);
226     return Error::success();
227   }
228
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(); }
234
235   /// Advance the stream's offset by \p Amount bytes.
236   ///
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);
240
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.
243   ///
244   /// \returns the next byte in the stream.
245   uint8_t peek() const;
246
247   std::pair<BinaryStreamReader, BinaryStreamReader>
248   split(uint32_t Offset) const;
249
250 private:
251   BinaryStreamRef Stream;
252   uint32_t Offset;
253 };
254 } // namespace llvm
255
256 #endif // LLVM_SUPPORT_BINARYSTREAMREADER_H