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