/* * @test /nodynamiccopyright/ * @bug 6827009 * @summary Positive tests for strings in switch. * @author Joseph D. Darcy */ public class StringSwitches { public static void main(String... args) { int failures = 0; failures += testPileup(); failures += testSwitchingTwoWays(); if (failures > 0) { throw new RuntimeException(); } } /* * A zero length string and all strings consisting only of the * zero character \u0000 have a hash code of zero. This method * maps such strings to the number of times \u0000 appears for 0 * through 6 occurrences. */ private static int zeroHashes(String s) { int result = Integer.MAX_VALUE; switch(s) { case "": return 0; case "\u0000": result = 1; break; case "\u0000\u0000": return 2; case "\u0000\u0000\u0000": result = 3; break; case "\u0000\u0000\u0000\u0000": return 4; case "\u0000\u0000\u0000\u0000\u0000": result = 5; break; case "\u0000\u0000\u0000\u0000\u0000\u0000": return 6; default: result = -1; } return result; } private static int testPileup() { int failures = 0; String zero = ""; for(int i = 0; i <= 6; i++, zero += "\u0000") { int result = zeroHashes(zero); if (result != i) { failures++; System.err.printf("For string \"%s\" unexpectedly got %d instead of %d%n.", zero, result, i); } } if (zeroHashes("foo") != -1) { failures++; System.err.println("Failed to get -1 for input string."); } return failures; } /** * Verify that a switch on an enum and a switch with the same * structure on the string name of an enum compute equivalent * values. */ private static int testSwitchingTwoWays() { int failures = 0; for(MetaSynVar msv : MetaSynVar.values()) { int enumResult = enumSwitch(msv); int stringResult = stringSwitch(msv.name()); if (enumResult != stringResult) { failures++; System.err.printf("One value %s, computed 0x%x with the enum switch " + "and 0x%x with the string one.%n", msv, enumResult, stringResult); } } return failures; } private static enum MetaSynVar { FOO, BAR, BAZ, QUX, QUUX, QUUUX, MUMBLE, FOOBAR; } private static int enumSwitch(MetaSynVar msv) { int result = 0; switch(msv) { case FOO: result |= (1<<0); // fallthrough: case BAR: case BAZ: result |= (1<<1); break; default: switch(msv) { case QUX: result |= (1<<2); break; case QUUX: result |= (1<<3); default: result |= (1<<4); } break; case MUMBLE: result |= (1<<5); return result; case FOOBAR: result |= (1<<6); break; } return result; } private static int stringSwitch(String msvName) { int result = 0; switch(msvName) { case "FOO": result |= (1<<0); // fallthrough: case "BAR": case "BAZ": result |= (1<<1); break; default: switch(msvName) { case "QUX": result |= (1<<2); break; case "QUUX": result |= (1<<3); default: result |= (1<<4); } break; case "MUMBLE": result |= (1<<5); return result; case "FOOBAR": result |= (1<<6); break; } return result; } }