TextInputStream.cxx 1.97 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20
#include "TextInputStream.hxx"
21
#include "InputStream.hxx"
22
#include "util/TextFile.hxx"
23
#include "Log.hxx"
24

25 26
#include <stdexcept>

27
#include <assert.h>
28

29
TextInputStream::TextInputStream(InputStreamPtr &&_is) noexcept
30 31
	:is(std::move(_is)) {}

32
TextInputStream::~TextInputStream() noexcept {}
33

34 35 36
char *
TextInputStream::ReadLine()
{
37
	char *line = ReadBufferedLine(buffer);
38 39
	if (line != nullptr)
		return line;
40

41 42
	buffer.Shift();

43 44 45
	while (true) {
		auto dest = buffer.Write();
		if (dest.size < 2) {
46 47
			/* line too long: terminate the current
			   line */
48

49
			assert(!dest.empty());
50
			dest[0] = 0;
51
			line = buffer.Read().data;
52
			buffer.Clear();
53
			return line;
54
		}
55

56 57 58 59
		/* reserve one byte for the null terminator if the
		   last line is not terminated by a newline
		   character */
		--dest.size;
60

61
		size_t nbytes = is->LockRead(dest.data, dest.size);
62

63 64
		buffer.Append(nbytes);

65
		line = ReadBufferedLine(buffer);
66 67 68
		if (line != nullptr)
			return line;

69 70 71 72 73
		if (nbytes == 0) {
			/* end of file: see if there's an unterminated
			   line */

			dest = buffer.Write();
74
			assert(!dest.empty());
75 76 77 78
			dest[0] = 0;

			auto r = buffer.Read();
			buffer.Clear();
79
			return r.empty()
80 81 82
				? nullptr
				: r.data;
		}
83
	}
84
}