common: prevent buffer overflow
[supercollider.git] / include / server / ReadWriteMacros.h
blob19ba8bb6c4891f13c1e228fc5f02030983d0625c
1 /*
2 SuperCollider real time audio synthesis system
3 Copyright (c) 2002 James McCartney. All rights reserved.
4 http://www.audiosynth.com
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #ifndef _ReadWriteMacros_
23 #define _ReadWriteMacros_
25 #include "SC_Types.h"
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdexcept>
30 inline int32 readInt8(FILE *file)
32 int32 res = fgetc(file);
34 return res;
37 inline uint32 readUInt8(FILE *file)
39 uint8 res = (uint8)fgetc(file);
40 return (uint32)res;
43 inline int32 readInt16_be(FILE *file)
45 int32 c = fgetc(file);
46 int32 d = fgetc(file);
48 int32 res = ((c & 255) << 8) | (d & 255);
49 return res;
52 inline int32 readInt32_be(FILE *file)
54 int32 a = fgetc(file);
55 int32 b = fgetc(file);
56 int32 c = fgetc(file);
57 int32 d = fgetc(file);
59 int32 res = ((a & 255) << 24) | ((b & 255) << 16) | ((c & 255) << 8) | (d & 255);
60 return res;
63 inline float readFloat_be(FILE *file)
65 union {
66 float f;
67 int32 i;
68 } u;
69 u.i = readInt32_be(file);
70 //post("readFloat %g\n", u.f);
71 return u.f;
74 inline void readData(FILE *file, char *outData, size_t inLength)
76 size_t read = fread(outData, 1, inLength, file);
77 if (read != inLength)
78 throw std::runtime_error("readData: read != inLength");
81 inline int32 readInt8(char *&buf)
83 int32 res = *buf++;
84 return res;
87 inline uint32 readUInt8(char *&buf)
89 uint8 res = (uint8)*buf++;
90 return (uint32)res;
93 inline int32 readInt16_be(char *&buf)
95 int32 c = readInt8(buf);
96 int32 d = readInt8(buf);
98 int32 res = ((c & 255) << 8) | (d & 255);
99 return res;
102 inline int32 readInt32_be(char *&buf)
104 int32 a = readInt8(buf);
105 int32 b = readInt8(buf);
106 int32 c = readInt8(buf);
107 int32 d = readInt8(buf);
109 int32 res = ((a & 255) << 24) | ((b & 255) << 16) | ((c & 255) << 8) | (d & 255);
110 return res;
113 inline float readFloat_be(char *&buf)
115 union {
116 float f;
117 int32 i;
118 } u;
119 u.i = readInt32_be(buf);
120 //post("readFloat %g\n", u.f);
121 return u.f;
124 inline void readData(char *&buf, char *outData, size_t inLength)
126 memcpy(outData, buf, inLength);
127 buf += inLength;
131 #endif