-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMutableString.java
More file actions
4669 lines (4019 loc) · 148 KB
/
MutableString.java
File metadata and controls
4669 lines (4019 loc) · 148 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DSI utilities
*
* Copyright (C) 2002-2023 Paolo Boldi and Sebastiano Vigna
*
* This program and the accompanying materials are made available under the
* terms of the GNU Lesser General Public License v2.1 or later,
* which is available at
* http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html,
* or the Apache Software License 2.0, which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*
* SPDX-License-Identifier: LGPL-2.1-or-later OR Apache-2.0
*/
package it.unimi.dsi.lang;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.UTFDataFormatException;
import java.io.Writer;
import it.unimi.dsi.fastutil.chars.Char2CharMap;
import it.unimi.dsi.fastutil.chars.CharArrays;
import it.unimi.dsi.fastutil.chars.CharList;
import it.unimi.dsi.fastutil.chars.CharSet;
import it.unimi.dsi.fastutil.objects.ObjectArrays;
import it.unimi.dsi.util.TextPattern;
/**
* Fast, compact, optimized & versatile mutable strings.
*
* <h2>Motivation</h2>
*
* <P>
* The classical Java string classes, {@link java.lang.String} and {@link java.lang.StringBuffer}
* (or {@link StringBuilder}), lie at the extreme of a spectrum (immutable and mutable).
*
* <P>
* However, large-scale text indexing requires some features that are not provided by these classes:
* in particular, the possibility of using a mutable string, once frozen, in the same optimized way
* of an immutable string.
*
* <P>
* In a typical scenario you are dividing text into words (so you use a <em>mutable</em> string to
* accumulate characters). Once you've got your word, you would like to check whether this word is
* in a dictionary <em>without creating a new object</em>. However, equality of {@link StringBuilder
* string builders} is not defined on their content, and storing words after a conversion to
* <code>String</code> will not help either, as then you would need to convert the current mutable
* string into an immutable one (thus creating a new object) <em>before deciding whether you need to
* store it</em>.
*
* <P>
* This class tries to make the best of both worlds, and thus aims at being a Better
* Mousetrap™.
*
* <P>
* You can read more details about the design of <code>MutableString</code> in Paolo Boldi and
* Sebastiano Vigna, “<a href="http://vigna.di.unimi.it/papers.php#BoVMSJ">Mutable strings in
* Java: Design, implementation and lightweight text-search algorithms</a>”, <i>Sci. Comput.
* Programming</i>, 54(1):3-23, 2005.
*
* <h2>Features</h2>
*
* Mutable strings come in two flavours: <em>compact</em> and <em>loose</em>. A mutable string
* created by the empty constructor or the constructor specifying a capacity is loose. All other
* constructors create compact mutable strings. In most cases, you can completely forget whether
* your mutable strings are loose or compact and get good performance.
*
* <ul>
*
* <li>Mutable strings occupy little space— their only attributes are a backing character
* array and an integer;
*
* <li>their methods try to be as efficient as possible:for instance, if some limitation on a
* parameter is implied by limitation on array access, we do not check it explicitly, and Bloom
* filters are used to speed up {@link #replace(char[],String[]) multi-character substitutions};
*
* <li>they let you access directly the backing array (at your own risk);
*
* <li>they implement {@link CharSequence}, so, for instance, you can match or split a mutable
* string against a regular expression using the {@linkplain java.util.regex.Pattern standard Java
* API};
*
* <li>they implement {@link Appendable}, so they can be used with {@link java.util.Formatter} and
* similar classes;
*
* <li>{@code null} is not accepted as a string argument;
*
* <li>compact mutable strings have a slow growth; loose mutable strings have a fast growth;
*
* <li>hash codes of compact mutable strings are cached (for faster equality checks);
*
* <li>all search-based methods ({@link #indexOf(MutableString,int)}, etc.) use a mini (single-word)
* Bloom filter to implement the last-character heuristics from the Boyer–Moore
* algorithm—they are much faster than the {@link String} counterparts;
*
* <li>typical conversions such as trimming, upper/lower casing and replacements are made in place,
* with minimal reallocations;
*
* <li>all methods try, whenever it is possible, to return <code>this</code>, so you can chain
* methods as in <code>s.length(0).append("foo").append("bar")</code>;
*
* <li>you can write or print a mutable string without creating a <code>String</code> by using
* {@link #write(Writer)}, {@link #print(PrintWriter)} and {@link #println(PrintWriter)}; you can
* read it back using {@link #read(Reader,int)}.
*
* <li>you can write <em>any</em> mutable string in (length-prefixed) UTF-8 format by using
* {@link #writeSelfDelimUTF8(DataOutput)}—you are not limited to strings whose UTF-8 encoded
* length fits 16 bits; notice however that surrogate pairs will not be coalesced into a single code
* point, so you must re-read such strings using the same method;
*
* <li>you can {@link #wrap(char[]) wrap} any character array into a mutable string;
*
* <li>this class is not final: thus, you can add your own methods to specialized versions.
*
* </ul>
*
* <P>
* Committing to use this class for such an ubiquitous data structure as strings may seem dangerous,
* as standard string classes are by now tested and stable. However, this class has been heavily
* regression (and torture) tested on all methods, and we believe it is very reliable.
*
* <P>
* To simplify the transition to mutable strings, we have tried to make mixing string classes
* simpler by providing polymorphic versions of all methods accepting one or more
* strings—whenever you must specify a string you can usually provide a
* <code>MutableString</code>, a <code>String</code>, or a generic <code>CharSequence</code>.
*
* <P>
* Note that usually we provide a specific method for <code>String</code>. This duplication may seem
* useless, as <code>String</code> implements <code>CharSequence</code>. However, invoking methods
* on an interface is slower than invoking methods on a class, and we expect constant strings to
* appear often in such methods.
*
* <h2>The Reallocation Heuristic</h2>
*
* <P>
* Backing array reallocations use a heuristic based on looseness. Whenever an operation changes the
* length, compact strings are resized to fit <em>exactly</em> the new content, whereas the capacity
* of a loose string is never shortened, and enlargements maximize the new length required with the
* double of the current capacity.
*
* <P>
* The effect of this policy is that loose strings will get large buffers quickly, but compact
* strings will occupy little space and perform very well in data structures using hash codes.
*
* <P>
* For instance, you can easily reuse a loose mutable string calling {@link #length(int) length(0)}
* (which does <em>not</em> reallocate the backing array).
*
* <P>
* In any case, you can call {@link #compact()} and {@link #loose()} to force the respective
* condition.
*
* <h2>Disadvantages</h2>
*
* <P>
* The main disadvantage of mutable strings is that their substrings cannot share their backing
* arrays, so if you need to generate many substrings you may want to use <code>String</code>.
* However, {@link #subSequence(int,int) subSequence()} returns a {@link CharSequence} that shares
* the backing array.
*
* <h2>Warnings</h2>
*
* There are a few differences with standard string classes you should be aware of.
*
* <ol>
*
* <li><STRONG>This class is not synchronized</STRONG>. If multiple threads access an object of this
* class concurrently, and at least one of the threads modifies it, it must be synchronized
* externally.
*
* <li>This class implements polymorphic versions of the {@link #equals(Object) equals} method that
* compare the <em>content</em> of <code>String</code>s and <code>CharSequence</code>s, so that you
* can easily do checks like
*
* <PRE>
* mutableString.equals("Hello")
* </PRE>
*
* Thus, you must <em>not</em> mix mutable strings with <code>CharSequence</code>s in collections as
* equality between objects of those types is not symmetric.
*
* <li>When the length of a string or char array argument is zero, some methods may just do nothing
* even if other parameters are out of bounds.
*
* <li>The output of {@link #writeSelfDelimUTF8(DataOutput) writeSelfDelimUTF8()} is <em>not</em>
* compatible with the usual Java {@link DataOutput#writeUTF(String) writeUTF()}.
*
* <li>Even if this class is not final, most <em>methods</em> are declared final for efficiency, so
* you cannot override them (why should you ever want to override {@link #array()}?).
*
* </ol>
*
* @author Sebastiano Vigna
* @author Paolo Boldi
* @since 0.3
*/
public class MutableString implements Serializable, CharSequence, Appendable, Comparable<MutableString>, Cloneable {
/** A mutable string containing <code>null</code>, used for implementing {@link Appendable}'s semantics. */
private final static MutableString NULL = new MutableString("null");
/** The backing array. */
protected transient char[] array;
/** This mutable string is compact iff this attribute is negative.
* It the string is compact, the attribute is its hash code (-1 denotes the invalid
* hash code). If the string is loose, the attribute is the number of
* characters actually stored in the backing array. */
protected transient int hashLength;
public static final long serialVersionUID = -518929984008928417L;
/** Creates a new loose empty mutable string with capacity 2. */
public MutableString() {
this(2);
}
/** Creates a new loose empty mutable string with given capacity.
*
* @param capacity the required capacity.
*/
public MutableString(final int capacity) {
array = capacity != 0 ? new char[capacity] : CharArrays.EMPTY_ARRAY;
}
/** Creates a new compact mutable string with given length.
*
* @param length the desired length of the new string.
*/
private void makeCompactMutableString(final int length) {
array = length != 0 ? new char[length] : CharArrays.EMPTY_ARRAY;
hashLength = -1;
}
/** Creates a new compact mutable string copying a given mutable string.
*
* @param s the initial contents of the string.
*/
public MutableString(final MutableString s) {
makeCompactMutableString(s.length());
System.arraycopy(s.array, 0, array, 0, array.length);
}
/** Creates a new compact mutable string copying a given <code>String</code>.
*
* @param s the initial contents of the string.
*/
public MutableString(final String s) {
makeCompactMutableString(s.length());
s.getChars(0, array.length, array, 0);
}
/** Creates a new compact mutable string copying a given <code>CharSequence</code>.
*
* @param s the initial contents of the string.
*/
public MutableString(final CharSequence s) {
makeCompactMutableString(s.length());
getChars(s, 0, array.length, array, 0);
}
/** Creates a new compact mutable string copying a given character array.
*
* @param a the initial contents of the string.
*/
public MutableString(final char[] a) {
makeCompactMutableString(a.length);
System.arraycopy(a, 0, array, 0, array.length);
}
/** Creates a new compact mutable string copying a part of a given character array.
*
* @param a a character array.
* @param offset an offset into the array.
* @param len how many characters to copy.
*/
public MutableString(final char[] a, final int offset, final int len) {
makeCompactMutableString(len);
System.arraycopy(a, offset, array, 0, len);
}
/** Creates a new compact mutable string by copying this one.
*
* @return a compact copy of this mutable string.
*/
public MutableString copy() {
return new MutableString(this);
}
/** Creates a new compact mutable string by copying this one.
*
* <P>This method is identical to {@link #copy}, but the latter returns
* a more specific type.
*
* @return a compact copy of this mutable string.
*/
@Override
public Object clone() {
return new MutableString(this);
}
/** Commodity static method implementing {@link
* java.lang.String#getChars(int,int,char[],int)} for a <code>CharSequence</code>s.
*
* @param s a <code>CharSequence</code>.
* @param start copy start from this index (inclusive).
* @param end copy ends at this index (exclusive).
* @param dest destination array.
* @param destStart the first character will be copied in <code>dest[destStart]</code>.
* @see java.lang.String#getChars(int,int,char[],int)
*/
public static void getChars(final CharSequence s, final int start, final int end, final char[] dest, final int destStart) {
int j = destStart, i = start;
while(i < end) dest[j++] = s.charAt(i++);
}
/** Returns the number of characters in this mutable string.
*
* @return the length of this mutable string.
*/
@Override
public final int length() {
return hashLength >= 0 ? hashLength : array.length;
}
/** Returns whether this mutable string is empty.
*
* @return whether this mutable string is empty.
*/
public final boolean isEmpty() {
return (hashLength >= 0 ? hashLength : array.length) == 0;
}
/** Returns the current length of the backing array.
*
* @return the current length of the backing array.
*/
public final int capacity() {
return array.length;
}
/** Gets the backing array.
*
* <P>For fast, repeated access to the characters of this mutable string,
* you can obtain the actual backing array. Be careful, and if this mutable
* string is compact do <em>not</em> modify its backing array without
* calling {@link #changed()} immediately afterwards (or the cached hash
* code will get out of sync, with unforeseeable consequences).
*
* @see #changed()
* @return the backing array.
*/
public final char[] array() {
return array;
}
/** Characters with indices from <code>start</code> (inclusive) to
* index <code>end</code> (exclusive) are copied from this
* mutable string into the array <code>dest</code>, starting
* from index <code>destStart</code>.
*
* @param start copy start from this index (inclusive).
* @param end copy ends at this index (exclusive).
* @param dest destination array.
* @param destStart the first character will be copied in <code>dest[destStart]</code>.
*
* @see String#getChars(int,int,char[],int)
* @throws NullPointerException if <code>dest</code> is {@code null}.
* @throws IndexOutOfBoundsException if any of the following is true:
* <ul>
* <li><code>start</code> or <code>end</code> is negative
* <li><code>start</code> is greater than
* <code>end</code>
* <li><code>end</code> is greater than
* {@link #length()}
* <li><code>end-start+destStart</code> is greater than
* <code>dest.length</code>
* </ul>
*/
public final void getChars(final int start, final int end, final char[] dest, final int destStart) {
if (end > length()) throw new IndexOutOfBoundsException();
System.arraycopy(array, start, dest, destStart, end - start);
}
/**
* Ensures that at least the given number of characters can be stored in this mutable string.
*
* <P>
* The new capacity of this string will be <em>exactly</em> equal to the provided argument if this
* mutable string is compact (this differs markedly from
* {@link java.lang.StringBuffer#ensureCapacity(int) StringBuffer}). If this mutable string is
* loose, the provided argument is maximized with the current capacity doubled.
*
* <P>
* Note that if the given argument is greater than the current length, you will make this string
* loose (see the {@linkplain MutableString class description}).
*
* @param minimumCapacity we want at least this number of characters, but no more.
* @return this mutable string.
*/
public final MutableString ensureCapacity(final int minimumCapacity) {
final int length = length();
expand(minimumCapacity);
if (length < minimumCapacity) hashLength = length;
return this;
}
/** Ensures that at least the given number of characters can be stored in this string.
*
* <P>If necessary, enlarges the backing array. If the string is compact,
* we expand it exactly to the given capacity; otherwise, expand to the
* maximum between the given capacity and the double of the current capacity.
*
* <P>This method works even with a {@code null} backing array (which
* will be considered of length 0).
*
* <P>After a call to this method, we may be in an inconsistent state: if
* you expand a compact string, {@link #hashLength} will be negative,
* but there will be spurious characters in the string. Be sure to
* fill them suitably.
*
* @param minimumCapacity we want at least this number of characters.
*/
private void expand(final int minimumCapacity) {
final int c = array == null ? 0 : array.length; // This can happen only deserialising.
if (minimumCapacity <= c && array != null) return;
final int length = hashLength >= 0 ? hashLength : c;
final char[] newArray =
new char[
hashLength >= 0 && c * 2 > minimumCapacity
? c * 2 // loose
: minimumCapacity // compact
];
if (length != 0) System.arraycopy(array, 0, newArray, 0, length); // We check because array could be null during deserialisation.
array = newArray;
}
/** Ensures that <em>exactly</em> the given number of characters can be stored in this string.
*
* <P>If necessary, reallocates the backing array. If the new capacity is smaller than
* the string length, the string will be truncated.
*
* <P>After a call to this method, we may be in an inconsistent state: if
* you expand a compact string, {@link #hashLength} will be negative,
* but there will be additional NUL characters in the string. Be sure to
* substitute them suitably.
*
* @param capacity we want exactly this number of characters.
*/
private void setCapacity(final int capacity) {
final int c = array.length;
if (capacity == c) return;
final int length = hashLength >= 0 ? hashLength : c;
final char[] newArray = capacity != 0 ? new char[capacity] : CharArrays.EMPTY_ARRAY;
System.arraycopy(array, 0, newArray, 0, length < capacity ? length : capacity);
array = newArray;
}
/** Sets the length.
*
* <P>If the provided length is greater than that of the current string,
* the string is padded with zeros. If it is shorter, the string is
* truncated to the given length. We do <em>not</em> reallocate the backing
* array, to increase object reuse. Use rather {@link #compact()} for that
* purpose.
*
* <P>Note that shortening a string will make it loose (see the {@linkplain
* MutableString class description}).
*
* @param newLength the new length for this mutable string.
* @return this mutable string.
* @see #compact()
*/
public final MutableString length(final int newLength) {
if (newLength < 0) throw new IllegalArgumentException("Negative length (" + newLength + ")");
if (hashLength < 0) {
if (array.length == newLength) return this;
hashLength = -1;
setCapacity(newLength); // For compact strings, length and capacity coincide.
}
else {
final int length = hashLength;
if (newLength == length) return this;
if (newLength > array.length) expand(newLength); // In this case, the array is already filled with zeroes.
else if (newLength > length) java.util.Arrays.fill(array, length, newLength, '\0');
hashLength = newLength;
}
return this;
}
/** A nickname for {@link #length(int)}.
*
* @param newLength the new length for this mutable string.
* @return this mutable string.
* @see #length(int)
*/
public final MutableString setLength(final int newLength) {
return length(newLength);
}
/** Makes this mutable string compact (see the {@linkplain MutableString class description}).
*
* <P>Note that this operation may require reallocating
* the backing array (of course, with a shorter length).
*
* @return this mutable string.
* @see #isCompact()
*/
public final MutableString compact() {
if (hashLength >= 0) {
setCapacity(hashLength);
hashLength = -1;
}
return this;
}
/** Makes this mutable string loose.
*
* @return this mutable string.
* @see #isLoose()
*/
public final MutableString loose() {
if (hashLength < 0) hashLength = array.length;
return this;
}
/** Returns whether this mutable string is compact (see the {@linkplain MutableString class description}).
*
* @return whether this mutable string is compact.
* @see #compact()
*/
public final boolean isCompact() {
return hashLength < 0;
}
/** Returns whether this mutable string is loose (see the {@linkplain MutableString class description}).
*
* @return whether this mutable string is loose.
* @see #loose()
*/
public final boolean isLoose() {
return hashLength >= 0;
}
/** Invalidates the current cached hash code if this mutable string is compact.
*
* <P>You will need to call this method only if you change the backing
* array of a compact mutable string {@linkplain #array() directly}.
*
* @return this mutable string.
*/
public final MutableString changed() {
if (hashLength < 0) hashLength = -1;
return this;
}
/** Wraps a given character array in a compact mutable string.
*
* <P>The returned mutable string will be compact and backed by the given character array.
*
* @param a a character array.
* @return a compact mutable string backed by the given array.
*/
static public MutableString wrap(final char a[]) {
final MutableString s = new MutableString(0);
s.array = a;
s.hashLength = -1;
return s;
}
/** Wraps a given character array for a given length in a loose mutable string.
*
* <P>The returned mutable string will be loose and backed by the given character array.
*
* @param a a character array.
* @param length a length.
* @return a loose mutable string backed by the given array with the given length.
*/
static public MutableString wrap(final char[] a, final int length) {
final MutableString s = new MutableString(0);
s.array = a;
s.hashLength = length;
return s;
}
/** Gets a character.
*
* <P>If you end up calling repeatedly this method, you
* should consider using {@link #array()} instead.
*
* @param index the index of a character.
* @return the chracter at that index.
*/
@Override
public final char charAt(final int index) {
if (index >= length()) throw new StringIndexOutOfBoundsException(index);
return array[index];
}
/** A nickname for {@link #charAt(int,char)}.
*
* @param index the index of a character.
* @param c the new character.
* @return this mutable string.
* @see #charAt(int,char)
*/
public final MutableString setCharAt(final int index, final char c) {
charAt(index, c);
return this;
}
/** Sets the character at the given index.
*
* <P>If you end up calling repeatedly this method, you should consider
* using {@link #array()} instead.
*
* @param index the index of a character.
* @param c the new character.
* @return this mutable string.
*/
public final MutableString charAt(final int index, final char c) {
if (index >= length()) throw new StringIndexOutOfBoundsException(index);
array[index] = c;
changed();
return this;
}
/** Returns the first character of this mutable string.
*
* @return the first character.
* @throws StringIndexOutOfBoundsException when called on the empty string.
*/
public final char firstChar() {
if (length() == 0) throw new StringIndexOutOfBoundsException(0);
return array[0];
}
/** Returns the last character of this mutable string.
*
* @return the last character.
* @throws ArrayIndexOutOfBoundsException when called on the empty string.
*/
public final char lastChar() {
return array[length() - 1];
}
/** Converts this string to a new character array.
*
* @return a newly allocated character array with the same length and content of this mutable string.
*/
public final char[] toCharArray() {
return CharArrays.copy(array, 0, length());
}
/** Returns a substring of this mutable string.
*
* <P>The creation of a substring implies the creation of a new backing
* array. The returned mutable string will be compact.
*
* @param start first character of the substring (inclusive).
* @param end last character of the substring (exclusive).
* @return a substring defined as above.
*/
public final MutableString substring(final int start, final int end) {
if (end > length()) throw new StringIndexOutOfBoundsException(end);
return new MutableString(array, start, end - start);
}
/** Returns a substring of this mutable string.
*
* @param start first character of the substring (inclusive).
* @return a substring ranging from the given position to the end of this string.
* @see #substring(int,int)
*/
public final MutableString substring(final int start) { return substring(start, length()); }
/** A class representing a subsequence.
*
* <P>Subsequences represented by this class share the backing array. Equality
* is content-based; hash codes are identical to those of a mutable string with the same content.
*/
private class SubSequence implements CharSequence {
final int from, to;
private SubSequence(final int from, final int to) {
this.from = from;
this.to = to;
}
@Override
public char charAt(final int index) { return array[from + index]; }
@Override
public int length() { return to - from; }
@Override
public CharSequence subSequence(final int start, final int end) {
if (start < 0) throw new StringIndexOutOfBoundsException(start);
if (end < start || end > length()) throw new StringIndexOutOfBoundsException(end);
return new SubSequence(this.from + start, this.from + end);
}
/** For convenience, the hash code of a subsequence is equal
* to that of a <code>String</code> with the same content with the
* 31st bit set.
*
* @return the hash code.
*/
@Override
public int hashCode() {
int h = 0;
final char[] a = array;
for (int i = from; i < to; i++) h = 31 * h + a[i];
return h | (1 << 31);
}
@Override
public boolean equals(final Object o) {
if (o instanceof CharSequence) {
final CharSequence s = (CharSequence)o;
int n = length();
if (n == s.length()) {
while(n-- != 0) if (charAt(n) != s.charAt(n)) return false;
return true;
}
}
return false;
}
@Override
public String toString() { return new String(array, from, to - from); }
}
/** Returns a subsequence of this mutable string.
*
* <P>Subsequences <em>share the backing array</em>. Thus, you should
* <em>not</em> use a subsequence after changing the characters of this
* mutable string between <code>start</code> and <code>end</code>.
*
* <P>Equality of <code>CharSequence</code>s returned by this method is defined by
* content equality, and hash codes are identical to mutable strings with the same
* content. Thus, you <em>can</em> mix mutable strings and <code>CharSequence</code>s
* returned by this method in data structures, as the contracts of {@link java.lang.Object#equals(Object) equals()} and
* {@link java.lang.Object#hashCode() hashCode()} are honoured.
*
* @param start first character of the subsequence (inclusive).
* @param end last character of the subsequence (exclusive).
* @return a subsequence defined as above.
* @see #substring(int,int)
*/
@Override
public final CharSequence subSequence(final int start, final int end) {
if (start < 0) throw new StringIndexOutOfBoundsException();
if (start > end || end > length()) throw new StringIndexOutOfBoundsException();
return new SubSequence(start, end);
}
/** Appends the given mutable string to this mutable string.
*
* @param s the mutable string to append.
* @return this mutable string.
*/
public final MutableString append(MutableString s) {
if (s == null) s = NULL;
final int l = s.length();
if (l == 0) return this;
final int newLength = length() + l;
expand(newLength);
System.arraycopy(s.array, 0, array, newLength - l, l);
hashLength = hashLength < 0 ? -1 : newLength;
return this;
}
/**
* Appends the given <code>String</code> to this mutable string.
*
* @param s a <code>String</code> ({@code null} is not allowed).
* @return this mutable string.
* @throws NullPointerException if the argument is {@code null}
*/
public final MutableString append(final String s) {
if (s == null) return append(NULL);
final int l = s.length();
if (l == 0) return this;
final int newLength = length() + l;
expand(newLength);
s.getChars(0, l, array, newLength - l);
hashLength = hashLength < 0 ? -1 : newLength;
return this;
}
/**
* Appends the given <code>CharSequence</code> to this mutable string.
*
* @param s a <code>CharSequence</code> or {@code null}.
* @return this mutable string.
*
* @see Appendable#append(java.lang.CharSequence)
*/
@Override
public final MutableString append(final CharSequence s) {
if (s == null) return append(NULL);
final int l = s.length();
if (l == 0) return this;
final int newLength = length() + l;
expand(newLength);
getChars(s, 0, l, array, newLength - l);
hashLength = hashLength < 0 ? -1 : newLength;
return this;
}
/**
* Appends a subsequence of the given <code>CharSequence</code> to this mutable string.
*
* <strong>Warning</strong>: the semantics of this method of that of
* {@link #append(char[], int, int)} are different.
*
* @param s a <code>CharSequence</code> or {@code null}.
* @param start the index of the first character of the subsequence to append.
* @param end the index of the character after the last character in the subsequence.
* @return this mutable string.
*
* @see Appendable#append(java.lang.CharSequence, int, int)
*/
@Override
public final MutableString append(final CharSequence s, final int start, final int end) {
if (s == null) return append(NULL, start, end);
final int len = end - start;
if (len < 0 || start < 0 || end > s.length())
throw new IndexOutOfBoundsException("start: " + start + " end: " + end + " length():" + s.length());
final int newLength = length() + len;
expand(newLength);
try {
getChars(s, start, end, array, newLength - len);
}
catch (final IndexOutOfBoundsException e) {
if (hashLength < 0) setCapacity(newLength - len);
else hashLength = newLength - len;
throw e;
}
if (len != 0) hashLength = hashLength < 0 ? -1 : newLength;
return this;
}
/**
* Appends the given character sequences to this mutable string using the given separator.
*
* @param a an array.
* @param offset the index of the first character sequence to append.
* @param length the number of character sequences to append.
* @param separator a separator that will be appended inbetween the character sequences.
* @return this mutable string.
*/
public final MutableString append(final CharSequence[] a, final int offset, final int length, final CharSequence separator) {
ObjectArrays.ensureOffsetLength(a, offset, length);
if (length == 0) return this;
// Precompute the length of the resulting string
int m = 0;
for(int i = 0; i < length; i++) m += a[offset + i].length();
final int separatorLength = separator.length();
m += (length - 1) * separatorLength;
final int l = length();
ensureCapacity(l + m);
m = 0;
for(int i = 0; i < length; i++) {
if (i != 0) {
getChars(separator, 0, separatorLength, array, l + m);
m += separatorLength;
}
getChars(a[i], 0, a[i + offset].length(), array, l + m);
m += a[i].length();
}
if (hashLength < 0) hashLength = -1;
else hashLength = l + m;
return this;
}
/** Appends the given character sequences to this mutable string using the given separator.
*
* @param a an array.
* @param separator a separator that will be appended inbetween the character sequences.
* @return this mutable string.
*/
public final MutableString append(final CharSequence[] a, final CharSequence separator) {
return append(a, 0, a.length, separator);
}
/** Appends the string representations of the given objects to this mutable string using the given separator.
*
* @param a an array of objects.
* @param offset the index of the first object to append.
* @param length the number of objects to append.
* @param separator a separator that will be appended inbetween the string representations of the given objects.
* @return this mutable string.
*/
public final MutableString append(final Object[] a, final int offset, final int length, final CharSequence separator) {
final String s[] = new String[a.length];
for(int i = 0; i < length; i++) s[i] = a[offset + i].toString();
return append(s, offset, length, separator);
}
/** Appends the string representations of the given objects to this mutable string using the given separator.
*
* @param a an array of objects.
* @param separator a separator that will be appended inbetween the string representations of the given objects.
* @return this mutable string.
*/
public final MutableString append(final Object[] a, final CharSequence separator) {
return append(a, 0, a.length, separator);
}
/** Appends the given character array to this mutable string.
*
* @param a an array to append.
* @return this mutable string.
*/
public final MutableString append(final char a[]) {
final int l = a.length;
if (l == 0) return this;
final int newLength = length() + l;
expand(newLength);
System.arraycopy(a, 0, array, newLength - l, l);
hashLength = hashLength < 0 ? -1 : newLength;
return this;
}
/** Appends a part of the given character array to this mutable string.
*
* <strong>Warning</strong>: the semantics of this method of that of
* {@link #append(CharSequence, int, int)} are different.
*
* @param a an array.
* @param offset the index of the first character to append.
* @param len the number of characters to append.
* @return this mutable string.
*/
public final MutableString append(final char[] a, final int offset, final int len) {
final int newLength = length() + len;
expand(newLength);
try {
System.arraycopy(a, offset, array, newLength - len, len);
}
catch(final IndexOutOfBoundsException e) {
if (hashLength < 0) setCapacity(newLength - len);
else hashLength = newLength - len;
throw e;
}
if (len != 0) hashLength = hashLength < 0 ? -1 : newLength;
return this;
}
/** Appends the given character list to this mutable string.
*
* @param list the list to append.
* @return this mutable string.
*/
public final MutableString append(final CharList list) {
final int l = list.size();
if (l == 0) return this;
final int newLength = length() + l;
expand(newLength);
list.getElements(0, array, newLength - l, l);
hashLength = hashLength < 0 ? -1 : newLength;