1 /*******************************************************************************
2 * Copyright (c) 2010 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.databoard.tests;
14 import java.nio.charset.Charset;
15 import java.util.Random;
17 public class StringTest {
19 static final Charset UTF8 = Charset.forName("utf-8");
20 static final Random r = new Random();
22 static public String getRandomString()
24 int len = r.nextInt(600);
25 StringBuilder sb = new StringBuilder(len);
26 for (int i=0; i<len; i++)
28 char c = (char) r.nextInt();
34 static public String getStringWithC(char c )
37 StringBuilder sb = new StringBuilder(len);
38 for (int i=0; i<len; i++)
46 public static int getStringUTF8EncodedByteLength1(String string)
48 return string.getBytes(UTF8).length;
51 public static int getStringUTF8EncodedByteLength2(String string)
54 int length = string.length();
55 for (int i=0; i<length; i++)
57 char c = string.charAt(i);
58 if (c>=0 && c<=0x7f) {
60 } else if (c>=0x80 && c<=0x07ff) {
62 } else if (c>=0xD800 && c<=0xDFFF) {
64 } else if (c>=0x800 && c<=0xffff) {
66 } else if (c>=0x10000 && c<=0x10ffff) {
68 } else if (c>=0x110000 && c<=0x1FFFFF) {
72 // Lets guess 5 bytes anyhow
80 public static void main(String[] args) {
81 char c = (char) 0x66778899;
83 System.out.println(j );
85 for (int i=1000000; i<0x7fffffff; i++)
87 String str = getStringWithC((char)i);
88 int len1 = getStringUTF8EncodedByteLength1(str);
89 int len2 = getStringUTF8EncodedByteLength2(str);
91 System.out.printf("i=%d, Correct=%d, My=%d, Chars=%d, %s\n", i, len1, len2, str.length(), str);
92 throw new RuntimeException("length mismatch");
94 if ((i & 0xFFFF) == 0)
95 System.out.printf("i=%d, Correct=%d, My=%d, Chars=%d, %s\n", i, len1, len2, str.length(), str);