summaryrefslogtreecommitdiff
path: root/src/hasher.cc
blob: dd94ce490d2b932cd0c60163782b4ebf06be08c1 (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
#include "common.hh"

#include "hash_method.hh"
#include "hasher.hh"
#include "io.hh"
#include "logger.hh"
#include "task_runner.hh"

#include <errno.h>
#include <string.h>

namespace {

class HasherImpl : public Hasher {
public:
  HasherImpl(std::shared_ptr<Logger> logger,
             std::shared_ptr<TaskRunner> runner,
             size_t threads)
    : logger_(std::move(logger)), runner_(std::move(runner)),
      workers_(TaskRunner::create(threads)) {
  }

  void hash(std::filesystem::path path,
            std::function<void(std::string, uint64_t)> callback) override {
    workers_->post(std::bind(&HasherImpl::do_hash, this, path, callback));
  }

private:
  void do_hash(std::filesystem::path path,
               std::function<void(std::string, uint64_t)> callback) {
    auto fd = io::open(path, io::open_flags::rdonly);
    std::string result;
    uint64_t size = 0;
    if (fd) {
      auto method = HashMethod::sha256();
      char buffer[1 * 1024 * 1024];
      while (true) {
        auto got = io::read(fd.get(), buffer, sizeof(buffer));
        if (got < 0) {
          logger_->warn("Error reading: %s: %s", path.c_str(),
                        strerror(errno));
          size = 0;
          break;
        }
        if (got == 0) {
          result = method->finish();
          break;
        }
        size += got;
        method->update(buffer, got);
      }
    } else {
      logger_->warn("Unable to open: %s: %s", path.c_str(),
                    strerror(errno));
    }
    runner_->post(std::bind(callback, result, size));
  }

  std::shared_ptr<Logger> logger_;
  std::shared_ptr<TaskRunner> runner_;
  std::unique_ptr<TaskRunner> workers_;
};

}  // namespace

std::unique_ptr<Hasher> Hasher::create(std::shared_ptr<Logger> logger,
                                       std::shared_ptr<TaskRunner> runner,
                                       size_t threads) {
  return std::make_unique<HasherImpl>(std::move(logger), std::move(runner),
                                      threads);
}