1// LAF Base Library
2// Copyright (c) 2001-2016 David Capello
3//
4// This file is released under the terms of the MIT license.
5// Read LICENSE.txt for more information.
6
7#ifdef HAVE_CONFIG_H
8#include "config.h"
9#endif
10
11#include "base/serialization.h"
12
13#include <iostream>
14
15namespace base {
16namespace serialization {
17
18std::ostream& write8(std::ostream& os, uint8_t byte)
19{
20 os.put(byte);
21 return os;
22}
23
24uint8_t read8(std::istream& is)
25{
26 return (uint8_t)is.get();
27}
28
29std::ostream& little_endian::write16(std::ostream& os, uint16_t word)
30{
31 os.put((int)((word & 0x00ff)));
32 os.put((int)((word & 0xff00) >> 8));
33 return os;
34}
35
36std::ostream& little_endian::write32(std::ostream& os, uint32_t dword)
37{
38 os.put((int)((dword & 0x000000ffl)));
39 os.put((int)((dword & 0x0000ff00l) >> 8));
40 os.put((int)((dword & 0x00ff0000l) >> 16));
41 os.put((int)((dword & 0xff000000l) >> 24));
42 return os;
43}
44
45uint16_t little_endian::read16(std::istream& is)
46{
47 int b1, b2;
48 b1 = is.get();
49 b2 = is.get();
50 return ((b2 << 8) | b1);
51}
52
53uint32_t little_endian::read32(std::istream& is)
54{
55 int b1, b2, b3, b4;
56 b1 = is.get();
57 b2 = is.get();
58 b3 = is.get();
59 b4 = is.get();
60 return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
61}
62
63std::ostream& big_endian::write16(std::ostream& os, uint16_t word)
64{
65 os.put((int)((word & 0xff00) >> 8));
66 os.put((int)((word & 0x00ff)));
67 return os;
68}
69
70std::ostream& big_endian::write32(std::ostream& os, uint32_t dword)
71{
72 os.put((int)((dword & 0xff000000l) >> 24));
73 os.put((int)((dword & 0x00ff0000l) >> 16));
74 os.put((int)((dword & 0x0000ff00l) >> 8));
75 os.put((int)((dword & 0x000000ffl)));
76 return os;
77}
78
79uint16_t big_endian::read16(std::istream& is)
80{
81 int b1, b2;
82 b2 = is.get();
83 b1 = is.get();
84 return ((b2 << 8) | b1);
85}
86
87uint32_t big_endian::read32(std::istream& is)
88{
89 int b1, b2, b3, b4;
90 b4 = is.get();
91 b3 = is.get();
92 b2 = is.get();
93 b1 = is.get();
94 return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
95}
96
97} // namespace serialization
98} // namespace base
99