StreamReader.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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. #ifndef AI_STREAMREADER_H_INCLUDED
  38. #define AI_STREAMREADER_H_INCLUDED
  39. #include "ByteSwapper.h"
  40. #include "Exceptional.h"
  41. #include <memory>
  42. #include <assimp/IOStream.hpp>
  43. #include "Defines.h"
  44. namespace Assimp {
  45. // --------------------------------------------------------------------------------------------
  46. /** Wrapper class around IOStream to allow for consistent reading of binary data in both
  47. * little and big endian format. Don't attempt to instance the template directly. Use
  48. * StreamReaderLE to read from a little-endian stream and StreamReaderBE to read from a
  49. * BE stream. The class expects that the endianness of any input data is known at
  50. * compile-time, which should usually be true (#BaseImporter::ConvertToUTF8 implements
  51. * runtime endianness conversions for text files).
  52. *
  53. * XXX switch from unsigned int for size types to size_t? or ptrdiff_t?*/
  54. // --------------------------------------------------------------------------------------------
  55. template <bool SwapEndianess = false, bool RuntimeSwitch = false>
  56. class StreamReader
  57. {
  58. public:
  59. // FIXME: use these data types throughout the whole library,
  60. // then change them to 64 bit values :-)
  61. typedef int diff;
  62. typedef unsigned int pos;
  63. public:
  64. // ---------------------------------------------------------------------
  65. /** Construction from a given stream with a well-defined endianness.
  66. *
  67. * The StreamReader holds a permanent strong reference to the
  68. * stream, which is released upon destruction.
  69. * @param stream Input stream. The stream is not restarted if
  70. * its file pointer is not at 0. Instead, the stream reader
  71. * reads from the current position to the end of the stream.
  72. * @param le If @c RuntimeSwitch is true: specifies whether the
  73. * stream is in little endian byte order. Otherwise the
  74. * endianness information is contained in the @c SwapEndianess
  75. * template parameter and this parameter is meaningless. */
  76. StreamReader(std::shared_ptr<IOStream> stream, bool le = false)
  77. : stream(stream)
  78. , le(le)
  79. {
  80. ai_assert(stream);
  81. InternBegin();
  82. }
  83. // ---------------------------------------------------------------------
  84. StreamReader(IOStream* stream, bool le = false)
  85. : stream(std::shared_ptr<IOStream>(stream))
  86. , le(le)
  87. {
  88. ai_assert(stream);
  89. InternBegin();
  90. }
  91. // ---------------------------------------------------------------------
  92. ~StreamReader() {
  93. delete[] buffer;
  94. }
  95. public:
  96. // deprecated, use overloaded operator>> instead
  97. // ---------------------------------------------------------------------
  98. /** Read a float from the stream */
  99. float GetF4()
  100. {
  101. return Get<float>();
  102. }
  103. // ---------------------------------------------------------------------
  104. /** Read a double from the stream */
  105. double GetF8() {
  106. return Get<double>();
  107. }
  108. // ---------------------------------------------------------------------
  109. /** Read a signed 16 bit integer from the stream */
  110. int16_t GetI2() {
  111. return Get<int16_t>();
  112. }
  113. // ---------------------------------------------------------------------
  114. /** Read a signed 8 bit integer from the stream */
  115. int8_t GetI1() {
  116. return Get<int8_t>();
  117. }
  118. // ---------------------------------------------------------------------
  119. /** Read an signed 32 bit integer from the stream */
  120. int32_t GetI4() {
  121. return Get<int32_t>();
  122. }
  123. // ---------------------------------------------------------------------
  124. /** Read a signed 64 bit integer from the stream */
  125. int64_t GetI8() {
  126. return Get<int64_t>();
  127. }
  128. // ---------------------------------------------------------------------
  129. /** Read a unsigned 16 bit integer from the stream */
  130. uint16_t GetU2() {
  131. return Get<uint16_t>();
  132. }
  133. // ---------------------------------------------------------------------
  134. /** Read a unsigned 8 bit integer from the stream */
  135. uint8_t GetU1() {
  136. return Get<uint8_t>();
  137. }
  138. // ---------------------------------------------------------------------
  139. /** Read an unsigned 32 bit integer from the stream */
  140. uint32_t GetU4() {
  141. return Get<uint32_t>();
  142. }
  143. // ---------------------------------------------------------------------
  144. /** Read a unsigned 64 bit integer from the stream */
  145. uint64_t GetU8() {
  146. return Get<uint64_t>();
  147. }
  148. public:
  149. // ---------------------------------------------------------------------
  150. /** Get the remaining stream size (to the end of the stream) */
  151. unsigned int GetRemainingSize() const {
  152. return (unsigned int)(end - current);
  153. }
  154. // ---------------------------------------------------------------------
  155. /** Get the remaining stream size (to the current read limit). The
  156. * return value is the remaining size of the stream if no custom
  157. * read limit has been set. */
  158. unsigned int GetRemainingSizeToLimit() const {
  159. return (unsigned int)(limit - current);
  160. }
  161. // ---------------------------------------------------------------------
  162. /** Increase the file pointer (relative seeking) */
  163. void IncPtr(size_t plus) {
  164. current += plus;
  165. if (current > limit) {
  166. throw DeadlyImportError("End of file or read limit was reached");
  167. }
  168. }
  169. // ---------------------------------------------------------------------
  170. /** Get the current file pointer */
  171. int8_t* GetPtr() const {
  172. return current;
  173. }
  174. // ---------------------------------------------------------------------
  175. /** Set current file pointer (Get it from #GetPtr). This is if you
  176. * prefer to do pointer arithmetics on your own or want to copy
  177. * large chunks of data at once.
  178. * @param p The new pointer, which is validated against the size
  179. * limit and buffer boundaries. */
  180. void SetPtr(int8_t* p) {
  181. current = p;
  182. if (current > limit || current < buffer) {
  183. throw DeadlyImportError("End of file or read limit was reached");
  184. }
  185. }
  186. // ---------------------------------------------------------------------
  187. /** Copy n bytes to an external buffer
  188. * @param out Destination for copying
  189. * @param bytes Number of bytes to copy */
  190. void CopyAndAdvance(void* out, size_t bytes) {
  191. int8_t* ur = GetPtr();
  192. SetPtr(ur+bytes); // fire exception if eof
  193. ::memcpy(out,ur,bytes);
  194. }
  195. // ---------------------------------------------------------------------
  196. /** Get the current offset from the beginning of the file */
  197. int GetCurrentPos() const {
  198. return (unsigned int)(current - buffer);
  199. }
  200. void SetCurrentPos(size_t pos) {
  201. SetPtr(buffer + pos);
  202. }
  203. // ---------------------------------------------------------------------
  204. /** Setup a temporary read limit
  205. *
  206. * @param limit Maximum number of bytes to be read from
  207. * the beginning of the file. Specifying UINT_MAX
  208. * resets the limit to the original end of the stream.
  209. * Returns the previously set limit. */
  210. unsigned int SetReadLimit(unsigned int _limit) {
  211. unsigned int prev = GetReadLimit();
  212. if (UINT_MAX == _limit) {
  213. limit = end;
  214. return prev;
  215. }
  216. limit = buffer + _limit;
  217. if (limit > end) {
  218. throw DeadlyImportError("StreamReader: Invalid read limit");
  219. }
  220. return prev;
  221. }
  222. // ---------------------------------------------------------------------
  223. /** Get the current read limit in bytes. Reading over this limit
  224. * accidentally raises an exception. */
  225. unsigned int GetReadLimit() const {
  226. return (unsigned int)(limit - buffer);
  227. }
  228. // ---------------------------------------------------------------------
  229. /** Skip to the read limit in bytes. Reading over this limit
  230. * accidentally raises an exception. */
  231. void SkipToReadLimit() {
  232. current = limit;
  233. }
  234. // ---------------------------------------------------------------------
  235. /** overload operator>> and allow chaining of >> ops. */
  236. template <typename T>
  237. StreamReader& operator >> (T& f) {
  238. f = Get<T>();
  239. return *this;
  240. }
  241. private:
  242. // ---------------------------------------------------------------------
  243. /** Generic read method. ByteSwap::Swap(T*) *must* be defined */
  244. template <typename T>
  245. T Get() {
  246. if ( current + sizeof(T) > limit) {
  247. throw DeadlyImportError("End of file or stream limit was reached");
  248. }
  249. #ifdef __arm__
  250. T f;
  251. ::memcpy (&f, current, sizeof(T));
  252. #else
  253. T f = *((const T*)current);
  254. #endif
  255. Intern :: Getter<SwapEndianess,T,RuntimeSwitch>() (&f,le);
  256. current += sizeof(T);
  257. return f;
  258. }
  259. // ---------------------------------------------------------------------
  260. void InternBegin() {
  261. if (!stream) {
  262. // in case someone wonders: StreamReader is frequently invoked with
  263. // no prior validation whether the input stream is valid. Since
  264. // no one bothers changing the error message, this message here
  265. // is passed down to the caller and 'unable to open file'
  266. // simply describes best what happened.
  267. throw DeadlyImportError("StreamReader: Unable to open file");
  268. }
  269. const size_t s = stream->FileSize() - stream->Tell();
  270. if (!s) {
  271. throw DeadlyImportError("StreamReader: File is empty or EOF is already reached");
  272. }
  273. current = buffer = new int8_t[s];
  274. const size_t read = stream->Read(current,1,s);
  275. // (read < s) can only happen if the stream was opened in text mode, in which case FileSize() is not reliable
  276. ai_assert(read <= s);
  277. end = limit = &buffer[read];
  278. }
  279. private:
  280. std::shared_ptr<IOStream> stream;
  281. int8_t *buffer, *current, *end, *limit;
  282. bool le;
  283. };
  284. // --------------------------------------------------------------------------------------------
  285. // `static` StreamReaders. Their byte order is fixed and they might be a little bit faster.
  286. #ifdef AI_BUILD_BIG_ENDIAN
  287. typedef StreamReader<true> StreamReaderLE;
  288. typedef StreamReader<false> StreamReaderBE;
  289. #else
  290. typedef StreamReader<true> StreamReaderBE;
  291. typedef StreamReader<false> StreamReaderLE;
  292. #endif
  293. // `dynamic` StreamReader. The byte order of the input data is specified in the
  294. // c'tor. This involves runtime branching and might be a little bit slower.
  295. typedef StreamReader<true,true> StreamReaderAny;
  296. } // end namespace Assimp
  297. #endif // !! AI_STREAMREADER_H_INCLUDED