summaryrefslogtreecommitdiff
path: root/Source/Library/Common/IStream.proto.cpp
blob: 6176eac1ed9adf7413cbd1b707d926befdb7004e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "IStream.proto.h"

IStream::IStream() {
	m_buffer = NULL;
	m_ptr = 0;
	m_eof = false;
}

IStream::IStream(const IStream& other) {
	m_buffer = NULL;
	m_ptr = 0;
}

IStream::~IStream() {
	delete m_buffer;
}

bool IStream::populate() {
	if (m_eof) return false;
	String s = read();
	if (s.empty()) {
		m_eof = true;
		return false;
	}
	if (m_buffer == NULL) {
		m_buffer = new SimpleList<String>(s);
	} else {
		m_buffer->addAtEnd(s);
	}
	return true;
}

WChar IStream::getChar() {
	waitLock();
	if (m_buffer == 0) {
		if (!populate()) {
			unlock();
		   	return WChar("\0");
		}
	}
	WChar ret = m_buffer->v()[m_ptr];
	m_ptr++;
	if (m_ptr >= m_buffer->v().size()) {
		m_buffer = m_buffer->delThis();
		m_ptr = 0;
	}
	unlock();
	return ret;
}

String IStream::get(WChar delimiter) {
	waitLock();
	//calculate length of string to read
	if (m_buffer == 0) {
		unlock();
		if (!populate()) return "";
	}
	int length = 0, ptr = m_ptr;
	for (SimpleList<String> *iter = m_buffer; iter != 0;) {
		if (iter->v()[ptr] == delimiter) break;
		ptr++;
		length++;
		if (ptr >= iter->v().size()) {
			if (iter->next() == 0) populate();
			iter = iter->next();
			ptr = 0;
		}
	}
	//get it
	String ret(WChar(" "), length);
	for (int i = 0; i <= length; i++) {
		if (i != length) ret[i] = m_buffer->v()[m_ptr];
		m_ptr++;
		if (m_ptr >= m_buffer->v().size()) {
			m_buffer = m_buffer->delThis();
			m_ptr = 0;
		}
	}
	unlock();
	return ret;
}