/
TokenReader.cs
77 lines (65 loc) · 1.85 KB
/
TokenReader.cs
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
using System;
using System.IO;
namespace ProtocolBuffers
{
public class TokenReader
{
readonly string whitespace = " \t\r\n";
readonly string singletoken = "{}=[];";
readonly string text;
public TokenReader(string text)
{
this.text = text;
}
public string Parsed { get { return text.Substring(0, offset); } }
public string Next { get { return text.Substring(offset, 1); } }
int offset;
private string GetChar()
{
if (offset >= text.Length)
{ throw new EndOfStreamException(); }
char c = text[offset];
offset += 1;
return c.ToString();
}
public string ReadNext()
{
//Character
string c;
//Skip whitespace characters
while (true)
{
c = GetChar();
if (whitespace.Contains(c))
continue;
break;
}
//Determine token type
if (singletoken.Contains(c))
return c.ToString();
//Follow token
string token = c;
bool parseString = false;
if (token == "\"")
{
parseString = true;
token = "";
}
while (true)
{
c = GetChar();
if (parseString)
{
if (c == "\"")
return token;
}
else if (whitespace.Contains(c) || singletoken.Contains(c))
{
offset -= 1;
return token;
}
token += c;
}
}
}
}