Commit e25abf09 authored by Benoît Lizé's avatar Benoît Lizé Committed by Commit Bot

zlib/google: Use malloc() rather than std::vector.

This has two benefits:

- Not touching the whole data (as most of it is not written to except for the
  initial memset() in vector's constructor.)
- Allowing to recover from allocation failures.

Bug: 905777
Change-Id: I748ec518af8cfc272a8342fdd567d957dbe1fbcc
Reviewed-on: https://chromium-review.googlesource.com/c/1339872
Commit-Queue: Benoit L <lizeb@chromium.org>
Reviewed-by: default avatarAlexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#608778}
parent 01aa6422
...@@ -6,10 +6,9 @@ ...@@ -6,10 +6,9 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <vector>
#include "base/bit_cast.h" #include "base/bit_cast.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/sys_byteorder.h" #include "base/sys_byteorder.h"
...@@ -124,21 +123,35 @@ int GzipUncompressHelper(Bytef* dest, ...@@ -124,21 +123,35 @@ int GzipUncompressHelper(Bytef* dest,
namespace compression { namespace compression {
bool GzipCompress(base::StringPiece input, std::string* output) { bool GzipCompress(base::StringPiece input, std::string* output) {
// Not using std::vector<> because allocation failures are recoverable,
// which is hidden by std::vector<>.
static_assert(sizeof(Bytef) == 1, "");
const uLongf input_size = static_cast<uLongf>(input.size()); const uLongf input_size = static_cast<uLongf>(input.size());
std::vector<Bytef> compressed_data(kGzipZlibHeaderDifferenceBytes +
compressBound(input_size));
uLongf compressed_size = static_cast<uLongf>(compressed_data.size()); uLongf compressed_data_size =
if (GzipCompressHelper(&compressed_data.front(), kGzipZlibHeaderDifferenceBytes + compressBound(input_size);
&compressed_size, Bytef* compressed_data =
reinterpret_cast<Bytef*>(malloc(compressed_data_size));
if (!compressed_data)
return false;
if (GzipCompressHelper(compressed_data, &compressed_data_size,
bit_cast<const Bytef*>(input.data()), bit_cast<const Bytef*>(input.data()),
input_size) != Z_OK) { input_size) != Z_OK) {
free(compressed_data);
return false; return false;
} }
compressed_data.resize(compressed_size); Bytef* resized_data =
output->assign(compressed_data.begin(), compressed_data.end()); reinterpret_cast<Bytef*>(realloc(compressed_data, compressed_data_size));
if (!resized_data) {
free(compressed_data);
return false;
}
output->assign(resized_data, resized_data + compressed_data_size);
DCHECK_EQ(input_size, GetUncompressedSize(*output)); DCHECK_EQ(input_size, GetUncompressedSize(*output));
free(resized_data);
return true; return true;
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment