View Javadoc
1   package org.davidmoten.text.utils;
2   
3   import java.util.Arrays;
4   
5   final class StringBuilder2 implements CharSequence {
6   
7       private char[] chars;
8       private int length;
9   
10      StringBuilder2(String s) {
11          this(s.toCharArray(), s.length());
12      }
13  
14      StringBuilder2() {
15          this(new char[16], 0);
16      }
17  
18      private StringBuilder2(char[] chars, int length) {
19          this.chars = chars;
20          this.length = length;
21      }
22  
23      char[] internalArray() {
24          return chars;
25      }
26  
27      @Override
28      public int length() {
29          return length;
30      }
31  
32      @Override
33      public char charAt(int index) {
34          return chars[index];
35      }
36  
37      @Override
38      public CharSequence subSequence(int start, int end) {
39          char[] chars2 = new char[end - start];
40          System.arraycopy(chars, start, chars2, 0, end - start);
41          return new StringBuilder2(chars2, chars2.length);
42      }
43  
44      public void append(StringBuilder2 s) {
45          int len = s.length();
46          checkSize(len);
47          System.arraycopy(s.chars, 0, chars, length, len);
48          length += len;
49      }
50  
51      private void checkSize(int len) {
52          if (length + len > chars.length) {
53              chars = Arrays.copyOf(chars, newSize(len));
54          }
55      }
56  
57      private int newSize(int len) {
58          int newSize = chars.length * 2;
59          if (newSize < length + len) {
60              newSize = length + len;
61          }
62          return newSize;
63      }
64  
65      public void setLength(int length) {
66          this.length = length;
67      }
68  
69      public void append(char ch) {
70          checkSize(1);
71          chars[length] = ch;
72          length++;
73      }
74  
75      public void delete(int start, int end) {
76          System.arraycopy(chars, end, chars, start, length - end);
77          length -= end - start;
78      }
79  
80      public String substring(int start, int end) {
81          return new String(chars, start, end - start);
82      }
83  
84      @Override
85      public String toString() {
86          return new String(chars, 0, length);
87      }
88  
89      /**
90       * Trims right space from this and returns {@code this}.
91       * 
92       * @return this
93       */
94      StringBuilder2 rightTrim() {
95          int i = length();
96          while (i > 0) {
97              if (!Character.isWhitespace(charAt(i - 1))) {
98                  break;
99              }
100             i--;
101         }
102         length = i;
103         return this;
104     }
105 
106 }