TextInputStream.cxx 2.07 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 "config.h"
21
#include "TextInputStream.hxx"
22
#include "InputStream.hxx"
23
#include "util/TextFile.hxx"
24
#include "Log.hxx"
25

26 27
#include <stdexcept>

28
#include <assert.h>
29

30 31 32 33 34
TextInputStream::TextInputStream(InputStreamPtr &&_is)
	:is(std::move(_is)) {}

TextInputStream::~TextInputStream() {}

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

42 43
	buffer.Shift();

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

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

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

62 63 64 65
		size_t nbytes;

		try {
			nbytes = is->LockRead(dest.data, dest.size);
66 67
		} catch (...) {
			LogError(std::current_exception());
68 69 70
			return nullptr;
		}

71 72
		buffer.Append(nbytes);

73
		line = ReadBufferedLine(buffer);
74 75 76
		if (line != nullptr)
			return line;

77 78 79 80 81
		if (nbytes == 0) {
			/* end of file: see if there's an unterminated
			   line */

			dest = buffer.Write();
82
			assert(!dest.empty());
83 84 85 86
			dest[0] = 0;

			auto r = buffer.Read();
			buffer.Clear();
87
			return r.empty()
88 89 90
				? nullptr
				: r.data;
		}
91
	}
92
}