aboutsummaryrefslogtreecommitdiff
path: root/llvm/unittests/CAS/OnDiskCommonUtils.h
blob: 57c8c228867fd72f9ec0bbf4ccb9d2305db9b156 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file Helper functions to test OnDiskCASDatabases.
//
//===----------------------------------------------------------------------===//

#include "llvm/CAS/BuiltinObjectHasher.h"
#include "llvm/CAS/OnDiskGraphDB.h"
#include "llvm/Support/BLAKE3.h"
#include "llvm/Testing/Support/Error.h"

namespace llvm::unittest::cas {

using namespace llvm::cas;
using namespace llvm::cas::ondisk;

using HasherT = BLAKE3;
using HashType = decltype(HasherT::hash(std::declval<ArrayRef<uint8_t> &>()));
using ValueType = std::array<char, 20>;

inline HashType digest(StringRef Data, ArrayRef<ArrayRef<uint8_t>> RefHashes) {
  return BuiltinObjectHasher<HasherT>::hashObject(
      RefHashes, arrayRefFromStringRef<char>(Data));
}

inline ObjectID digest(OnDiskGraphDB &DB, StringRef Data,
                       ArrayRef<ObjectID> Refs) {
  SmallVector<ArrayRef<uint8_t>, 8> RefHashes;
  for (ObjectID Ref : Refs)
    RefHashes.push_back(DB.getDigest(Ref));
  HashType Digest = digest(Data, RefHashes);
  std::optional<ObjectID> ID;
  EXPECT_THAT_ERROR(DB.getReference(Digest).moveInto(ID), Succeeded());
  return *ID;
}

inline HashType digest(StringRef Data) {
  return HasherT::hash(arrayRefFromStringRef(Data));
}

inline ValueType valueFromString(StringRef S) {
  ValueType Val;
  llvm::copy(S.substr(0, sizeof(Val)), Val.data());
  return Val;
}

inline Expected<ObjectID> store(OnDiskGraphDB &DB, StringRef Data,
                                ArrayRef<ObjectID> Refs) {
  ObjectID ID = digest(DB, Data, Refs);
  if (Error E = DB.store(ID, Refs, arrayRefFromStringRef<char>(Data)))
    return std::move(E);
  return ID;
}

inline Error printTree(OnDiskGraphDB &DB, ObjectID ID, raw_ostream &OS,
                       unsigned Indent = 0) {
  std::optional<ondisk::ObjectHandle> Obj;
  if (Error E = DB.load(ID).moveInto(Obj))
    return E;
  if (!Obj)
    return Error::success();
  OS.indent(Indent) << toStringRef(DB.getObjectData(*Obj)) << '\n';
  for (ObjectID Ref : DB.getObjectRefs(*Obj)) {
    if (Error E = printTree(DB, Ref, OS, Indent + 2))
      return E;
  }
  return Error::success();
}

} // namespace llvm::unittest::cas