MyGUI 3.5.3
MyGUI_DataStream.cpp
Go to the documentation of this file.
1/*
2 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
3 * Distributed under the MIT License
4 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
5 */
6
7#include "MyGUI_Precompiled.h"
8#include "MyGUI_DataStream.h"
9
10#include <limits>
11
12namespace MyGUI
13{
14
15 DataStream::DataStream() :
16 mStream(nullptr),
17 mSize((size_t)-1)
18 {
19 }
20
21 DataStream::DataStream(std::istream* _stream) :
22 mStream(_stream),
23 mSize((size_t)-1)
24 {
25 }
26
27 size_t DataStream::size()
28 {
29 if (mStream == nullptr || mStream->rdbuf() == nullptr)
30 return 0;
31 if (mSize == (size_t)-1)
32 {
33 // Query the buffer directly to preserve stream flags, including EOF and errors.
34 auto* buffer = mStream->rdbuf();
35 const auto position = buffer->pubseekoff(0, std::ios::cur, std::ios::in);
36 if (position == std::streampos(-1))
37 return 0;
38 const auto end = buffer->pubseekoff(0, std::ios::end, std::ios::in);
39 const auto restored = buffer->pubseekpos(position, std::ios::in);
40 if (end == std::streampos(-1) || restored == std::streampos(-1))
41 return 0;
42 mSize = static_cast<size_t>(end);
43 }
44 return mSize;
45 }
46
47 bool DataStream::eof()
48 {
49 return mStream == nullptr ? true : mStream->eof();
50 }
51
52 void DataStream::readline(std::string& _source, Char _delim)
53 {
54 if (mStream == nullptr)
55 return;
56 std::getline(*mStream, _source, (char)_delim);
57 }
58
59 size_t DataStream::read(void* _buf, size_t _count)
60 {
61 if (mStream == nullptr || _count == 0)
62 return 0;
63 const auto count = std::min(_count, static_cast<size_t>(std::numeric_limits<std::streamsize>::max()));
64 mStream->read(static_cast<char*>(_buf), static_cast<std::streamsize>(count));
65 return static_cast<size_t>(mStream->gcount());
66 }
67
68} // namespace MyGUI