2018-12-31 20:04:05 +01:00
|
|
|
//
|
2024-01-01 01:07:21 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2024
|
2018-12-31 20:04:05 +01:00
|
|
|
//
|
|
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
//
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "td/utils/common.h"
|
|
|
|
#include "td/utils/port/FileFd.h"
|
|
|
|
#include "td/utils/Slice.h"
|
|
|
|
#include "td/utils/Status.h"
|
|
|
|
|
|
|
|
namespace td {
|
2019-07-21 20:07:07 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
class BufferedReader {
|
|
|
|
public:
|
2019-07-06 13:29:15 +02:00
|
|
|
explicit BufferedReader(FileFd &file, size_t buff_size = 8152)
|
2018-12-31 20:04:05 +01:00
|
|
|
: file_(file), buff_(buff_size), begin_pos_(0), end_pos_(0) {
|
|
|
|
}
|
|
|
|
|
|
|
|
Result<size_t> read(MutableSlice slice) TD_WARN_UNUSED_RESULT;
|
|
|
|
|
|
|
|
private:
|
|
|
|
FileFd &file_;
|
|
|
|
vector<char> buff_;
|
|
|
|
size_t begin_pos_;
|
|
|
|
size_t end_pos_;
|
|
|
|
};
|
|
|
|
|
|
|
|
inline Result<size_t> BufferedReader::read(MutableSlice slice) {
|
|
|
|
size_t available = end_pos_ - begin_pos_;
|
|
|
|
if (available >= slice.size()) {
|
|
|
|
// have enough data in buffer
|
2019-07-27 00:27:22 +02:00
|
|
|
slice.copy_from({&buff_[begin_pos_], slice.size()});
|
2018-12-31 20:04:05 +01:00
|
|
|
begin_pos_ += slice.size();
|
|
|
|
return slice.size();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (available) {
|
2019-07-27 00:27:22 +02:00
|
|
|
slice.copy_from({&buff_[begin_pos_], available});
|
2018-12-31 20:04:05 +01:00
|
|
|
begin_pos_ += available;
|
|
|
|
slice.remove_prefix(available);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (slice.size() > buff_.size() / 2) {
|
|
|
|
TRY_RESULT(result, file_.read(slice));
|
|
|
|
return result + available;
|
|
|
|
}
|
|
|
|
|
|
|
|
TRY_RESULT(result, file_.read({&buff_[0], buff_.size()}));
|
|
|
|
begin_pos_ = 0;
|
|
|
|
end_pos_ = result;
|
|
|
|
|
2018-02-12 11:37:54 +01:00
|
|
|
size_t left = min(end_pos_, slice.size());
|
2019-07-27 00:27:22 +02:00
|
|
|
slice.copy_from({&buff_[0], left});
|
|
|
|
begin_pos_ = left;
|
2018-12-31 20:04:05 +01:00
|
|
|
return left + available;
|
|
|
|
}
|
2019-07-21 20:07:07 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
} // namespace td
|