}
public static void unescapeString(final StringBuilder stringBuilder, final String string)
throws ImageReadException {
if (string.length() < 2) {
throw new ImageReadException("Parsing XPM file failed, "
+ "string is too short");
}
if (string.charAt(0) != '"'
|| string.charAt(string.length() - 1) != '"') {
throw new ImageReadException("Parsing XPM file failed, "
+ "string not surrounded by '\"'");
}
boolean hadBackSlash = false;
for (int i = 1; i < (string.length() - 1); i++) {
final char c = string.charAt(i);
if (hadBackSlash) {
if (c == '\\') {
stringBuilder.append('\\');
} else if (c == '"') {
stringBuilder.append('"');
} else if (c == '\'') {
stringBuilder.append('\'');
} else if (c == 'x') {
if (i + 2 >= string.length()) {
throw new ImageReadException(
"Parsing XPM file failed, "
+ "hex constant in string too short");
}
final char hex1 = string.charAt(i + 1);
final char hex2 = string.charAt(i + 2);
i += 2;
int constant;
try {
constant = Integer.parseInt(Character.toString(hex1) + Character.toString(hex2), 16);
} catch (final NumberFormatException nfe) {
throw new ImageReadException(
"Parsing XPM file failed, "
+ "hex constant invalid", nfe);
}
stringBuilder.append((char) constant);
} else if (c == '0' || c == '1' || c == '2' || c == '3'
|| c == '4' || c == '5' || c == '6' || c == '7') {
int length = 1;
if (i + 1 < string.length() && '0' <= string.charAt(i + 1)
&& string.charAt(i + 1) <= '7') {
++length;
}
if (i + 2 < string.length() && '0' <= string.charAt(i + 2)
&& string.charAt(i + 2) <= '7') {
++length;
}
int constant = 0;
for (int j = 0; j < length; j++) {
constant *= 8;
constant += (string.charAt(i + j) - '0');
}
i += length - 1;
stringBuilder.append((char) constant);
} else if (c == 'a') {
stringBuilder.append((char) 0x07);
} else if (c == 'b') {
stringBuilder.append((char) 0x08);
} else if (c == 'f') {
stringBuilder.append((char) 0x0c);
} else if (c == 'n') {
stringBuilder.append((char) 0x0a);
} else if (c == 'r') {
stringBuilder.append((char) 0x0d);
} else if (c == 't') {
stringBuilder.append((char) 0x09);
} else if (c == 'v') {
stringBuilder.append((char) 0x0b);
} else {
throw new ImageReadException("Parsing XPM file failed, "
+ "invalid escape sequence");
}
hadBackSlash = false;
} else {
if (c == '\\') {
hadBackSlash = true;
} else if (c == '"') {
throw new ImageReadException("Parsing XPM file failed, "
+ "extra '\"' found in string");
} else {
stringBuilder.append(c);
}
}
}
if (hadBackSlash) {
throw new ImageReadException("Parsing XPM file failed, "
+ "unterminated escape sequence found in string");
}
}