|
| 1 | +package Text |
| 2 | + |
| 3 | +type StringBuilder struct { |
| 4 | + data []rune |
| 5 | + position int |
| 6 | +} |
| 7 | + |
| 8 | +// Creates a new instance of the StringBuilder with preallocated array |
| 9 | +func NewStringBuilder(initialCapacity int) *StringBuilder { |
| 10 | + return &StringBuilder{data: make([]rune, initialCapacity)} |
| 11 | +} |
| 12 | + |
| 13 | +// Appends a text to the StringBuilder instance |
| 14 | +func (s *StringBuilder) Append(text string) { |
| 15 | + newLen := s.position + len(text) |
| 16 | + if newLen > cap(s.data) { |
| 17 | + s.grow(newLen) |
| 18 | + } |
| 19 | + |
| 20 | + copy(s.data[s.position:], []rune(text)) |
| 21 | + s.position = newLen |
| 22 | +} |
| 23 | + |
| 24 | +// Appends a text and a new line character to the StringBuilder instance |
| 25 | +func (s *StringBuilder) AppendLine(text string) { |
| 26 | + s.Append(text) |
| 27 | + s.Append("\n") |
| 28 | +} |
| 29 | + |
| 30 | +// Appends a single character to the StringBuilder instance |
| 31 | +func (s *StringBuilder) AppendRune(char rune) { |
| 32 | + newLen := s.position + 1 |
| 33 | + if newLen > cap(s.data) { |
| 34 | + s.grow(newLen) |
| 35 | + } |
| 36 | + |
| 37 | + s.data[s.position] = char |
| 38 | + s.position++ |
| 39 | +} |
| 40 | + |
| 41 | +// Returns the current length of the represented string |
| 42 | +func (s *StringBuilder) Len() int { |
| 43 | + return s.position |
| 44 | +} |
| 45 | + |
| 46 | +// Returns the represented string |
| 47 | +func (s *StringBuilder) ToString() string { |
| 48 | + return string(s.data[:s.position]) |
| 49 | +} |
| 50 | + |
| 51 | +func (s *StringBuilder) grow(lenToAdd int) { |
| 52 | + // Grow times 2 until lenToAdd fits |
| 53 | + newLen := cap(s.data) |
| 54 | + |
| 55 | + if cap(s.data) == 0 { |
| 56 | + newLen = 8 |
| 57 | + } |
| 58 | + |
| 59 | + for newLen < lenToAdd { |
| 60 | + newLen = newLen * 2 |
| 61 | + } |
| 62 | + |
| 63 | + new := make([]rune, newLen) |
| 64 | + copy(new, s.data) |
| 65 | + s.data = new |
| 66 | +} |
0 commit comments