BinaryStreamRef.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- BinaryStreamRef.h - A copyable reference to a 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. #ifndef LLVM_SUPPORT_BINARYSTREAMREF_H
  14. #define LLVM_SUPPORT_BINARYSTREAMREF_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/Support/BinaryStream.h"
  18. #include "llvm/Support/BinaryStreamError.h"
  19. #include "llvm/Support/Error.h"
  20. #include <cstdint>
  21. #include <memory>
  22. namespace llvm {
  23. /// Common stuff for mutable and immutable StreamRefs.
  24. template <class RefType, class StreamType> class BinaryStreamRefBase {
  25. protected:
  26. BinaryStreamRefBase() = default;
  27. explicit BinaryStreamRefBase(StreamType &BorrowedImpl)
  28. : BorrowedImpl(&BorrowedImpl), ViewOffset(0) {
  29. if (!(BorrowedImpl.getFlags() & BSF_Append))
  30. Length = BorrowedImpl.getLength();
  31. }
  32. BinaryStreamRefBase(std::shared_ptr<StreamType> SharedImpl, uint64_t Offset,
  33. Optional<uint64_t> Length)
  34. : SharedImpl(SharedImpl), BorrowedImpl(SharedImpl.get()),
  35. ViewOffset(Offset), Length(Length) {}
  36. BinaryStreamRefBase(StreamType &BorrowedImpl, uint64_t Offset,
  37. Optional<uint64_t> Length)
  38. : BorrowedImpl(&BorrowedImpl), ViewOffset(Offset), Length(Length) {}
  39. BinaryStreamRefBase(const BinaryStreamRefBase &Other) = default;
  40. BinaryStreamRefBase &operator=(const BinaryStreamRefBase &Other) = default;
  41. BinaryStreamRefBase &operator=(BinaryStreamRefBase &&Other) = default;
  42. BinaryStreamRefBase(BinaryStreamRefBase &&Other) = default;
  43. public:
  44. llvm::support::endianness getEndian() const {
  45. return BorrowedImpl->getEndian();
  46. }
  47. uint64_t getLength() const {
  48. if (Length.hasValue())
  49. return *Length;
  50. return BorrowedImpl ? (BorrowedImpl->getLength() - ViewOffset) : 0;
  51. }
  52. /// Return a new BinaryStreamRef with the first \p N elements removed. If
  53. /// this BinaryStreamRef is length-tracking, then the resulting one will be
  54. /// too.
  55. RefType drop_front(uint64_t N) const {
  56. if (!BorrowedImpl)
  57. return RefType();
  58. N = std::min(N, getLength());
  59. RefType Result(static_cast<const RefType &>(*this));
  60. if (N == 0)
  61. return Result;
  62. Result.ViewOffset += N;
  63. if (Result.Length.hasValue())
  64. *Result.Length -= N;
  65. return Result;
  66. }
  67. /// Return a new BinaryStreamRef with the last \p N elements removed. If
  68. /// this BinaryStreamRef is length-tracking and \p N is greater than 0, then
  69. /// this BinaryStreamRef will no longer length-track.
  70. RefType drop_back(uint64_t N) const {
  71. if (!BorrowedImpl)
  72. return RefType();
  73. RefType Result(static_cast<const RefType &>(*this));
  74. N = std::min(N, getLength());
  75. if (N == 0)
  76. return Result;
  77. // Since we're dropping non-zero bytes from the end, stop length-tracking
  78. // by setting the length of the resulting StreamRef to an explicit value.
  79. if (!Result.Length.hasValue())
  80. Result.Length = getLength();
  81. *Result.Length -= N;
  82. return Result;
  83. }
  84. /// Return a new BinaryStreamRef with only the first \p N elements remaining.
  85. RefType keep_front(uint64_t N) const {
  86. assert(N <= getLength());
  87. return drop_back(getLength() - N);
  88. }
  89. /// Return a new BinaryStreamRef with only the last \p N elements remaining.
  90. RefType keep_back(uint64_t N) const {
  91. assert(N <= getLength());
  92. return drop_front(getLength() - N);
  93. }
  94. /// Return a new BinaryStreamRef with the first and last \p N elements
  95. /// removed.
  96. RefType drop_symmetric(uint64_t N) const {
  97. return drop_front(N).drop_back(N);
  98. }
  99. /// Return a new BinaryStreamRef with the first \p Offset elements removed,
  100. /// and retaining exactly \p Len elements.
  101. RefType slice(uint64_t Offset, uint64_t Len) const {
  102. return drop_front(Offset).keep_front(Len);
  103. }
  104. bool valid() const { return BorrowedImpl != nullptr; }
  105. friend bool operator==(const RefType &LHS, const RefType &RHS) {
  106. if (LHS.BorrowedImpl != RHS.BorrowedImpl)
  107. return false;
  108. if (LHS.ViewOffset != RHS.ViewOffset)
  109. return false;
  110. if (LHS.Length != RHS.Length)
  111. return false;
  112. return true;
  113. }
  114. protected:
  115. Error checkOffsetForRead(uint64_t Offset, uint64_t DataSize) const {
  116. if (Offset > getLength())
  117. return make_error<BinaryStreamError>(stream_error_code::invalid_offset);
  118. if (getLength() < DataSize + Offset)
  119. return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
  120. return Error::success();
  121. }
  122. std::shared_ptr<StreamType> SharedImpl;
  123. StreamType *BorrowedImpl = nullptr;
  124. uint64_t ViewOffset = 0;
  125. Optional<uint64_t> Length;
  126. };
  127. /// BinaryStreamRef is to BinaryStream what ArrayRef is to an Array. It
  128. /// provides copy-semantics and read only access to a "window" of the underlying
  129. /// BinaryStream. Note that BinaryStreamRef is *not* a BinaryStream. That is to
  130. /// say, it does not inherit and override the methods of BinaryStream. In
  131. /// general, you should not pass around pointers or references to BinaryStreams
  132. /// and use inheritance to achieve polymorphism. Instead, you should pass
  133. /// around BinaryStreamRefs by value and achieve polymorphism that way.
  134. class BinaryStreamRef
  135. : public BinaryStreamRefBase<BinaryStreamRef, BinaryStream> {
  136. friend BinaryStreamRefBase<BinaryStreamRef, BinaryStream>;
  137. friend class WritableBinaryStreamRef;
  138. BinaryStreamRef(std::shared_ptr<BinaryStream> Impl, uint64_t ViewOffset,
  139. Optional<uint64_t> Length)
  140. : BinaryStreamRefBase(Impl, ViewOffset, Length) {}
  141. public:
  142. BinaryStreamRef() = default;
  143. BinaryStreamRef(BinaryStream &Stream);
  144. BinaryStreamRef(BinaryStream &Stream, uint64_t Offset,
  145. Optional<uint64_t> Length);
  146. explicit BinaryStreamRef(ArrayRef<uint8_t> Data,
  147. llvm::support::endianness Endian);
  148. explicit BinaryStreamRef(StringRef Data, llvm::support::endianness Endian);
  149. BinaryStreamRef(const BinaryStreamRef &Other) = default;
  150. BinaryStreamRef &operator=(const BinaryStreamRef &Other) = default;
  151. BinaryStreamRef(BinaryStreamRef &&Other) = default;
  152. BinaryStreamRef &operator=(BinaryStreamRef &&Other) = default;
  153. // Use BinaryStreamRef.slice() instead.
  154. BinaryStreamRef(BinaryStreamRef &S, uint64_t Offset,
  155. uint64_t Length) = delete;
  156. /// Given an Offset into this StreamRef and a Size, return a reference to a
  157. /// buffer owned by the stream.
  158. ///
  159. /// \returns a success error code if the entire range of data is within the
  160. /// bounds of this BinaryStreamRef's view and the implementation could read
  161. /// the data, and an appropriate error code otherwise.
  162. Error readBytes(uint64_t Offset, uint64_t Size,
  163. ArrayRef<uint8_t> &Buffer) const;
  164. /// Given an Offset into this BinaryStreamRef, return a reference to the
  165. /// largest buffer the stream could support without necessitating a copy.
  166. ///
  167. /// \returns a success error code if implementation could read the data,
  168. /// and an appropriate error code otherwise.
  169. Error readLongestContiguousChunk(uint64_t Offset,
  170. ArrayRef<uint8_t> &Buffer) const;
  171. };
  172. struct BinarySubstreamRef {
  173. uint64_t Offset = 0; // Offset in the parent stream
  174. BinaryStreamRef StreamData; // Stream Data
  175. BinarySubstreamRef slice(uint64_t Off, uint64_t Size) const {
  176. BinaryStreamRef SubSub = StreamData.slice(Off, Size);
  177. return {Off + Offset, SubSub};
  178. }
  179. BinarySubstreamRef drop_front(uint64_t N) const {
  180. return slice(N, size() - N);
  181. }
  182. BinarySubstreamRef keep_front(uint64_t N) const { return slice(0, N); }
  183. std::pair<BinarySubstreamRef, BinarySubstreamRef> split(uint64_t Off) const {
  184. return std::make_pair(keep_front(Off), drop_front(Off));
  185. }
  186. uint64_t size() const { return StreamData.getLength(); }
  187. bool empty() const { return size() == 0; }
  188. };
  189. class WritableBinaryStreamRef
  190. : public BinaryStreamRefBase<WritableBinaryStreamRef,
  191. WritableBinaryStream> {
  192. friend BinaryStreamRefBase<WritableBinaryStreamRef, WritableBinaryStream>;
  193. WritableBinaryStreamRef(std::shared_ptr<WritableBinaryStream> Impl,
  194. uint64_t ViewOffset, Optional<uint64_t> Length)
  195. : BinaryStreamRefBase(Impl, ViewOffset, Length) {}
  196. Error checkOffsetForWrite(uint64_t Offset, uint64_t DataSize) const {
  197. if (!(BorrowedImpl->getFlags() & BSF_Append))
  198. return checkOffsetForRead(Offset, DataSize);
  199. if (Offset > getLength())
  200. return make_error<BinaryStreamError>(stream_error_code::invalid_offset);
  201. return Error::success();
  202. }
  203. public:
  204. WritableBinaryStreamRef() = default;
  205. WritableBinaryStreamRef(WritableBinaryStream &Stream);
  206. WritableBinaryStreamRef(WritableBinaryStream &Stream, uint64_t Offset,
  207. Optional<uint64_t> Length);
  208. explicit WritableBinaryStreamRef(MutableArrayRef<uint8_t> Data,
  209. llvm::support::endianness Endian);
  210. WritableBinaryStreamRef(const WritableBinaryStreamRef &Other) = default;
  211. WritableBinaryStreamRef &
  212. operator=(const WritableBinaryStreamRef &Other) = default;
  213. WritableBinaryStreamRef(WritableBinaryStreamRef &&Other) = default;
  214. WritableBinaryStreamRef &operator=(WritableBinaryStreamRef &&Other) = default;
  215. // Use WritableBinaryStreamRef.slice() instead.
  216. WritableBinaryStreamRef(WritableBinaryStreamRef &S, uint64_t Offset,
  217. uint64_t Length) = delete;
  218. /// Given an Offset into this WritableBinaryStreamRef and some input data,
  219. /// writes the data to the underlying stream.
  220. ///
  221. /// \returns a success error code if the data could fit within the underlying
  222. /// stream at the specified location and the implementation could write the
  223. /// data, and an appropriate error code otherwise.
  224. Error writeBytes(uint64_t Offset, ArrayRef<uint8_t> Data) const;
  225. /// Conver this WritableBinaryStreamRef to a read-only BinaryStreamRef.
  226. operator BinaryStreamRef() const;
  227. /// For buffered streams, commits changes to the backing store.
  228. Error commit();
  229. };
  230. } // end namespace llvm
  231. #endif // LLVM_SUPPORT_BINARYSTREAMREF_H
  232. #ifdef __GNUC__
  233. #pragma GCC diagnostic pop
  234. #endif