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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
/*
* Copyright 2010 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkData.h"
#include "SkFlate.h"
#include "SkStream.h"
#ifndef SK_NO_FLATE
namespace {
#include "zlib.h"
// static
const size_t kBufferSize = 1024;
bool doFlate(bool compress, SkStream* src, SkWStream* dst) {
uint8_t inputBuffer[kBufferSize];
uint8_t outputBuffer[kBufferSize];
z_stream flateData;
flateData.zalloc = NULL;
flateData.zfree = NULL;
flateData.next_in = NULL;
flateData.avail_in = 0;
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
int rc;
if (compress)
rc = deflateInit(&flateData, Z_DEFAULT_COMPRESSION);
else
rc = inflateInit(&flateData);
if (rc != Z_OK)
return false;
uint8_t* input = (uint8_t*)src->getMemoryBase();
size_t inputLength = src->getLength();
if (input == NULL || inputLength == 0) {
input = NULL;
flateData.next_in = inputBuffer;
flateData.avail_in = 0;
} else {
flateData.next_in = input;
flateData.avail_in = SkToUInt(inputLength);
}
rc = Z_OK;
while (true) {
if (flateData.avail_out < kBufferSize) {
if (!dst->write(outputBuffer, kBufferSize - flateData.avail_out)) {
rc = Z_BUF_ERROR;
break;
}
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
}
if (rc != Z_OK)
break;
if (flateData.avail_in == 0) {
if (input != NULL)
break;
size_t read = src->read(&inputBuffer, kBufferSize);
if (read == 0)
break;
flateData.next_in = inputBuffer;
flateData.avail_in = SkToUInt(read);
}
if (compress)
rc = deflate(&flateData, Z_NO_FLUSH);
else
rc = inflate(&flateData, Z_NO_FLUSH);
}
while (rc == Z_OK) {
if (compress)
rc = deflate(&flateData, Z_FINISH);
else
rc = inflate(&flateData, Z_FINISH);
if (flateData.avail_out < kBufferSize) {
if (!dst->write(outputBuffer, kBufferSize - flateData.avail_out))
return false;
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
}
}
if (compress)
deflateEnd(&flateData);
else
inflateEnd(&flateData);
if (rc == Z_STREAM_END)
return true;
return false;
}
}
// static
bool SkFlate::Deflate(SkStream* src, SkWStream* dst) {
return doFlate(true, src, dst);
}
bool SkFlate::Deflate(const void* ptr, size_t len, SkWStream* dst) {
SkMemoryStream stream(ptr, len);
return doFlate(true, &stream, dst);
}
bool SkFlate::Deflate(const SkData* data, SkWStream* dst) {
if (data) {
SkMemoryStream stream(data->data(), data->size());
return doFlate(true, &stream, dst);
}
return false;
}
// static
bool SkFlate::Inflate(SkStream* src, SkWStream* dst) {
return doFlate(false, src, dst);
}
#endif // SK_NO_FLATE
|