blob: 5a2bb85c0b6058c121cd8e73caef95400299b615 [file] [log] [blame]
Kun Yi9125e632019-01-09 13:52:06 -08001#pragma once
2
3#include "sys.hpp"
4
5#include <fcntl.h>
6#include <unistd.h>
7
8#include <string>
9
10namespace binstore
11{
12
13/**
14 * @brief Represents a file that supports read/write semantics
15 * TODO: leverage stdplus's support for smart file descriptors when it's ready.
16 */
17class SysFile
18{
19 public:
20 virtual ~SysFile() = default;
21
22 /**
23 * @brief Reads content at pos to char* buffer
24 * @param pos The byte pos into the file to read from
25 * @param count How many bytes to read
26 * @param buf Output data
27 * @returns The size of data read
28 * @throws std::system_error if read operation cannot be completed
29 */
30 virtual size_t readToBuf(size_t pos, size_t count, char* buf) const = 0;
31
32 /**
33 * @brief Reads content at pos
34 * @param pos The byte pos into the file to read from
35 * @param count How many bytes to read
36 * @returns The data read in a vector, whose size might be smaller than
37 * count if there is not enough to read.
38 * @throws std::system_error if read operation cannot be completed
39 */
40 virtual std::string readAsStr(size_t pos, size_t count) const = 0;
41
42 /**
43 * @brief Reads all the content in file after pos
44 * @param pos The byte pos to read from
45 * @returns The data read in a vector, whose size might be smaller than
46 * count if there is not enough to read.
47 * @throws std::system_error if read operation cannot be completed
48 */
49 virtual std::string readRemainingAsStr(size_t pos) const = 0;
50
51 /**
52 * @brief Writes all of data into file at pos
53 * @param pos The byte pos to write
54 * @returns void
55 * @throws std::system_error if write operation cannot be completed or
56 * not all of the bytes can be written
57 */
58 virtual void writeStr(const std::string& data, size_t pos) = 0;
59};
60
61class SysFileImpl : public SysFile
62{
63 public:
64 /**
65 * @brief Constructs sysFile specified by path and offset
66 * @param path The file path
67 * @param offset The byte offset relatively. Reading a sysfile at position 0
68 * actually reads underlying file at 'offset'
69 * @param sys Syscall operation interface
70 */
71 explicit SysFileImpl(const std::string& path, size_t offset = 0,
72 const internal::Sys* sys = &internal::sys_impl);
73 ~SysFileImpl();
74 SysFileImpl() = delete;
75 SysFileImpl(const SysFileImpl&) = delete;
76 SysFileImpl& operator=(SysFileImpl) = delete;
77
78 size_t readToBuf(size_t pos, size_t count, char* buf) const override;
79 std::string readAsStr(size_t pos, size_t count) const override;
80 std::string readRemainingAsStr(size_t pos) const override;
81 void writeStr(const std::string& data, size_t pos) override;
82
83 private:
84 int fd_;
85 size_t offset_;
86 void lseek(size_t pos) const;
87 const internal::Sys* sys;
88};
89
90} // namespace binstore