LibHac/build/CodeGen/IndentingStringBuilder.cs

95 lines
2.2 KiB
C#
Raw Permalink Normal View History

2020-02-24 22:45:51 +01:00
using System;
using System.Text;
2021-11-14 20:08:57 +01:00
namespace LibHacBuild.CodeGen;
public class IndentingStringBuilder
2020-02-24 22:45:51 +01:00
{
2021-11-14 20:08:57 +01:00
public int LevelSize { get; set; } = 4;
public int Level { get; private set; }
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
private StringBuilder _sb = new StringBuilder();
private string _indentation = string.Empty;
private bool _hasIndentedCurrentLine;
private bool _lastLineWasEmpty;
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder() { }
public IndentingStringBuilder(int levelSize) => LevelSize = levelSize;
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public void SetLevel(int level)
{
Level = Math.Max(level, 0);
_indentation = new string(' ', Level * LevelSize);
}
public void IncreaseLevel() => SetLevel(Level + 1);
public void DecreaseLevel() => SetLevel(Level - 1);
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder AppendLine()
{
_sb.AppendLine();
_hasIndentedCurrentLine = false;
_lastLineWasEmpty = true;
return this;
}
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder AppendSpacerLine()
{
if (!_lastLineWasEmpty)
2020-02-24 22:45:51 +01:00
{
_sb.AppendLine();
_hasIndentedCurrentLine = false;
2020-02-26 08:55:53 +01:00
_lastLineWasEmpty = true;
}
2021-11-14 20:08:57 +01:00
return this;
}
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder AppendLine(string value)
{
IndentIfNeeded();
_sb.AppendLine(value);
_hasIndentedCurrentLine = false;
_lastLineWasEmpty = string.IsNullOrWhiteSpace(value);
return this;
}
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder Append(string value)
{
IndentIfNeeded();
_sb.Append(value);
return this;
}
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder AppendLineAndIncrease(string value)
{
AppendLine(value);
IncreaseLevel();
return this;
}
2020-02-24 22:45:51 +01:00
2021-11-14 20:08:57 +01:00
public IndentingStringBuilder DecreaseAndAppendLine(string value)
{
DecreaseLevel();
AppendLine(value);
return this;
}
2020-02-24 22:45:51 +01:00
public IndentingStringBuilder DecreaseAndAppend(string value)
{
DecreaseLevel();
Append(value);
return this;
}
2021-11-14 20:08:57 +01:00
private void IndentIfNeeded()
{
if (!_hasIndentedCurrentLine)
2020-02-24 22:45:51 +01:00
{
2021-11-14 20:08:57 +01:00
_sb.Append(_indentation);
_hasIndentedCurrentLine = true;
2020-02-24 22:45:51 +01:00
}
}
2021-11-14 20:08:57 +01:00
public override string ToString() => _sb.ToString();
}