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 "aemu/base/files/CompressingStream.h"
16
17 #include "aemu/base/files/StreamSerializing.h"
18
19 #include "lz4.h"
20
21 #include <errno.h>
22
23 namespace android {
24 namespace base {
25
CompressingStream(Stream & output)26 CompressingStream::CompressingStream(Stream& output)
27 : mOutput(output) {
28 mLzStream = reinterpret_cast<void *>(LZ4_createStream());
29 }
30
~CompressingStream()31 CompressingStream::~CompressingStream() {
32 saveBuffer(&mOutput, mBuffer);
33 LZ4_freeStream((LZ4_stream_t*)mLzStream);
34 }
35
read(void *,size_t)36 ssize_t CompressingStream::read(void*, size_t) {
37 return -EPERM;
38 }
39
write(const void * buffer,size_t size)40 ssize_t CompressingStream::write(const void* buffer, size_t size) {
41 if (!size) {
42 return 0;
43 }
44
45 size_t outSize = 0;
46 outSize = LZ4_compressBound(size);
47 auto oldSize = mBuffer.size();
48 mBuffer.resize_noinit(mBuffer.size() + outSize);
49 const auto outBuffer = mBuffer.data() + oldSize;
50 int written = 0;
51 written = LZ4_compress_fast_continue((LZ4_stream_t*)mLzStream,
52 (const char*)buffer,
53 outBuffer, size, outSize, 1);
54
55 if (!written) {
56 return -EIO;
57 }
58 mBuffer.resize(oldSize + written);
59 return size;
60 }
61
62 } // namespace base
63 } // namespace android
64