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
TestZlibCompression(StringRef Input,int Level)26 void TestZlibCompression(StringRef Input, int Level) {
27 SmallString<32> Compressed;
28 SmallString<32> Uncompressed;
29
30 Error E = zlib::compress(Input, Compressed, Level);
31 EXPECT_FALSE(E);
32 consumeError(std::move(E));
33
34 // Check that uncompressed buffer is the same as original.
35 E = zlib::uncompress(Compressed, Uncompressed, Input.size());
36 EXPECT_FALSE(E);
37 consumeError(std::move(E));
38
39 EXPECT_EQ(Input, Uncompressed);
40 if (Input.size() > 0) {
41 // Uncompression fails if expected length is too short.
42 E = zlib::uncompress(Compressed, Uncompressed, Input.size() - 1);
43 EXPECT_EQ("zlib error: Z_BUF_ERROR", llvm::toString(std::move(E)));
44 }
45 }
46
TEST(CompressionTest,Zlib)47 TEST(CompressionTest, Zlib) {
48 TestZlibCompression("", zlib::DefaultCompression);
49
50 TestZlibCompression("hello, world!", zlib::NoCompression);
51 TestZlibCompression("hello, world!", zlib::BestSizeCompression);
52 TestZlibCompression("hello, world!", zlib::BestSpeedCompression);
53 TestZlibCompression("hello, world!", zlib::DefaultCompression);
54
55 const size_t kSize = 1024;
56 char BinaryData[kSize];
57 for (size_t i = 0; i < kSize; ++i) {
58 BinaryData[i] = i & 255;
59 }
60 StringRef BinaryDataStr(BinaryData, kSize);
61
62 TestZlibCompression(BinaryDataStr, zlib::NoCompression);
63 TestZlibCompression(BinaryDataStr, zlib::BestSizeCompression);
64 TestZlibCompression(BinaryDataStr, zlib::BestSpeedCompression);
65 TestZlibCompression(BinaryDataStr, zlib::DefaultCompression);
66 }
67
TEST(CompressionTest,ZlibCRC32)68 TEST(CompressionTest, ZlibCRC32) {
69 EXPECT_EQ(
70 0x414FA339U,
71 zlib::crc32(StringRef("The quick brown fox jumps over the lazy dog")));
72 }
73
74 #endif
75
76 }
77