ScriptWriter.cs 2.8 KB

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