StreamReader.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Defines the StreamReader class which reads data from
  35. * a binary stream with a well-defined endianness.
  36. */
  37. #pragma once
  38. #ifndef AI_STREAMREADER_H_INCLUDED
  39. #define AI_STREAMREADER_H_INCLUDED
  40. #ifdef __GNUC__
  41. # pragma GCC system_header
  42. #endif
  43. #include <assimp/ByteSwapper.h>
  44. #include <assimp/Exceptional.h>
  45. #include <assimp/IOStream.hpp>
  46. #include <memory>
  47. namespace Assimp {
  48. // --------------------------------------------------------------------------------------------
  49. /** Wrapper class around IOStream to allow for consistent reading of binary data in both
  50. * little and big endian format. Don't attempt to instance the template directly. Use
  51. * StreamReaderLE to read from a little-endian stream and StreamReaderBE to read from a
  52. * BE stream. The class expects that the endianness of any input data is known at
  53. * compile-time, which should usually be true (#BaseImporter::ConvertToUTF8 implements
  54. * runtime endianness conversions for text files).
  55. *
  56. * XXX switch from unsigned int for size types to size_t? or ptrdiff_t?*/
  57. // --------------------------------------------------------------------------------------------
  58. template <bool SwapEndianness = false, bool RuntimeSwitch = false>
  59. class StreamReader {
  60. public:
  61. using diff = size_t;
  62. using pos = size_t;
  63. // ---------------------------------------------------------------------
  64. /** Construction from a given stream with a well-defined endianness.
  65. *
  66. * The StreamReader holds a permanent strong reference to the
  67. * stream, which is released upon destruction.
  68. * @param stream Input stream. The stream is not restarted if
  69. * its file pointer is not at 0. Instead, the stream reader
  70. * reads from the current position to the end of the stream.
  71. * @param le If @c RuntimeSwitch is true: specifies whether the
  72. * stream is in little endian byte order. Otherwise the
  73. * endianness information is contained in the @c SwapEndianness
  74. * template parameter and this parameter is meaningless. */
  75. StreamReader(std::shared_ptr<IOStream> stream, bool le = false) :
  76. mStream(stream),
  77. mBuffer(nullptr),
  78. mCurrent(nullptr),
  79. mEnd(nullptr),
  80. mLimit(nullptr),
  81. mLe(le) {
  82. ai_assert(stream);
  83. InternBegin();
  84. }
  85. // ---------------------------------------------------------------------
  86. StreamReader(IOStream *stream, bool le = false) :
  87. mStream(std::shared_ptr<IOStream>(stream)),
  88. mBuffer(nullptr),
  89. mCurrent(nullptr),
  90. mEnd(nullptr),
  91. mLimit(nullptr),
  92. mLe(le) {
  93. ai_assert(nullptr != stream);
  94. InternBegin();
  95. }
  96. // ---------------------------------------------------------------------
  97. ~StreamReader() {
  98. delete[] mBuffer;
  99. }
  100. // deprecated, use overloaded operator>> instead
  101. // ---------------------------------------------------------------------
  102. /// Read a float from the stream.
  103. float GetF4() {
  104. return Get<float>();
  105. }
  106. // ---------------------------------------------------------------------
  107. /// Read a double from the stream.
  108. double GetF8() {
  109. return Get<double>();
  110. }
  111. // ---------------------------------------------------------------------
  112. /** Read a signed 16 bit integer from the stream */
  113. int16_t GetI2() {
  114. return Get<int16_t>();
  115. }
  116. // ---------------------------------------------------------------------
  117. /** Read a signed 8 bit integer from the stream */
  118. int8_t GetI1() {
  119. return Get<int8_t>();
  120. }
  121. // ---------------------------------------------------------------------
  122. /** Read an signed 32 bit integer from the stream */
  123. int32_t GetI4() {
  124. return Get<int32_t>();
  125. }
  126. // ---------------------------------------------------------------------
  127. /** Read a signed 64 bit integer from the stream */
  128. int64_t GetI8() {
  129. return Get<int64_t>();
  130. }
  131. // ---------------------------------------------------------------------
  132. /** Read a unsigned 16 bit integer from the stream */
  133. uint16_t GetU2() {
  134. return Get<uint16_t>();
  135. }
  136. // ---------------------------------------------------------------------
  137. /// Read a unsigned 8 bit integer from the stream
  138. uint8_t GetU1() {
  139. return Get<uint8_t>();
  140. }
  141. // ---------------------------------------------------------------------
  142. /// Read an unsigned 32 bit integer from the stream
  143. uint32_t GetU4() {
  144. return Get<uint32_t>();
  145. }
  146. // ---------------------------------------------------------------------
  147. /// Read a unsigned 64 bit integer from the stream
  148. uint64_t GetU8() {
  149. return Get<uint64_t>();
  150. }
  151. // ---------------------------------------------------------------------
  152. /// Get the remaining stream size (to the end of the stream)
  153. size_t GetRemainingSize() const {
  154. return (unsigned int)(mEnd - mCurrent);
  155. }
  156. // ---------------------------------------------------------------------
  157. /** Get the remaining stream size (to the current read limit). The
  158. * return value is the remaining size of the stream if no custom
  159. * read limit has been set. */
  160. size_t GetRemainingSizeToLimit() const {
  161. return (unsigned int)(mLimit - mCurrent);
  162. }
  163. // ---------------------------------------------------------------------
  164. /** Increase the file pointer (relative seeking) */
  165. void IncPtr(intptr_t plus) {
  166. mCurrent += plus;
  167. if (mCurrent > mLimit) {
  168. throw DeadlyImportError("End of file or read limit was reached");
  169. }
  170. }
  171. // ---------------------------------------------------------------------
  172. /** Get the current file pointer */
  173. int8_t *GetPtr() const {
  174. return mCurrent;
  175. }
  176. // ---------------------------------------------------------------------
  177. /** Set current file pointer (Get it from #GetPtr). This is if you
  178. * prefer to do pointer arithmetic on your own or want to copy
  179. * large chunks of data at once.
  180. * @param p The new pointer, which is validated against the size
  181. * limit and buffer boundaries. */
  182. void SetPtr(int8_t *p) {
  183. mCurrent = p;
  184. if (mCurrent > mLimit || mCurrent < mBuffer) {
  185. throw DeadlyImportError("End of file or read limit was reached");
  186. }
  187. }
  188. // ---------------------------------------------------------------------
  189. /** Copy n bytes to an external buffer
  190. * @param out Destination for copying
  191. * @param bytes Number of bytes to copy */
  192. void CopyAndAdvance(void *out, size_t bytes) {
  193. int8_t *ur = GetPtr();
  194. SetPtr(ur + bytes); // fire exception if eof
  195. ::memcpy(out, ur, bytes);
  196. }
  197. /// @brief Get the current offset from the beginning of the file
  198. int GetCurrentPos() const {
  199. return (unsigned int)(mCurrent - mBuffer);
  200. }
  201. void SetCurrentPos(size_t pos) {
  202. SetPtr(mBuffer + pos);
  203. }
  204. // ---------------------------------------------------------------------
  205. /** Setup a temporary read limit
  206. *
  207. * @param limit Maximum number of bytes to be read from
  208. * the beginning of the file. Specifying UINT_MAX
  209. * resets the limit to the original end of the stream.
  210. * Returns the previously set limit. */
  211. unsigned int SetReadLimit(unsigned int _limit) {
  212. unsigned int prev = GetReadLimit();
  213. if (UINT_MAX == _limit) {
  214. mLimit = mEnd;
  215. return prev;
  216. }
  217. mLimit = mBuffer + _limit;
  218. if (mLimit > mEnd) {
  219. throw DeadlyImportError("StreamReader: Invalid read limit");
  220. }
  221. return prev;
  222. }
  223. // ---------------------------------------------------------------------
  224. /** Get the current read limit in bytes. Reading over this limit
  225. * accidentally raises an exception. */
  226. unsigned int GetReadLimit() const {
  227. return (unsigned int)(mLimit - mBuffer);
  228. }
  229. // ---------------------------------------------------------------------
  230. /** Skip to the read limit in bytes. Reading over this limit
  231. * accidentally raises an exception. */
  232. void SkipToReadLimit() {
  233. mCurrent = mLimit;
  234. }
  235. // ---------------------------------------------------------------------
  236. /** overload operator>> and allow chaining of >> ops. */
  237. template <typename T>
  238. StreamReader &operator>>(T &f) {
  239. f = Get<T>();
  240. return *this;
  241. }
  242. // ---------------------------------------------------------------------
  243. /** Generic read method. ByteSwap::Swap(T*) *must* be defined */
  244. template <typename T>
  245. T Get() {
  246. if (mCurrent + sizeof(T) > mLimit) {
  247. throw DeadlyImportError("End of file or stream limit was reached");
  248. }
  249. T f;
  250. ::memcpy(&f, mCurrent, sizeof(T));
  251. Intern::Getter<SwapEndianness, T, RuntimeSwitch>()(&f, mLe);
  252. mCurrent += sizeof(T);
  253. return f;
  254. }
  255. private:
  256. // ---------------------------------------------------------------------
  257. void InternBegin() {
  258. if (nullptr == mStream) {
  259. throw DeadlyImportError("StreamReader: Unable to open file");
  260. }
  261. const size_t filesize = mStream->FileSize() - mStream->Tell();
  262. if (0 == filesize) {
  263. throw DeadlyImportError("StreamReader: File is empty or EOF is already reached");
  264. }
  265. mCurrent = mBuffer = new int8_t[filesize];
  266. const size_t read = mStream->Read(mCurrent, 1, filesize);
  267. // (read < s) can only happen if the stream was opened in text mode, in which case FileSize() is not reliable
  268. ai_assert(read <= filesize);
  269. mEnd = mLimit = &mBuffer[read - 1] + 1;
  270. }
  271. private:
  272. std::shared_ptr<IOStream> mStream;
  273. int8_t *mBuffer;
  274. int8_t *mCurrent;
  275. int8_t *mEnd;
  276. int8_t *mLimit;
  277. bool mLe;
  278. };
  279. // --------------------------------------------------------------------------------------------
  280. // `static` StreamReaders. Their byte order is fixed and they might be a little bit faster.
  281. #ifdef AI_BUILD_BIG_ENDIAN
  282. typedef StreamReader<true> StreamReaderLE;
  283. typedef StreamReader<false> StreamReaderBE;
  284. #else
  285. typedef StreamReader<true> StreamReaderBE;
  286. typedef StreamReader<false> StreamReaderLE;
  287. #endif
  288. // `dynamic` StreamReader. The byte order of the input data is specified in the
  289. // c'tor. This involves runtime branching and might be a little bit slower.
  290. typedef StreamReader<true, true> StreamReaderAny;
  291. } // end namespace Assimp
  292. #endif // !! AI_STREAMREADER_H_INCLUDED