-
Notifications
You must be signed in to change notification settings - Fork 21
/
LimitedLineLengthStringBuilder.cs
101 lines (84 loc) · 3.1 KB
/
LimitedLineLengthStringBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Text;
namespace WowClientDB2MySQLTableGenerator
{
public sealed class LimitedLineLengthStringBuilder
{
private readonly StringBuilder _builder;
private readonly StringBuilder _lineBuffer;
public int Length => _builder.Length + _lineBuffer.Length;
private bool _finalized;
private bool _ignoreLimit;
public int LineLength { get; set; }
public string WrappedLinePrefix = string.Empty;
public string WrappedLineSuffix = string.Empty;
public LimitedLineLengthStringBuilder() : this(150)
{
}
public LimitedLineLengthStringBuilder(int lineLength)
{
_builder = new StringBuilder();
_lineBuffer = new StringBuilder(lineLength);
LineLength = lineLength;
}
public LimitedLineLengthStringBuilder Nonbreaking() { _ignoreLimit = true; return this; }
public LimitedLineLengthStringBuilder Append(string value)
{
if (_finalized)
throw new InvalidOperationException("Cannot append after finalizing.");
if (!_ignoreLimit)
FlushIfNeeded(value);
_lineBuffer.Append(value);
_ignoreLimit = false;
return this;
}
public LimitedLineLengthStringBuilder AppendLine()
{
return AppendLine(string.Empty);
}
public LimitedLineLengthStringBuilder AppendLine(string value)
{
if (_finalized)
throw new InvalidOperationException("Cannot append after finalizing.");
if (!_ignoreLimit)
FlushIfNeeded(value);
_lineBuffer.Append(value);
_builder.AppendLine(_lineBuffer.ToString());
_lineBuffer.Clear();
_ignoreLimit = false;
return this;
}
public string Finalize()
{
if (!_finalized && _lineBuffer.Length > 0)
_builder.Append(_lineBuffer.ToString());
_finalized = true;
return _builder.ToString();
}
private void FlushIfNeeded(string value)
{
if (_lineBuffer.Length + value.Length > LineLength)
{
_builder.Append(_lineBuffer.ToString());
_builder.AppendLine(WrappedLineSuffix);
_lineBuffer.Clear();
_lineBuffer.Append(WrappedLinePrefix);
}
}
public LimitedLineLengthStringBuilder Remove(int startIndex, int length)
{
if (startIndex > Length - length)
throw new IndexOutOfRangeException();
if (startIndex > _builder.Length)
_lineBuffer.Remove(startIndex - _builder.Length, length);
else if (startIndex <= _builder.Length - length)
_builder.Remove(startIndex, length);
else
{
_builder.Remove(startIndex, _builder.Length - startIndex);
_lineBuffer.Remove(0, startIndex + length - _builder.Length);
}
return this;
}
}
}