Debian Codegraph @

src/core/devfsdatasource.h

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright 2019 Juan Palacios <[email protected]>
3
4 #pragma once
5
6 #include "core/idatasource.h"
7 #include <fcntl.h>
8 #include <filesystem>
9 #include <functional>
10 #include <spdlog/spdlog.h>
11 #include <string>
12 #include <unistd.h>
13 #include <utility>
14
15 template<typename T>
16 class DevFSDataSource : public IDataSource<T>
17 {
18 public:
19 DevFSDataSource(std::filesystem::path const &path,
20 std::function<T(int)> &&reader) noexcept
21 : path_(path.string())
22 , reader_(std::move(reader))
23 {
24 fd_ = open(path.c_str(), O_RDONLY);
25 if (fd_ < 0)
26 SPDLOG_DEBUG("Cannot open {}", path.c_str());
27 }
28
29 ~DevFSDataSource() override
30 {
31 if (fd_ > 0)
32 close(fd_);
33 }
34
35 std::string source() const override
36 {
37 return path_;
38 }
39
40 bool read(T &data) override
41 {
42 data = reader_(fd_);
43 return true;
44 }
45
46 private:
47 std::string const path_;
48 std::function<T(int)> const reader_;
49 int fd_;
50 };