1 // Copyright 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "base/DecompressingStream.h"
16
17 #include "base/StreamSerializing.h"
18 #include "lz4.h"
19
20 #include <errno.h>
21 #include <cassert>
22
23 namespace android {
24 namespace base {
25
DecompressingStream(Stream & input)26 DecompressingStream::DecompressingStream(Stream& input)
27 : mLzStream(LZ4_createStreamDecode()) {
28 loadBuffer(&input, &mBuffer);
29 }
30
~DecompressingStream()31 DecompressingStream::~DecompressingStream() {
32 LZ4_freeStreamDecode((LZ4_streamDecode_t*)mLzStream);
33 }
34
read(void * buffer,size_t size)35 ssize_t DecompressingStream::read(void* buffer, size_t size) {
36 assert(mBufferPos < mBuffer.size() ||
37 (mBufferPos == mBuffer.size() && size == 0));
38 if (!size) {
39 return 0;
40 }
41 const int read = LZ4_decompress_fast_continue(
42 (LZ4_streamDecode_t*)mLzStream, mBuffer.data() + mBufferPos,
43 (char*)buffer, size);
44 if (!read) {
45 return -EIO;
46 }
47 mBufferPos += read;
48 assert(mBufferPos <= mBuffer.size());
49 return size;
50 }
51
write(const void *,size_t)52 ssize_t DecompressingStream::write(const void*, size_t) {
53 return -EPERM;
54 }
55
56 } // namespace base
57 } // namespace android
58