raw_sha1_ostream_test.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //===- llvm/unittest/Support/raw_ostream_test.cpp - raw_ostream 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. #include "llvm/Support/Format.h"
  9. #include "llvm/Support/raw_sha1_ostream.h"
  10. #include "gtest/gtest.h"
  11. #include <string>
  12. using namespace llvm;
  13. static std::string toHex(StringRef Input) {
  14. static const char *const LUT = "0123456789ABCDEF";
  15. size_t Length = Input.size();
  16. std::string Output;
  17. Output.reserve(2 * Length);
  18. for (size_t i = 0; i < Length; ++i) {
  19. const unsigned char c = Input[i];
  20. Output.push_back(LUT[c >> 4]);
  21. Output.push_back(LUT[c & 15]);
  22. }
  23. return Output;
  24. }
  25. TEST(raw_sha1_ostreamTest, Basic) {
  26. llvm::raw_sha1_ostream Sha1Stream;
  27. Sha1Stream << "Hello World!";
  28. auto Hash = toHex(Sha1Stream.sha1());
  29. ASSERT_EQ("2EF7BDE608CE5404E97D5F042F95F89F1C232871", Hash);
  30. }
  31. TEST(sha1_hash_test, Basic) {
  32. ArrayRef<uint8_t> Input((const uint8_t *)"Hello World!", 12);
  33. std::array<uint8_t, 20> Vec = SHA1::hash(Input);
  34. std::string Hash = toHex({(const char *)Vec.data(), 20});
  35. ASSERT_EQ("2EF7BDE608CE5404E97D5F042F95F89F1C232871", Hash);
  36. }
  37. // Check that getting the intermediate hash in the middle of the stream does
  38. // not invalidate the final result.
  39. TEST(raw_sha1_ostreamTest, Intermediate) {
  40. llvm::raw_sha1_ostream Sha1Stream;
  41. Sha1Stream << "Hello";
  42. auto Hash = toHex(Sha1Stream.sha1());
  43. ASSERT_EQ("F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0", Hash);
  44. Sha1Stream << " World!";
  45. Hash = toHex(Sha1Stream.sha1());
  46. // Compute the non-split hash separately as a reference.
  47. llvm::raw_sha1_ostream NonSplitSha1Stream;
  48. NonSplitSha1Stream << "Hello World!";
  49. auto NonSplitHash = toHex(NonSplitSha1Stream.sha1());
  50. ASSERT_EQ(NonSplitHash, Hash);
  51. }
  52. TEST(raw_sha1_ostreamTest, Reset) {
  53. llvm::raw_sha1_ostream Sha1Stream;
  54. Sha1Stream << "Hello";
  55. auto Hash = toHex(Sha1Stream.sha1());
  56. ASSERT_EQ("F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0", Hash);
  57. Sha1Stream.resetHash();
  58. Sha1Stream << " World!";
  59. Hash = toHex(Sha1Stream.sha1());
  60. ASSERT_EQ("7447F2A5A42185C8CF91E632789C431830B59067", Hash);
  61. }