99 lines
2.0 KiB
C#
99 lines
2.0 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Collections.Generic;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace WorldOfPeacecraft
|
|
{
|
|
public class Parser
|
|
{
|
|
private Queue<string> Buffer = new Queue<string> ();
|
|
private AutoResetEvent BufferFilledEvent = new AutoResetEvent (false);
|
|
private Thread ParserThread;
|
|
private LinkedList<string> message;
|
|
private Regex LastLineRegex;
|
|
|
|
public Parser ()
|
|
{
|
|
ParserThread = new Thread (new ThreadStart (this.RunParser));
|
|
message = new LinkedList<string> ();
|
|
LastLineRegex = new Regex("^end:[0-9]+$");
|
|
}
|
|
|
|
public void RunParser ()
|
|
{
|
|
while (true) {
|
|
bool waitRequired = false;
|
|
lock (Buffer) {
|
|
if (Buffer.Count == 0) {
|
|
waitRequired = true;
|
|
BufferFilledEvent.Reset ();
|
|
}
|
|
}
|
|
if (waitRequired)
|
|
BufferFilledEvent.WaitOne ();
|
|
lock (Buffer) {
|
|
message.AddLast (Buffer.Dequeue ());
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Parse ()
|
|
{
|
|
// If package is not complete wait for more lines
|
|
if (!IsCompletePackage())
|
|
return;
|
|
|
|
}
|
|
|
|
public bool IsCompletePackage()
|
|
{
|
|
string lastLine = message.Last.Value;
|
|
return LastLineRegex.IsMatch(lastLine);
|
|
}
|
|
|
|
public void Stop ()
|
|
{
|
|
ParserThread.Abort ();
|
|
}
|
|
|
|
public void AddToBuffer (string s)
|
|
{
|
|
lock (Buffer) {
|
|
Buffer.Enqueue (s);
|
|
BufferFilledEvent.Set ();
|
|
}
|
|
}
|
|
|
|
private class Block
|
|
{
|
|
private string Name;
|
|
private ISet<Block> Blocks = new HashSet<Block>();
|
|
private Dictionary<String, String> Values = new Dictionary<String, String>();
|
|
|
|
public Block (String[] message, int start, int end)
|
|
{
|
|
int pos = start;
|
|
while (pos < end)
|
|
{
|
|
// Is the next element a block or a value?
|
|
if (message[pos].StartsWith("begin:"))
|
|
{
|
|
// It's a block
|
|
}
|
|
else
|
|
{
|
|
// It's a value
|
|
string name = StringUtils.SubstringBefore(message[pos], ":");
|
|
string val = StringUtils.SubstringAfter(message[pos], ":");
|
|
Values[name] = val;
|
|
pos++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|