stream.cpp 1.31 KB
Newer Older
1
2
3
4
5
6
#include "crt.h"
#include "stream.h"
#include <iostream>

namespace YAML
{
7
	Stream::Stream(std::istream& input): pos(0), line(0), column(0), size(0), buffer(0)
8
	{
9
10
11
		if(!input)
			return;

12
13
14
15
16
17
		std::streambuf *pBuf = input.rdbuf();

		// store entire file in buffer
		size = pBuf->pubseekoff(0, std::ios::end, std::ios::in);
		pBuf->pubseekpos(0, std::ios::in);
		buffer = new char[size];
18
19
20
		size = pBuf->sgetn(buffer, size);  // Note: when reading a Windows CR/LF file,
		                                   // pubseekoff() counts CR/LF as two characters,
		                                   // setgn() reads CR/LF as a single LF character!
21
	}
22
23
24
25
26
27
28

	Stream::~Stream()
	{
		delete [] buffer;
	}


29
30
	char Stream::peek()
	{
31
		return buffer[pos];
32
33
	}
	
34
	Stream::operator bool() const
35
	{
36
		return pos < size;
37
38
39
40
41
42
	}

	// get
	// . Extracts a character from the stream and updates our position
	char Stream::get()
	{
43
44
		char ch = buffer[pos];
		pos++;
45
46
47
48
49
50
51
52
53
54
55
56
57
		column++;
		if(ch == '\n') {
			column = 0;
			line++;
		}
		return ch;
	}

	// get
	// . Extracts 'n' characters from the stream and updates our position
	std::string Stream::get(int n)
	{
		std::string ret;
58
		ret.reserve(n);
59
60
61
62
63
64
65
66
67
68
69
70
71
72
		for(int i=0;i<n;i++)
			ret += get();
		return ret;
	}

	// eat
	// . Eats 'n' characters and updates our position.
	void Stream::eat(int n)
	{
		for(int i=0;i<n;i++)
			get();
	}

}