Initial files
[oweals/minetest.git] / src / serialization.cpp
1 /*
2 (c) 2010 Perttu Ahola <celeron55@gmail.com>
3 */
4
5 #include "serialization.h"
6 #include "utility.h"
7
8 void compress(SharedBuffer<u8> data, std::ostream &os, u8 version)
9 {
10         if(data.getSize() == 0)
11                 return;
12
13         // Write length (u32)
14
15         u8 tmp[4];
16         writeU32(tmp, data.getSize());
17         os.write((char*)tmp, 4);
18         
19         // We will be writing 8-bit pairs of more_count and byte
20         u8 more_count = 0;
21         u8 current_byte = data[0];
22         for(u32 i=1; i<data.getSize(); i++)
23         {
24                 if(
25                         data[i] != current_byte
26                         || more_count == 255
27                 )
28                 {
29                         // write count and byte
30                         os.write((char*)&more_count, 1);
31                         os.write((char*)&current_byte, 1);
32                         more_count = 0;
33                         current_byte = data[i];
34                 }
35                 else
36                 {
37                         more_count++;
38                 }
39         }
40         // write count and byte
41         os.write((char*)&more_count, 1);
42         os.write((char*)&current_byte, 1);
43 }
44
45 void decompress(std::istream &is, std::ostream &os, u8 version)
46 {
47         // Read length (u32)
48
49         u8 tmp[4];
50         is.read((char*)tmp, 4);
51         u32 len = readU32(tmp);
52         
53         // We will be reading 8-bit pairs of more_count and byte
54         u32 count = 0;
55         for(;;)
56         {
57                 u8 more_count=0;
58                 u8 byte=0;
59
60                 is.read((char*)&more_count, 1);
61                 
62                 is.read((char*)&byte, 1);
63
64                 if(is.eof())
65                         throw SerializationError("decompress: stream ended halfway");
66
67                 for(s32 i=0; i<(u16)more_count+1; i++)
68                         os.write((char*)&byte, 1);
69
70                 count += (u16)more_count+1;
71
72                 if(count == len)
73                         break;
74         }
75 }
76
77