BinaryStreamArray.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- BinaryStreamArray.h - Array backed by an arbitrary stream *- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// Lightweight arrays that are backed by an arbitrary BinaryStream. This file
  16. /// provides two different array implementations.
  17. ///
  18. /// VarStreamArray - Arrays of variable length records. The user specifies
  19. /// an Extractor type that can extract a record from a given offset and
  20. /// return the number of bytes consumed by the record.
  21. ///
  22. /// FixedStreamArray - Arrays of fixed length records. This is similar in
  23. /// spirit to ArrayRef<T>, but since it is backed by a BinaryStream, the
  24. /// elements of the array need not be laid out in contiguous memory.
  25. ///
  26. #ifndef LLVM_SUPPORT_BINARYSTREAMARRAY_H
  27. #define LLVM_SUPPORT_BINARYSTREAMARRAY_H
  28. #include "llvm/ADT/ArrayRef.h"
  29. #include "llvm/ADT/iterator.h"
  30. #include "llvm/Support/Alignment.h"
  31. #include "llvm/Support/BinaryStreamRef.h"
  32. #include "llvm/Support/Error.h"
  33. #include <cassert>
  34. #include <cstdint>
  35. namespace llvm {
  36. /// VarStreamArrayExtractor is intended to be specialized to provide customized
  37. /// extraction logic. On input it receives a BinaryStreamRef pointing to the
  38. /// beginning of the next record, but where the length of the record is not yet
  39. /// known. Upon completion, it should return an appropriate Error instance if
  40. /// a record could not be extracted, or if one could be extracted it should
  41. /// return success and set Len to the number of bytes this record occupied in
  42. /// the underlying stream, and it should fill out the fields of the value type
  43. /// Item appropriately to represent the current record.
  44. ///
  45. /// You can specialize this template for your own custom value types to avoid
  46. /// having to specify a second template argument to VarStreamArray (documented
  47. /// below).
  48. template <typename T> struct VarStreamArrayExtractor {
  49. // Method intentionally deleted. You must provide an explicit specialization
  50. // with the following method implemented.
  51. Error operator()(BinaryStreamRef Stream, uint32_t &Len,
  52. T &Item) const = delete;
  53. };
  54. /// VarStreamArray represents an array of variable length records backed by a
  55. /// stream. This could be a contiguous sequence of bytes in memory, it could
  56. /// be a file on disk, or it could be a PDB stream where bytes are stored as
  57. /// discontiguous blocks in a file. Usually it is desirable to treat arrays
  58. /// as contiguous blocks of memory, but doing so with large PDB files, for
  59. /// example, could mean allocating huge amounts of memory just to allow
  60. /// re-ordering of stream data to be contiguous before iterating over it. By
  61. /// abstracting this out, we need not duplicate this memory, and we can
  62. /// iterate over arrays in arbitrarily formatted streams. Elements are parsed
  63. /// lazily on iteration, so there is no upfront cost associated with building
  64. /// or copying a VarStreamArray, no matter how large it may be.
  65. ///
  66. /// You create a VarStreamArray by specifying a ValueType and an Extractor type.
  67. /// If you do not specify an Extractor type, you are expected to specialize
  68. /// VarStreamArrayExtractor<T> for your ValueType.
  69. ///
  70. /// By default an Extractor is default constructed in the class, but in some
  71. /// cases you might find it useful for an Extractor to maintain state across
  72. /// extractions. In this case you can provide your own Extractor through a
  73. /// secondary constructor. The following examples show various ways of
  74. /// creating a VarStreamArray.
  75. ///
  76. /// // Will use VarStreamArrayExtractor<MyType> as the extractor.
  77. /// VarStreamArray<MyType> MyTypeArray;
  78. ///
  79. /// // Will use a default-constructed MyExtractor as the extractor.
  80. /// VarStreamArray<MyType, MyExtractor> MyTypeArray2;
  81. ///
  82. /// // Will use the specific instance of MyExtractor provided.
  83. /// // MyExtractor need not be default-constructible in this case.
  84. /// MyExtractor E(SomeContext);
  85. /// VarStreamArray<MyType, MyExtractor> MyTypeArray3(E);
  86. ///
  87. template <typename ValueType, typename Extractor> class VarStreamArrayIterator;
  88. template <typename ValueType,
  89. typename Extractor = VarStreamArrayExtractor<ValueType>>
  90. class VarStreamArray {
  91. friend class VarStreamArrayIterator<ValueType, Extractor>;
  92. public:
  93. typedef VarStreamArrayIterator<ValueType, Extractor> Iterator;
  94. VarStreamArray() = default;
  95. explicit VarStreamArray(const Extractor &E) : E(E) {}
  96. explicit VarStreamArray(BinaryStreamRef Stream, uint32_t Skew = 0)
  97. : Stream(Stream), Skew(Skew) {}
  98. VarStreamArray(BinaryStreamRef Stream, const Extractor &E, uint32_t Skew = 0)
  99. : Stream(Stream), E(E), Skew(Skew) {}
  100. Iterator begin(bool *HadError = nullptr) const {
  101. return Iterator(*this, E, Skew, nullptr);
  102. }
  103. bool valid() const { return Stream.valid(); }
  104. uint32_t skew() const { return Skew; }
  105. Iterator end() const { return Iterator(E); }
  106. bool empty() const { return Stream.getLength() == 0; }
  107. VarStreamArray<ValueType, Extractor> substream(uint32_t Begin,
  108. uint32_t End) const {
  109. assert(Begin >= Skew);
  110. // We should never cut off the beginning of the stream since it might be
  111. // skewed, meaning the initial bytes are important.
  112. BinaryStreamRef NewStream = Stream.slice(0, End);
  113. return {NewStream, E, Begin};
  114. }
  115. /// given an offset into the array's underlying stream, return an
  116. /// iterator to the record at that offset. This is considered unsafe
  117. /// since the behavior is undefined if \p Offset does not refer to the
  118. /// beginning of a valid record.
  119. Iterator at(uint32_t Offset) const {
  120. return Iterator(*this, E, Offset, nullptr);
  121. }
  122. const Extractor &getExtractor() const { return E; }
  123. Extractor &getExtractor() { return E; }
  124. BinaryStreamRef getUnderlyingStream() const { return Stream; }
  125. void setUnderlyingStream(BinaryStreamRef NewStream, uint32_t NewSkew = 0) {
  126. Stream = NewStream;
  127. Skew = NewSkew;
  128. }
  129. void drop_front() { Skew += begin()->length(); }
  130. private:
  131. BinaryStreamRef Stream;
  132. Extractor E;
  133. uint32_t Skew = 0;
  134. };
  135. template <typename ValueType, typename Extractor>
  136. class VarStreamArrayIterator
  137. : public iterator_facade_base<VarStreamArrayIterator<ValueType, Extractor>,
  138. std::forward_iterator_tag, const ValueType> {
  139. typedef VarStreamArrayIterator<ValueType, Extractor> IterType;
  140. typedef VarStreamArray<ValueType, Extractor> ArrayType;
  141. public:
  142. VarStreamArrayIterator(const ArrayType &Array, const Extractor &E,
  143. uint32_t Offset, bool *HadError)
  144. : IterRef(Array.Stream.drop_front(Offset)), Extract(E),
  145. Array(&Array), AbsOffset(Offset), HadError(HadError) {
  146. if (IterRef.getLength() == 0)
  147. moveToEnd();
  148. else {
  149. auto EC = Extract(IterRef, ThisLen, ThisValue);
  150. if (EC) {
  151. consumeError(std::move(EC));
  152. markError();
  153. }
  154. }
  155. }
  156. VarStreamArrayIterator() = default;
  157. explicit VarStreamArrayIterator(const Extractor &E) : Extract(E) {}
  158. ~VarStreamArrayIterator() = default;
  159. bool operator==(const IterType &R) const {
  160. if (Array && R.Array) {
  161. // Both have a valid array, make sure they're same.
  162. assert(Array == R.Array);
  163. return IterRef == R.IterRef;
  164. }
  165. // Both iterators are at the end.
  166. if (!Array && !R.Array)
  167. return true;
  168. // One is not at the end and one is.
  169. return false;
  170. }
  171. const ValueType &operator*() const {
  172. assert(Array && !HasError);
  173. return ThisValue;
  174. }
  175. IterType &operator+=(unsigned N) {
  176. for (unsigned I = 0; I < N; ++I) {
  177. // We are done with the current record, discard it so that we are
  178. // positioned at the next record.
  179. AbsOffset += ThisLen;
  180. IterRef = IterRef.drop_front(ThisLen);
  181. if (IterRef.getLength() == 0) {
  182. // There is nothing after the current record, we must make this an end
  183. // iterator.
  184. moveToEnd();
  185. } else {
  186. // There is some data after the current record.
  187. auto EC = Extract(IterRef, ThisLen, ThisValue);
  188. if (EC) {
  189. consumeError(std::move(EC));
  190. markError();
  191. } else if (ThisLen == 0) {
  192. // An empty record? Make this an end iterator.
  193. moveToEnd();
  194. }
  195. }
  196. }
  197. return *this;
  198. }
  199. uint32_t offset() const { return AbsOffset; }
  200. uint32_t getRecordLength() const { return ThisLen; }
  201. private:
  202. void moveToEnd() {
  203. Array = nullptr;
  204. ThisLen = 0;
  205. }
  206. void markError() {
  207. moveToEnd();
  208. HasError = true;
  209. if (HadError != nullptr)
  210. *HadError = true;
  211. }
  212. ValueType ThisValue;
  213. BinaryStreamRef IterRef;
  214. Extractor Extract;
  215. const ArrayType *Array{nullptr};
  216. uint32_t ThisLen{0};
  217. uint32_t AbsOffset{0};
  218. bool HasError{false};
  219. bool *HadError{nullptr};
  220. };
  221. template <typename T> class FixedStreamArrayIterator;
  222. /// FixedStreamArray is similar to VarStreamArray, except with each record
  223. /// having a fixed-length. As with VarStreamArray, there is no upfront
  224. /// cost associated with building or copying a FixedStreamArray, as the
  225. /// memory for each element is not read from the backing stream until that
  226. /// element is iterated.
  227. template <typename T> class FixedStreamArray {
  228. friend class FixedStreamArrayIterator<T>;
  229. public:
  230. typedef FixedStreamArrayIterator<T> Iterator;
  231. FixedStreamArray() = default;
  232. explicit FixedStreamArray(BinaryStreamRef Stream) : Stream(Stream) {
  233. assert(Stream.getLength() % sizeof(T) == 0);
  234. }
  235. bool operator==(const FixedStreamArray<T> &Other) const {
  236. return Stream == Other.Stream;
  237. }
  238. bool operator!=(const FixedStreamArray<T> &Other) const {
  239. return !(*this == Other);
  240. }
  241. FixedStreamArray(const FixedStreamArray &) = default;
  242. FixedStreamArray &operator=(const FixedStreamArray &) = default;
  243. const T &operator[](uint32_t Index) const {
  244. assert(Index < size());
  245. uint32_t Off = Index * sizeof(T);
  246. ArrayRef<uint8_t> Data;
  247. if (auto EC = Stream.readBytes(Off, sizeof(T), Data)) {
  248. assert(false && "Unexpected failure reading from stream");
  249. // This should never happen since we asserted that the stream length was
  250. // an exact multiple of the element size.
  251. consumeError(std::move(EC));
  252. }
  253. assert(isAddrAligned(Align::Of<T>(), Data.data()));
  254. return *reinterpret_cast<const T *>(Data.data());
  255. }
  256. uint32_t size() const { return Stream.getLength() / sizeof(T); }
  257. bool empty() const { return size() == 0; }
  258. FixedStreamArrayIterator<T> begin() const {
  259. return FixedStreamArrayIterator<T>(*this, 0);
  260. }
  261. FixedStreamArrayIterator<T> end() const {
  262. return FixedStreamArrayIterator<T>(*this, size());
  263. }
  264. const T &front() const { return *begin(); }
  265. const T &back() const {
  266. FixedStreamArrayIterator<T> I = end();
  267. return *(--I);
  268. }
  269. BinaryStreamRef getUnderlyingStream() const { return Stream; }
  270. private:
  271. BinaryStreamRef Stream;
  272. };
  273. template <typename T>
  274. class FixedStreamArrayIterator
  275. : public iterator_facade_base<FixedStreamArrayIterator<T>,
  276. std::random_access_iterator_tag, const T> {
  277. public:
  278. FixedStreamArrayIterator(const FixedStreamArray<T> &Array, uint32_t Index)
  279. : Array(Array), Index(Index) {}
  280. FixedStreamArrayIterator(const FixedStreamArrayIterator<T> &Other)
  281. : Array(Other.Array), Index(Other.Index) {}
  282. FixedStreamArrayIterator<T> &
  283. operator=(const FixedStreamArrayIterator<T> &Other) {
  284. Array = Other.Array;
  285. Index = Other.Index;
  286. return *this;
  287. }
  288. const T &operator*() const { return Array[Index]; }
  289. const T &operator*() { return Array[Index]; }
  290. bool operator==(const FixedStreamArrayIterator<T> &R) const {
  291. assert(Array == R.Array);
  292. return (Index == R.Index) && (Array == R.Array);
  293. }
  294. FixedStreamArrayIterator<T> &operator+=(std::ptrdiff_t N) {
  295. Index += N;
  296. return *this;
  297. }
  298. FixedStreamArrayIterator<T> &operator-=(std::ptrdiff_t N) {
  299. assert(std::ptrdiff_t(Index) >= N);
  300. Index -= N;
  301. return *this;
  302. }
  303. std::ptrdiff_t operator-(const FixedStreamArrayIterator<T> &R) const {
  304. assert(Array == R.Array);
  305. assert(Index >= R.Index);
  306. return Index - R.Index;
  307. }
  308. bool operator<(const FixedStreamArrayIterator<T> &RHS) const {
  309. assert(Array == RHS.Array);
  310. return Index < RHS.Index;
  311. }
  312. private:
  313. FixedStreamArray<T> Array;
  314. uint32_t Index;
  315. };
  316. } // namespace llvm
  317. #endif // LLVM_SUPPORT_BINARYSTREAMARRAY_H
  318. #ifdef __GNUC__
  319. #pragma GCC diagnostic pop
  320. #endif