1//===----------------------------------------------------------------------===//
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#include "llvm/CAS/BuiltinObjectHasher.h"
10#include "llvm/ADT/ScopeExit.h"
11
12using namespace llvm;
13using namespace llvm::cas;
14
15template <class HasherT>
16Expected<typename BuiltinObjectHasher<HasherT>::HashT>
17BuiltinObjectHasher<HasherT>::hashFile(StringRef FilePath) {
18 BuiltinObjectHasher H;
19 H.updateSize(Size: 0); // 0 refs
20
21 sys::fs::file_t FD;
22 if (Error E = sys::fs::openNativeFileForRead(Name: FilePath).moveInto(Value&: FD))
23 return E;
24
25 llvm::scope_exit CloseFile([&]() { sys::fs::closeFile(F&: FD); });
26
27 ErrorOr<uint64_t> FileSize = sys::fs::file_size(FileHandle: FD);
28 if (!FileSize)
29 return createFileError(F: FilePath, EC: FileSize.getError());
30 H.updateSize(Size: *FileSize);
31
32 size_t ChunkSize = sys::fs::DefaultReadChunkSize;
33 SmallVector<char, 0> Buffer;
34 Buffer.resize_for_overwrite(N: ChunkSize);
35 for (;;) {
36 Expected<size_t> ReadBytes =
37 sys::fs::readNativeFile(FileHandle: FD, Buf: MutableArrayRef(Buffer.begin(), ChunkSize));
38 if (!ReadBytes)
39 return ReadBytes.takeError();
40 if (*ReadBytes == 0)
41 break;
42 H.Hasher.update(toStringRef(Input: ArrayRef(Buffer).take_front(N: *ReadBytes)));
43 }
44
45 return H.finish();
46}
47
48namespace llvm::cas {
49template class LLVM_EXPORT_TEMPLATE BuiltinObjectHasher<BLAKE3>;
50}
51