1 //===- llvm/unittest/Support/raw_ostream_test.cpp - raw_ostream tests -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "gtest/gtest.h"
11 #include "llvm/Support/Format.h"
12 #include "llvm/Support/raw_sha1_ostream.h"
13 
14 #include <string>
15 
16 using namespace llvm;
17 
18 static std::string toHex(StringRef Input) {
19   static const char *const LUT = "0123456789ABCDEF";
20   size_t Length = Input.size();
21 
22   std::string Output;
23   Output.reserve(2 * Length);
24   for (size_t i = 0; i < Length; ++i) {
25     const unsigned char c = Input[i];
26     Output.push_back(LUT[c >> 4]);
27     Output.push_back(LUT[c & 15]);
28   }
29   return Output;
30 }
31 
32 TEST(raw_sha1_ostreamTest, Basic) {
33   llvm::raw_sha1_ostream Sha1Stream;
34   Sha1Stream << "Hello World!";
35   auto Hash = toHex(Sha1Stream.sha1());
36 
37   ASSERT_EQ("2EF7BDE608CE5404E97D5F042F95F89F1C232871", Hash);
38 }
39 
40 TEST(sha1_hash_test, Basic) {
41   ArrayRef<uint8_t> Input((const uint8_t *)"Hello World!", 12);
42   std::array<uint8_t, 20> Vec = SHA1::hash(Input);
43   std::string Hash = toHex({(const char *)Vec.data(), 20});
44   ASSERT_EQ("2EF7BDE608CE5404E97D5F042F95F89F1C232871", Hash);
45 }
46 
47 // Check that getting the intermediate hash in the middle of the stream does
48 // not invalidate the final result.
49 TEST(raw_sha1_ostreamTest, Intermediate) {
50   llvm::raw_sha1_ostream Sha1Stream;
51   Sha1Stream << "Hello";
52   auto Hash = toHex(Sha1Stream.sha1());
53 
54   ASSERT_EQ("F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0", Hash);
55   Sha1Stream << " World!";
56   Hash = toHex(Sha1Stream.sha1());
57 
58   // Compute the non-split hash separately as a reference.
59   llvm::raw_sha1_ostream NonSplitSha1Stream;
60   NonSplitSha1Stream << "Hello World!";
61   auto NonSplitHash = toHex(NonSplitSha1Stream.sha1());
62 
63   ASSERT_EQ(NonSplitHash, Hash);
64 }
65 
66 TEST(raw_sha1_ostreamTest, Reset) {
67   llvm::raw_sha1_ostream Sha1Stream;
68   Sha1Stream << "Hello";
69   auto Hash = toHex(Sha1Stream.sha1());
70 
71   ASSERT_EQ("F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0", Hash);
72 
73   Sha1Stream.resetHash();
74   Sha1Stream << " World!";
75   Hash = toHex(Sha1Stream.sha1());
76 
77   ASSERT_EQ("7447F2A5A42185C8CF91E632789C431830B59067", Hash);
78 }
79