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