Blender  V3.3
Stream.cpp
Go to the documentation of this file.
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
7 #include <Stream.h>
8 
9 #include <cstdio> /* printf */
10 #include <cstring> /* memcpy */
11 
12 static const char *msg_error_seek = "DDS: trying to seek beyond end of stream (corrupt file?)";
13 static const char *msg_error_read = "DDS: trying to read beyond end of stream (corrupt file?)";
14 
15 inline bool is_read_within_bounds(const Stream &mem, unsigned int count)
16 {
17  if (mem.pos >= mem.size) {
18  /* No more data remained in the memory buffer. */
19  return false;
20  }
21 
22  if (count > mem.size - mem.pos) {
23  /* Reading past the memory bounds. */
24  return false;
25  }
26 
27  return true;
28 }
29 
30 unsigned int Stream::seek(unsigned int p)
31 {
32  if (p > size) {
34  }
35  else {
36  pos = p;
37  }
38 
39  return pos;
40 }
41 
42 unsigned int mem_read(Stream &mem, unsigned long long &i)
43 {
44  if (!is_read_within_bounds(mem, 8)) {
46  return 0;
47  }
48  memcpy(&i, mem.mem + mem.pos, 8); /* TODO: make sure little endian. */
49  mem.pos += 8;
50  return 8;
51 }
52 
53 unsigned int mem_read(Stream &mem, unsigned int &i)
54 {
55  if (!is_read_within_bounds(mem, 4)) {
57  return 0;
58  }
59  memcpy(&i, mem.mem + mem.pos, 4); /* TODO: make sure little endian. */
60  mem.pos += 4;
61  return 4;
62 }
63 
64 unsigned int mem_read(Stream &mem, unsigned short &i)
65 {
66  if (!is_read_within_bounds(mem, 2)) {
68  return 0;
69  }
70  memcpy(&i, mem.mem + mem.pos, 2); /* TODO: make sure little endian. */
71  mem.pos += 2;
72  return 2;
73 }
74 
75 unsigned int mem_read(Stream &mem, unsigned char &i)
76 {
77  if (!is_read_within_bounds(mem, 1)) {
79  return 0;
80  }
81  i = (mem.mem + mem.pos)[0];
82  mem.pos += 1;
83  return 1;
84 }
85 
86 unsigned int mem_read(Stream &mem, unsigned char *i, unsigned int count)
87 {
88  if (!is_read_within_bounds(mem, count)) {
90  return 0;
91  }
92  memcpy(i, mem.mem + mem.pos, count);
93  mem.pos += count;
94  return count;
95 }
96 
97 void Stream::set_failed(const char *msg)
98 {
99  if (!failed) {
100  puts(msg);
101  failed = true;
102  }
103 }
static const char * msg_error_read
Definition: Stream.cpp:13
bool is_read_within_bounds(const Stream &mem, unsigned int count)
Definition: Stream.cpp:15
unsigned int mem_read(Stream &mem, unsigned long long &i)
Definition: Stream.cpp:42
static const char * msg_error_seek
Definition: Stream.cpp:12
int count
Definition: Stream.h:11
bool failed
Definition: Stream.h:15
void set_failed(const char *msg)
Definition: Stream.cpp:97
unsigned int seek(unsigned int p)
Definition: Stream.cpp:30
unsigned int size
Definition: Stream.h:13
unsigned int pos
Definition: Stream.h:14
unsigned char * mem
Definition: Stream.h:12