Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
BaseStreamReader.h
浏览该文件的文档.
1// Copyright 2024 libsese
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
21#pragma once
22
23#include "sese/io/ByteBuilder.h"
24#include "sese/io/Stream.h"
25#include "sese/util/Util.h"
26
27#include <sstream>
28
29#ifdef _WIN32
30#pragma warning(disable : 4251)
31#endif
32
33namespace sese::io {
37template<typename T = char>
39public:
40 using Ptr = std::shared_ptr<BaseStreamReader<T>>;
41
42public:
47 explicit BaseStreamReader(const Stream::Ptr &source) {
48 this->sourceStream = source;
49 this->bufferStream = std::make_unique<ByteBuilder>();
50 }
51
57 bool read(T &ch) {
58 if (bufferStream->read(&ch, sizeof(T)) == 0) {
60 auto len = preRead();
61 if (0 == len) {
64 return false;
65 }
66 }
68 return true;
69 }
70
75 std::basic_string<T> readLine() {
76 std::basic_stringstream<T> string;
77 // auto canReadSize = bufferStream->getLength() - bufferStream->getCurrentReadPos();
78 auto can_read_size = bufferStream->getReadableSize();
79 if (can_read_size == 0) {
80 can_read_size += preRead();
81 }
82
83 if (can_read_size > 0) {
85 T ch;
86 while (read(ch)) {
87 if (ch == '\r' || ch == '\n') {
88 auto empty = string.rdbuf()->in_avail() == 0;
89 if (!empty) {
90 break;
91 } else {
92 continue;
93 }
94 }
95 string << ch;
96 }
97 }
98 bufferStream->freeCapacity();
99 return string.str();
100 }
101
106 // [[nodiscard]] size_t getAheadLength() const { return bufferStream->getLength() - bufferStream->getCurrentReadPos(); }
107
112 const ByteBuilder::Ptr &getBuffer() noexcept { return this->bufferStream; }
113
114private:
115 int64_t preRead() {
117 auto len = sourceStream->read(buffer, STRING_BUFFER_SIZE_FACTOR);
118 if (0 < len) {
119 bufferStream->write(buffer, len);
120 }
121 return len;
122 }
123
124private:
127};
128
131} // namespace sese::io