tools/incparser/ParseWriter.cs
author David Anderson <dvander@alliedmods.net>
Wed Dec 19 01:47:26 2007 +0000 (2007-12-19)
changeset 1806 b1ba61360272
parent 824 0e9a2c98c9aa
child 2019 9f473114a511
permissions -rw-r--r--
fixed build
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace incparser
     6 {
     7     class ParseWriter
     8     {
     9         private int level;
    10         private StringBuilder data;
    11 
    12         public int Level
    13         {
    14             get
    15             {
    16                 return level;
    17             }
    18         }
    19 
    20         public string Contents
    21         {
    22             get
    23             {
    24                 return data.ToString();
    25             }
    26         }
    27 
    28         public ParseWriter()
    29         {
    30             level = 0;
    31             data = new StringBuilder();
    32         }
    33 
    34         public void BeginSection(string name)
    35         {
    36             WriteLine("\"" + PrepString(name) + "\"");
    37             WriteLine("{");
    38             level++;
    39         }
    40 
    41         public void WritePair(string key, string value)
    42         {
    43             WriteLine("\"" + PrepString(key) + "\"\t\t\"" + PrepString(value) + "\"");
    44         }
    45 
    46         public void EndSection()
    47         {
    48             if (--level < 0)
    49             {
    50                 throw new System.Exception("Writer nesting level went out of bounds");
    51             }
    52             WriteLine("}");
    53         }
    54 
    55         private void WriteLine(string line)
    56         {
    57             Tabinate();
    58             data.Append(line + "\n");
    59         }
    60 
    61         private void Tabinate()
    62         {
    63             for (int i = 0; i < level; i++)
    64             {
    65                 data.Append("\t");
    66             }
    67         }
    68 
    69         private string PrepString(string text)
    70         {
    71             /* Escape all escaped newlines (so they can be unescaped later) */
    72             text = text.Replace("\\n", "\\\\n");
    73             /* Escape all literal newlines */
    74             text = text.Replace("\n", "\\n");
    75             text = text.Replace("\r", "");
    76             /* Remove escaped quotations */
    77             text = text.Replace("\\\"", "\"");
    78             /* Replace all quotations with escaped ones now */
    79             text = text.Replace("\"", "\\\"");
    80             return text;
    81         }
    82     }
    83 }