Debian Codegraph @

src/attic/Zip/ReduceDecompressor.cpp

raw
1 /* Copyright (C) Teemu Suutari */
2
3 #include <cstdint>
4 #include <cstring>
5
6 #include "ReduceDecompressor.hpp"
7 #include "../InputStream.hpp"
8 #include "../OutputStream.hpp"
9
10
11 namespace ancient::internal
12 {
13
14 ReduceDecompressor::ReduceDecompressor(const Buffer &packedData,uint32_t mode) :
15 _packedData(packedData),
16 _mode(mode)
17 {
18 if (mode<2 || mode>5) throw InvalidFormatError();
19 }
20
21 ReduceDecompressor::~ReduceDecompressor()
22 {
23 // nothing needed
24 }
25
26 size_t ReduceDecompressor::getRawSize() const noexcept
27 {
28 // N/A
29 return 0;
30 }
31
32 size_t ReduceDecompressor::getPackedSize() const noexcept
33 {
34 // N/A
35 return 0;
36 }
37
38 const std::string &ReduceDecompressor::getName() const noexcept
39 {
40 static std::string name="Zip: Reduce";
41 return name;
42 }
43
44 void ReduceDecompressor::decompressImpl(Buffer &rawData,bool verify)
45 {
46 ForwardInputStream inputStream(_packedData,0,_packedData.size());
47 LSBBitReader<ForwardInputStream> bitReader(inputStream);
48 auto readBits=[&](uint32_t count)->uint32_t
49 {
50 return bitReader.readBits8(count);
51 };
52
53 ForwardOutputStream outputStream(rawData,0,rawData.size());
54
55 uint8_t SLengths[256];
56 auto SBuf=std::make_unique<uint8_t[]>(256*64);
57 uint8_t (&S)[256][64]=*reinterpret_cast<uint8_t(*)[256][64]>(SBuf.get());
58
59 static const uint8_t bitLengths[64]={
60 8,1,1,2,2,3,3,3, 3,4,4,4,4,4,4,4,
61 4,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,
62 5,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,
63 6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6};
64
65 for (int32_t i=255;i>=0;i--)
66 {
67 uint32_t length=SLengths[i]=readBits(6);
68 for (uint32_t j=0;j<length;j++) S[i][j]=readBits(8);
69 }
70
71 uint8_t lengthBits=9U-_mode;
72
73 uint8_t lastChar=0;
74 while (!outputStream.eof())
75 {
76 auto readByte=[&]()->uint8_t
77 {
78 uint8_t ret;
79 if (!SLengths[lastChar] || readBits(1))
80 {
81 ret=readBits(8);
82 } else {
83 uint8_t tmp=readBits(bitLengths[SLengths[lastChar]]);
84 if (tmp>=SLengths[lastChar]) throw DecompressionError();
85 ret=S[lastChar][tmp];
86 }
87 lastChar=ret;
88 return ret;
89 };
90
91 uint8_t ch=readByte();
92 if (ch!=0x90U)
93 {
94 outputStream.writeByte(ch);
95 } else {
96 ch=readByte();
97 if (!ch)
98 {
99 outputStream.writeByte(0x90U);
100 } else {
101 uint8_t lengthMask=0xffU>>(8U-lengthBits);
102 uint32_t count=ch&lengthMask;
103 if (count==lengthMask)
104 count+=uint32_t(readByte());
105 count+=3;
106 uint32_t distance=(uint32_t(ch>>lengthBits)<<8)|uint32_t(readByte());
107 distance++;
108
109 outputStream.copy(distance,count,0);
110 }
111 }
112 }
113 }
114
115 }