filter_source_stream_test_util.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2016 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. #include "net/filter/filter_source_stream_test_util.h"
  5. #include <cstring>
  6. #include "base/bit_cast.h"
  7. #include "base/check_op.h"
  8. #include "third_party/zlib/zlib.h"
  9. namespace net {
  10. // Compress |source| with length |source_len|. Write output into |dest|, and
  11. // output length into |dest_len|. If |gzip_framing| is true, header will be
  12. // added.
  13. void CompressGzip(const char* source,
  14. size_t source_len,
  15. char* dest,
  16. size_t* dest_len,
  17. bool gzip_framing) {
  18. size_t dest_left = *dest_len;
  19. z_stream zlib_stream;
  20. memset(&zlib_stream, 0, sizeof(zlib_stream));
  21. int code;
  22. if (gzip_framing) {
  23. const int kMemLevel = 8; // the default, see deflateInit2(3)
  24. code = deflateInit2(&zlib_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
  25. -MAX_WBITS, kMemLevel, Z_DEFAULT_STRATEGY);
  26. } else {
  27. code = deflateInit(&zlib_stream, Z_DEFAULT_COMPRESSION);
  28. }
  29. DCHECK_EQ(Z_OK, code);
  30. // If compressing with gzip framing, prepend a gzip header. See RFC 1952 2.2
  31. // and 2.3 for more information.
  32. if (gzip_framing) {
  33. const unsigned char gzip_header[] = {
  34. 0x1f,
  35. 0x8b, // magic number
  36. 0x08, // CM 0x08 == "deflate"
  37. 0x00, // FLG 0x00 == nothing
  38. 0x00, 0x00, 0x00,
  39. 0x00, // MTIME 0x00000000 == no mtime
  40. 0x00, // XFL 0x00 == nothing
  41. 0xff, // OS 0xff == unknown
  42. };
  43. DCHECK_GE(dest_left, sizeof(gzip_header));
  44. memcpy(dest, gzip_header, sizeof(gzip_header));
  45. dest += sizeof(gzip_header);
  46. dest_left -= sizeof(gzip_header);
  47. }
  48. zlib_stream.next_in = base::bit_cast<Bytef*>(source);
  49. zlib_stream.avail_in = source_len;
  50. zlib_stream.next_out = base::bit_cast<Bytef*>(dest);
  51. zlib_stream.avail_out = dest_left;
  52. code = deflate(&zlib_stream, Z_FINISH);
  53. DCHECK_EQ(Z_STREAM_END, code);
  54. dest_left = zlib_stream.avail_out;
  55. deflateEnd(&zlib_stream);
  56. *dest_len -= dest_left;
  57. }
  58. } // namespace net