File: utils.h

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (75 lines) | stat: -rw-r--r-- 1,895 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#pragma once

// Fixed width integer types are defined in the C++11 header <cstdint>
#include <cstdint>

#include "idatastream.h"
#include <ostream>
#include <algorithm>

namespace stream
{

/**
 * greebo: Writes the given number value to the given output stream in Big Endian byte order,
 * regardless of the calling platform's endianness.
 */
template<typename ValueType>
void writeBigEndian(std::ostream& stream, ValueType value)
{
	ValueType output = value;

#ifndef __BIG_ENDIAN__
	std::reverse(reinterpret_cast<char*>(&output), reinterpret_cast<char*>(&output) + sizeof(ValueType));
#endif

	stream.write(reinterpret_cast<const char*>(&output), sizeof(ValueType));
}

/**
* greebo: Writes the given number value to the given output stream in Little Endian byte order,
* regardless of the calling platform's endianness.
*/
template<typename ValueType>
void writeLittleEndian(std::ostream& stream, ValueType value)
{
	ValueType output = value;

#ifdef __BIG_ENDIAN__
	std::reverse(reinterpret_cast<char*>(&output), reinterpret_cast<char*>(&output) + sizeof(ValueType));
#endif

	stream.write(reinterpret_cast<const char*>(&output), sizeof(ValueType));
}

/**
 * greebo: Read an integer type stored in little endian format 
 * from the given stream and returns its value.
 */
template<typename ValueType>
inline ValueType readLittleEndian(InputStream& stream)
{
	ValueType value;
	stream.read(reinterpret_cast<InputStream::byte_type*>(&value), sizeof(ValueType));

#ifdef __BIG_ENDIAN__
	std::reverse(reinterpret_cast<InputStream::byte_type*>(&value), reinterpret_cast<InputStream::byte_type*>(&value) + sizeof(ValueType));
#endif

	return value;
}

inline void readByte(InputStream& stream, InputStream::byte_type& value)
{
	stream.read(&value, 1);
}

inline InputStream::byte_type readByte(InputStream& stream)
{
	InputStream::byte_type value;
	stream.read(&value, 1);

	return value;
}

}