SNode.C
Loading...
Searching...
No Matches
FileReader.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - a slim toolkit for network communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "core/file/FileReader.h"
21
22#include "core/State.h"
23
24#ifndef DOXYGEN_SHOULD_SKIP_THIS
25
26#include "core/system/unistd.h"
27
28#include <cerrno>
29#include <vector>
30
31#endif /* DOXYGEN_SHOULD_SKIP_THIS */
32
33constexpr int MF_READSIZE = 16384;
34
35namespace core::file {
36
37 FileReader::FileReader(int fd, const std::string& name, std::size_t pufferSize, int openErrno)
41 , openErrno(openErrno) {
42 }
43
44 FileReader* FileReader::open(const std::string& path) {
45 errno = 0;
46
47 const int fd = core::system::open(path.c_str(), O_RDONLY);
48
49 return new FileReader(fd, "FileReader: " + path, MF_READSIZE, fd < 0 ? errno : 0);
50 }
51
53 return getFd() >= 0;
54 }
55
56 void FileReader::onEvent([[maybe_unused]] const utils::Timeval& currentTime) {
57 if (running && core::eventLoopState() != core::State::STOPPING) {
58 if (!suspended) {
59 std::vector<char> puffer(pufferSize);
60
61 const ssize_t ret = core::system::read(getFd(), puffer.data(), puffer.capacity());
62 if (ret > 0) {
63 if (this->send(puffer.data(), static_cast<std::size_t>(ret)) < 0) {
64 running = false;
65
66 this->error(errno);
67 }
68 } else {
69 running = false;
70
71 if (ret == 0) {
72 this->eof();
73 } else {
74 this->error(errno);
75 }
76 }
77
78 span();
79 }
80 } else {
81 delete this;
82 }
83 }
84
85 void FileReader::start() {
86 if (!running) {
87 running = true;
88 span();
89 }
90 }
91
93 if (running) {
94 suspended = true;
95 }
96 }
97
99 if (running) {
100 suspended = false;
101 span();
102 }
103 }
104
105 void FileReader::stop() {
106 if (running) {
107 this->eof();
108
109 running = false;
110 span();
111 }
112 }
113
114} // namespace core::file
constexpr int MF_READSIZE
void onEvent(const utils::Timeval &currentTime) override
FileReader(int fd, const std::string &name, std::size_t pufferSize, int openErrno)
bool isOpen() override
void error(int errnum)
Definition Source.cpp:87