1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "gtest/gtest.h"
18
19 #include <string.h>
20 #include <zlib.h>
21
22 const char kTestString[] = "compressed string";
23
ZAlloc(void * opaque,uint32_t items,uint32_t size)24 void* ZAlloc(void* opaque, uint32_t items, uint32_t size) {
25 *reinterpret_cast<int*>(opaque) |= 1;
26 return calloc(items, size);
27 }
28
ZFree(void * opaque,void * address)29 void ZFree(void* opaque, void* address) {
30 *reinterpret_cast<int*>(opaque) |= 2;
31 free(address);
32 }
33
TEST(ZLib,Deflate)34 TEST(ZLib, Deflate) {
35 char input[1024];
36 char output[1024];
37
38 z_stream encode_stream;
39 memset(&encode_stream, 0, sizeof(encode_stream));
40 strncpy(input, kTestString, sizeof(input));
41 encode_stream.next_in = reinterpret_cast<Bytef*>(input);
42 encode_stream.avail_in = strlen(input) + 1;
43 encode_stream.next_out = reinterpret_cast<Bytef*>(output);
44 encode_stream.avail_out = sizeof(output);
45 encode_stream.zalloc = ZAlloc;
46 encode_stream.zfree = ZFree;
47 int opaque = 0;
48 encode_stream.opaque = &opaque;
49 ASSERT_EQ(deflateInit(&encode_stream, Z_BEST_COMPRESSION), Z_OK);
50 ASSERT_EQ(deflate(&encode_stream, Z_FINISH), Z_STREAM_END);
51 ASSERT_EQ(deflateEnd(&encode_stream), Z_OK);
52 EXPECT_EQ(opaque, 3);
53
54 z_stream decode_stream;
55 memset(&decode_stream, 0, sizeof(decode_stream));
56 decode_stream.next_in = reinterpret_cast<Bytef*>(output);
57 decode_stream.avail_in = encode_stream.total_out;
58 decode_stream.next_out = reinterpret_cast<Bytef*>(input);
59 decode_stream.avail_out = sizeof(input);
60 opaque = 0;
61 decode_stream.zalloc = ZAlloc;
62 decode_stream.zfree = ZFree;
63 decode_stream.opaque = &opaque;
64 ASSERT_EQ(inflateInit(&decode_stream), Z_OK);
65 ASSERT_EQ(inflate(&decode_stream, Z_FINISH), Z_STREAM_END);
66 ASSERT_EQ(inflateEnd(&decode_stream), Z_OK);
67 EXPECT_EQ(decode_stream.total_out, sizeof(kTestString));
68 EXPECT_EQ(strncmp(input, kTestString, sizeof(input)), 0);
69 EXPECT_EQ(opaque, 3);
70 }
71