ScriptWriter.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Text;
  3. namespace FF8
  4. {
  5. public sealed class ScriptWriter
  6. {
  7. public Int32 Indent { get; set; }
  8. private readonly StringBuilder _sb;
  9. private Boolean _newLine;
  10. public Boolean HasWhiteLine { get; private set; }
  11. public ScriptWriter(Int32 capacity = 8096)
  12. {
  13. _sb = new StringBuilder(capacity);
  14. }
  15. public void AppendLine()
  16. {
  17. if (_newLine)
  18. HasWhiteLine = true;
  19. _sb.AppendLine();
  20. _newLine = true;
  21. }
  22. public void AppendLine(String text)
  23. {
  24. AppendIndent();
  25. _sb.AppendLine(text);
  26. _newLine = true;
  27. HasWhiteLine = (text == "{");
  28. }
  29. public void Append(String text)
  30. {
  31. AppendIndent();
  32. _sb.Append(text);
  33. }
  34. private void AppendIndent()
  35. {
  36. if (_newLine)
  37. {
  38. for (Int32 i = 0; i < Indent; i++)
  39. _sb.Append(" ");
  40. _newLine = false;
  41. HasWhiteLine = false;
  42. }
  43. }
  44. public String Release()
  45. {
  46. String result = _sb.ToString();
  47. _sb.Clear();
  48. Indent = 0;
  49. _newLine = true;
  50. HasWhiteLine = false;
  51. return result;
  52. }
  53. public override String ToString()
  54. {
  55. return _sb.ToString();
  56. }
  57. public State RememberState()
  58. {
  59. return new State(this);
  60. }
  61. public sealed class State
  62. {
  63. private readonly ScriptWriter _sw;
  64. private Int32 _indent;
  65. private Boolean _newLine;
  66. private Boolean _hasEmptyLine;
  67. private Int32 _length;
  68. public State(ScriptWriter sw)
  69. {
  70. _sw = sw;
  71. _indent = _sw.Indent;
  72. _newLine = _sw._newLine;
  73. _length = _sw._sb.Length;
  74. _hasEmptyLine = _sw.HasWhiteLine;
  75. }
  76. public Boolean IsChanged => _length != _sw._sb.Length;
  77. public void Cancel()
  78. {
  79. _sw.Indent = _indent;
  80. _sw._newLine = _newLine;
  81. _sw.HasWhiteLine = _hasEmptyLine;
  82. _sw._sb.Length = _length;
  83. }
  84. }
  85. }
  86. }