| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "base/strings/string_compress.h" |
| 6 |
| 7 #if defined(USE_SYSTEM_LIBBZ2) |
| 8 #include <bzlib.h> |
| 9 #else |
| 10 #include "third_party/bzip2/bzlib.h" |
| 11 #endif |
| 12 |
| 13 #include "base/logging.h" |
| 14 |
| 15 namespace base { |
| 16 |
| 17 // This implementation is based on the Firefox MetricsService implementation. |
| 18 bool Bzip2Compress(const std::string& input, std::string* output) { |
| 19 bz_stream stream = {0}; |
| 20 // As long as our input is smaller than the bzip2 block size, we should get |
| 21 // the best compression. For example, if your input was 250k, using a block |
| 22 // size of 300k or 500k should result in the same compression ratio. Since |
| 23 // our data should be under 100k, using the minimum block size of 100k should |
| 24 // allocate less temporary memory, but result in the same compression ratio. |
| 25 int result = BZ2_bzCompressInit(&stream, |
| 26 1, // 100k (min) block size |
| 27 0, // quiet |
| 28 0); // default "work factor" |
| 29 if (result != BZ_OK) { // out of memory? |
| 30 return false; |
| 31 } |
| 32 |
| 33 output->clear(); |
| 34 |
| 35 stream.next_in = const_cast<char*>(input.data()); |
| 36 stream.avail_in = static_cast<int>(input.size()); |
| 37 // NOTE: we don't need a BZ_RUN phase since our input buffer contains |
| 38 // the entire input |
| 39 do { |
| 40 output->resize(output->size() + 1024); |
| 41 stream.next_out = &((*output)[stream.total_out_lo32]); |
| 42 stream.avail_out = static_cast<int>(output->size()) - stream.total_out_lo32; |
| 43 result = BZ2_bzCompress(&stream, BZ_FINISH); |
| 44 } while (result == BZ_FINISH_OK); |
| 45 if (result != BZ_STREAM_END) { // unknown failure? |
| 46 output->clear(); |
| 47 // TODO(jar): See if it would be better to do a CHECK() here. |
| 48 return false; |
| 49 } |
| 50 result = BZ2_bzCompressEnd(&stream); |
| 51 DCHECK(result == BZ_OK); |
| 52 |
| 53 output->resize(stream.total_out_lo32); |
| 54 |
| 55 return true; |
| 56 } |
| 57 |
| 58 } // namespace base |
| OLD | NEW |