Colobot
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
ioutils.h
Go to the documentation of this file.
1 // * This file is part of the COLOBOT source code
2 // * Copyright (C) 2012, Polish Portal of Colobot (PPC)
3 // *
4 // * This program is free software: you can redistribute it and/or modify
5 // * it under the terms of the GNU General Public License as published by
6 // * the Free Software Foundation, either version 3 of the License, or
7 // * (at your option) any later version.
8 // *
9 // * This program is distributed in the hope that it will be useful,
10 // * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // * GNU General Public License for more details.
13 // *
14 // * You should have received a copy of the GNU General Public License
15 // * along with this program. If not, see http://www.gnu.org/licenses/.
16 
22 #pragma once
23 
24 
25 #include <iostream>
26 
27 #include <cstring>
28 
29 namespace IOUtils {
30 
32 
37 template<int N, typename T>
38 void WriteBinary(T value, std::ostream &ostr)
39 {
40  for (int i = 0; i < N; ++i)
41  {
42  unsigned char byte = (value >> (i*8)) & 0xFF;
43  ostr.write(reinterpret_cast<char*>(&byte), 1);
44  }
45 }
46 
48 
53 template<int N, typename T>
54 T ReadBinary(std::istream &istr)
55 {
56  T value = 0;
57  for (int i = 0; i < N; ++i)
58  {
59  unsigned char byte = 0;
60  istr.read(reinterpret_cast<char*>(&byte), 1);
61  value |= byte << (i*8);
62  }
63  return value;
64 }
65 
67 
70 void WriteBinaryBool(float value, std::ostream &ostr)
71 {
72  unsigned char v = value ? 1 : 0;
73  IOUtils::WriteBinary<1, unsigned char>(v, ostr);
74 }
75 
77 
80 bool ReadBinaryBool(std::istream &istr)
81 {
82  int v = IOUtils::ReadBinary<1, unsigned char>(istr);
83  return v != 0;
84 }
85 
87 
91 void WriteBinaryFloat(float value, std::ostream &ostr)
92 {
93  union { float fValue; unsigned int iValue; } u;
94  memset(&u, 0, sizeof(u));
95  u.fValue = value;
96  IOUtils::WriteBinary<4, unsigned int>(u.iValue, ostr);
97 }
98 
100 
104 float ReadBinaryFloat(std::istream &istr)
105 {
106  union { float fValue; unsigned int iValue; } u;
107  memset(&u, 0, sizeof(u));
108  u.iValue = IOUtils::ReadBinary<4, unsigned int>(istr);
109  return u.fValue;
110 }
111 
113 
117 template<int N>
118 void WriteBinaryString(const std::string &value, std::ostream &ostr)
119 {
120  int length = value.size();
121  WriteBinary<N, int>(length, ostr);
122 
123  for (int i = 0; i < length; ++i)
124  ostr.put(value[i]);
125 }
126 
128 
132 template<int N>
133 std::string ReadBinaryString(std::istream &istr)
134 {
135  int length = ReadBinary<N, int>(istr);
136 
137  std::string str;
138  char c = 0;
139  for (int i = 0; i < length; ++i)
140  {
141  istr.read(&c, 1);
142  str += c;
143  }
144 
145  return str;
146 }
147 
148 }; // namespace IOUtils
149