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