Welcome to mirror list, hosted at ThFree Co, Russian Federation.

StringHelper.java « lang « java « classpath - github.com/mono/ikvm-fork.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3fc5431117ff11868b2c2f797815684d5fee0f4e (plain)
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
/* StringHelper.java -- helper class adapted from java/lang/String.java
   Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath 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.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package java.lang;

import gnu.classpath.SystemProperties;
import gnu.java.lang.CharData;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Locale;

final class StringHelper
{
    private StringHelper() {}

    static boolean equalsIgnoreCase(String s1, String s2)
    {
	int len = s1.length();
	if(s2 == null || len != s2.length())
	{
	    return false;
	}
	for(int i = 0; i < len; i++)
	{
	    char c1 = s1.charAt(i);
	    char c2 = s2.charAt(i);
	    if(c1 != c2 && (Character.toUpperCase(c1) != Character.toUpperCase(c2)) &&
		(Character.toLowerCase(c1) != Character.toLowerCase(c2)))
	    {
		return false;
	    }
	}
	return true;
    }

    static int compareTo(String s1, String s2)
    {
	int len = Math.min(s1.length(), s2.length());
	for(int i = 0; i < len; i++)
	{
	    int diff = s1.charAt(i) - s2.charAt(i);
	    if(diff != 0)
	    {
		return diff;
	    }
	}
	return s1.length() - s2.length();
    }

    static int compareToIgnoreCase(String s1, String s2)
    {
	int len = Math.min(s1.length(), s2.length());
	for(int i = 0; i < len; i++)
	{
	    int result = Character.toLowerCase(Character.toUpperCase(s1.charAt(i)))
		- Character.toLowerCase(Character.toUpperCase(s2.charAt(i)));
	    if (result != 0)
		return result;
	}
	return s1.length() - s2.length();
    }

    static String toLowerCase(String s)
    {
	return toLowerCase(s, Locale.getDefault());
    }

    static String toLowerCase(String s, Locale loc)
    {
	// First, see if the current string is already lower case.
	boolean turkish = "tr".equals(loc.getLanguage());
	int len = s.length();
	for(int i = 0; i < len; i++)
	{
	    char ch = s.charAt(i);
	    if((turkish && ch == '\u0049') || ch != Character.toLowerCase(ch))
	    {
		// Now we perform the conversion. Fortunately, there are no multi-character
		// lowercase expansions in Unicode 3.0.0.
		char[] newStr = s.toCharArray();
		for(; i < len; i++)
		{
		    ch = newStr[i];
		    // Hardcoded special case.
		    newStr[i] = (turkish && ch == '\u0049') ? '\u0131' : Character.toLowerCase(ch);
		}
		return new String(newStr);
	    }
	}
	return s;
    }

    static String toUpperCase(String s)
    {
	return toUpperCase(s, Locale.getDefault());
    }

    static String toUpperCase(String s, Locale loc)
    {
	// First, see how many characters we have to grow by, as well as if the
	// current string is already upper case.
	boolean turkish = "tr".equals(loc.getLanguage());
	int expand = 0;
	boolean unchanged = true;
	int i = s.length();
	int x = i;
	while (--i >= 0)
	{
	    char ch = s.charAt(--x);
	    expand += upperCaseExpansion(ch);
	    unchanged = (unchanged && expand == 0
		&& ! (turkish && ch == '\u0069')
		&& ch == Character.toUpperCase(ch));
	}
	if (unchanged)
	    return s;

	// Now we perform the conversion.
	i = s.length();
	if (expand == 0)
	{
	    char[] newStr = s.toCharArray();
	    while (--i >= 0)
	    {
		char ch = s.charAt(x);
		// Hardcoded special case.
		newStr[x++] = (turkish && ch == '\u0069') ? '\u0130'
		    : Character.toUpperCase(ch);
	    }
	    return new String(newStr);
	}

	// Expansion is necessary.
	char[] newStr = new char[s.length() + expand];
	int j = 0;
	while (--i >= 0)
	{
	    char ch = s.charAt(x++);
	    // Hardcoded special case.
	    if (turkish && ch == '\u0069')
	    {
		newStr[j++] = '\u0130';
		continue;
	    }
	    expand = upperCaseExpansion(ch);
	    if (expand > 0)
	    {
		int index = upperCaseIndex(ch);
		while (expand-- >= 0)
		    newStr[j++] = upperExpand[index++];
	    }
	    else
		newStr[j++] = Character.toUpperCase(ch);
	}
	return new String(newStr);
    }

    private static int upperCaseExpansion(char ch)
    {
	return Character.direction[Character.readChar(ch) >> 7] & 3;
    }

    private static int upperCaseIndex(char ch)
    {
	// Simple binary search for the correct character.
	int low = 0;
	int hi = upperSpecial.length - 2;
	int mid = ((low + hi) >> 2) << 1;
	char c = upperSpecial[mid];
	while (ch != c)
	{
	    if (ch < c)
		hi = mid - 2;
	    else
		low = mid + 2;
	    mid = ((low + hi) >> 2) << 1;
	    c = upperSpecial[mid];
	}
	return upperSpecial[mid + 1];
    }

    private static final char[] upperExpand = CharData.UPPER_EXPAND.toCharArray();
    private static final char[] upperSpecial = CharData.UPPER_SPECIAL.toCharArray();

    static String NewString(byte[] ascii, int hibyte, int offset, int count)
    {
	if (offset < 0 || count < 0 || ascii.length - offset < count)
	    throw new StringIndexOutOfBoundsException();
	char[] value = new char[count];
	hibyte <<= 8;
	offset += count;
	while (--count >= 0)
	    value[count] = (char) (hibyte | (ascii[--offset] & 0xff));
	return new String(value);
    }

    static String NewString(byte[] ascii, int hibyte)
    {
	return NewString(ascii, hibyte, 0, ascii.length);
    }

    private static Charset getCharset(String encoding) throws UnsupportedEncodingException
    {
        try
        {
            return Charset.forName(encoding);
        }
        catch(IllegalCharsetNameException e)
        {
            throw (UnsupportedEncodingException)new UnsupportedEncodingException("Encoding: " + encoding + " not found.").initCause(e);
        }
        catch(UnsupportedCharsetException e)
        {
            throw (UnsupportedEncodingException)new UnsupportedEncodingException("Encoding: " + encoding + " not found.").initCause(e);
        }
    }

    static String NewString(byte[] data, int offset, int count, String encoding)
	throws UnsupportedEncodingException
    {
	if (offset < 0 || count < 0 || data.length - offset < count)
	    throw new StringIndexOutOfBoundsException();

        CharsetDecoder csd = getCharset(encoding).newDecoder();
        csd.onMalformedInput(CodingErrorAction.REPLACE);
        csd.onUnmappableCharacter(CodingErrorAction.REPLACE);
        CharBuffer out = CharBuffer.allocate(count * (int)csd.maxCharsPerByte());
        csd.decode(ByteBuffer.wrap(data, offset, count), out, true);
        csd.flush(out);
        return out.flip().toString();
    }

    static String NewString(byte[] data, String encoding)
	throws UnsupportedEncodingException
    {
	return NewString(data, 0, data.length, encoding);
    }

    static String NewString(byte[] data, int offset, int count)
    {
        try
        {
            return NewString(data, offset, count, SystemProperties.getProperty("file.encoding"));
        }
        catch(UnsupportedEncodingException e)
        {
            throw new Error(e);
        }
    }

    static String NewString(byte[] data)
    {
	return NewString(data, 0, data.length);
    }

    static String NewString(char[] data, int offset, int count, boolean dont_copy)
    {
	return new String(data, offset, count);
    }

    static String NewString(StringBuffer sb)
    {
	synchronized(sb)
	{
	    return new String(sb.value, 0, sb.count);
	}
    }

    static String substring(cli.System.String s, int off, int end)
    {
	return s.Substring(off, end - off);
    }

    static boolean startsWith(cli.System.String s, String prefix, int toffset)
    {
	if(toffset < 0 || toffset > s.get_Length())
	{
	    return false;
	}
	s = (cli.System.String)(Object)s.Substring(Math.min(s.get_Length(), toffset));
	return s.StartsWith(prefix);
    }

    static void getChars(cli.System.String s, int srcBegin, int srcEnd, char[] dst, int dstBegin) 
    {
	s.CopyTo(srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

    // this exposes the package accessible "count" field (for use by StringBuffer)
    static int GetCountField(cli.System.String s)
    {
	return s.get_Length();
    }

    // this exposes the package accessible "value" field (for use by StringBuffer)
    static char[] GetValueField(cli.System.String s)
    {
	return s.ToCharArray();
    }

    // this exposes the package accessible "offset" field (for use by StringBuffer)
    static int GetOffsetField(cli.System.String s)
    {
	return 0;
    }

    static int indexOf(cli.System.String s, int ch, int fromIndex)
    {
	if(ch < 0 || ch > Character.MAX_VALUE)
	{
	    if(s == null)
	    {
		throw new NullPointerException();
	    }
    	    return -1;
	}
	// Java allow fromIndex to both below zero or above the length of the string, .NET doesn't
	return s.IndexOf((char)ch, Math.max(0, Math.min(s.get_Length(), fromIndex)));
    }

    static int indexOf(cli.System.String s, String o, int fromIndex)
    {
	// Java allow fromIndex to both below zero or above the length of the string, .NET doesn't
	return s.IndexOf(o, Math.max(0, Math.min(s.get_Length(), fromIndex)));
    }

    static int lastIndexOf(cli.System.String s, int ch, int fromIndex)
    {
	// start by dereferencing s, to make sure we throw a NullPointerException if s is null
	int len = s.get_Length();
	if(fromIndex  < 0)
	{
	    return -1;
	}
	if(ch < 0 || ch > Character.MAX_VALUE)
	{
	    return -1;
	}
	// Java allows fromIndex to be above the length of the string, .NET doesn't
	return s.LastIndexOf((char)ch, Math.min(len - 1, fromIndex));
    }

    static int lastIndexOf(cli.System.String s, String o)
    {
	return lastIndexOf(s, o, s.get_Length());
    }

    static int lastIndexOf(cli.System.String s, String o, int fromIndex)
    {
	// start by dereferencing s, to make sure we throw a NullPointerException if s is null
	int len = s.get_Length();
	if(fromIndex  < 0)
	{
	    return -1;
	}
	if(o.length() == 0)
	{
	    return Math.min(len, fromIndex);
	}
	// make sure we don't overflow if fromIndex is near Integer.MAX_VALUE
	if((fromIndex + o.length() - 1) < 0) 
	{ 
	    fromIndex = len - 1; 
	} 
	// Java allows fromIndex to be above the length of the string, .NET doesn't
	return s.LastIndexOf(o, Math.min(len - 1, fromIndex + o.length() - 1));
    }

    static String concat(String s1, String s2)
    {
	if(s1.length() == 0)
	{
	    return s2;
	}
	if(s2.length() == 0)
	{
	    return s1;
	}
	return cli.System.String.Concat(s1, s2);
    }

    static void getBytes(String s, int srcBegin, int srcEnd, byte dst[], int dstBegin)
    {
	if (srcBegin < 0 || srcBegin > srcEnd || srcEnd > s.length())
	    throw new StringIndexOutOfBoundsException();
	int i = srcEnd - srcBegin;
	while (--i >= 0)
	    dst[dstBegin++] = (byte)s.charAt(srcBegin++);
    }

    static byte[] getBytes(String s, String enc) throws UnsupportedEncodingException
    {
        try 
        {
            CharsetEncoder cse = getCharset(enc).newEncoder();
            cse.onMalformedInput(CodingErrorAction.REPLACE);
            cse.onUnmappableCharacter(CodingErrorAction.REPLACE);
            char[] value = s.toCharArray();
            ByteBuffer bbuf = cse.encode(CharBuffer.wrap(value, 0, value.length));
            if(bbuf.hasArray())
                return bbuf.array();

            // Doubt this will happen. But just in case.
            byte[] bytes = new byte[bbuf.remaining()];
            bbuf.get(bytes);
            return bytes;
        }
        catch(CharacterCodingException e)
        {
            throw new Error(e);
        }
    }

    static byte[] getBytes(String s)
    {
        try 
        {
            return getBytes(s, SystemProperties.getProperty("file.encoding"));
        }
        catch(UnsupportedEncodingException e)
        {
            throw new Error(e);
        }
    }

    static boolean regionMatches(String s, int toffset, String other, int ooffset, int len)
    {
	return regionMatches(s, false, toffset, other, ooffset, len);
    }

    static boolean regionMatches(String s, boolean ignoreCase, int toffset,
	String other, int ooffset, int len)
    {
	// this explicit test is needed, because Integer.MIN_VALUE will underflow the while
	if (len < 0)
	{
	    return true;
	}
	// be careful to avoid integer overflow
	if (toffset < 0 || ooffset < 0 || s.length() - toffset < len || other.length() - ooffset < len)
	{
	    return false;
	}
	while (--len >= 0)
	{
	    char c1 = s.charAt(toffset++);
	    char c2 = other.charAt(ooffset++);
	    // Note that checking c1 != c2 is redundant when ignoreCase is true,
	    // but it avoids method calls.
	    if (c1 != c2
		&& (! ignoreCase
		|| (Character.toLowerCase(c1) != Character.toLowerCase(c2)
		&& (Character.toUpperCase(c1)
		!= Character.toUpperCase(c2)))))
		return false;
	}
	return true;
    }

    static String trim(String s)
    {
	int limit = s.length();
	if (limit == 0 || (s.charAt(0) > '\u0020'
	    && s.charAt(limit - 1) > '\u0020'))
	    return s;
	int begin = 0;
	do
	    if (begin == limit)
		return "";
	while (s.charAt(begin++) <= '\u0020');
	int end = limit;
	while (s.charAt(--end) <= '\u0020');
	return s.substring(begin - 1, end + 1);
    }

    static String valueOf(boolean b)
    {
	return b ? "true" : "false";
    }

    static String valueOf(int i)
    {
	return Integer.toString(i, 10);
    }

    static String valueOf(long l)
    {
	return Long.toString(l);
    }

    static cli.System.String valueOf(char c)
    {
	return new cli.System.String(c, 1);
    }

    static String valueOf(float f)
    {
	return Float.toString(f);
    }

    static String valueOf(double d)
    {
	return Double.toString(d);
    }

    static String valueOf(char[] c)
    {
	return new String(c);
    }

    static String valueOf(char[] c, int offset, int count)
    {
	return new String(c, offset, count);
    }

    static String valueOf(Object o)
    {
	return o == null ? "null" : o.toString();
    }

    static int hashCode(cli.System.String s)
    {
	int h = 0;
	// NOTE having the get_Length in the for condition is actually faster than hoisting it,
	// the CLR JIT recognizes this pattern and optimizes the array bounds check in get_Chars.
	for(int i = 0; i < s.get_Length(); i++)
	{
	    h = h * 31 + s.get_Chars(i);
	}
	return h;
    }
}