1 //===- llvm/unittest/Support/CompressionTest.cpp - Compression tests ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements unit tests for the Compression functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Support/Compression.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/Support/Error.h"
18 #include "gtest/gtest.h"
19 
20 using namespace llvm;
21 
22 namespace {
23 
24 #if LLVM_ENABLE_ZLIB
25 
26 void TestZlibCompression(StringRef Input, int Level) {
27   SmallString<32> Compressed;
28   SmallString<32> Uncompressed;
29 
30   zlib::compress(Input, Compressed, Level);
31 
32   // Check that uncompressed buffer is the same as original.
33   Error E = zlib::uncompress(Compressed, Uncompressed, Input.size());
34   consumeError(std::move(E));
35 
36   EXPECT_EQ(Input, Uncompressed);
37   if (Input.size() > 0) {
38     // Uncompression fails if expected length is too short.
39     E = zlib::uncompress(Compressed, Uncompressed, Input.size() - 1);
40     EXPECT_EQ("zlib error: Z_BUF_ERROR", llvm::toString(std::move(E)));
41   }
42 }
43 
44 TEST(CompressionTest, Zlib) {
45   TestZlibCompression("", zlib::DefaultCompression);
46 
47   TestZlibCompression("hello, world!", zlib::NoCompression);
48   TestZlibCompression("hello, world!", zlib::BestSizeCompression);
49   TestZlibCompression("hello, world!", zlib::BestSpeedCompression);
50   TestZlibCompression("hello, world!", zlib::DefaultCompression);
51 
52   const size_t kSize = 1024;
53   char BinaryData[kSize];
54   for (size_t i = 0; i < kSize; ++i) {
55     BinaryData[i] = i & 255;
56   }
57   StringRef BinaryDataStr(BinaryData, kSize);
58 
59   TestZlibCompression(BinaryDataStr, zlib::NoCompression);
60   TestZlibCompression(BinaryDataStr, zlib::BestSizeCompression);
61   TestZlibCompression(BinaryDataStr, zlib::BestSpeedCompression);
62   TestZlibCompression(BinaryDataStr, zlib::DefaultCompression);
63 }
64 
65 TEST(CompressionTest, ZlibCRC32) {
66   EXPECT_EQ(
67       0x414FA339U,
68       zlib::crc32(StringRef("The quick brown fox jumps over the lazy dog")));
69 }
70 
71 #endif
72 
73 }
74