Skip to content

Instantly share code, notes, and snippets.

@franz1981
Created April 3, 2023 12:03
Show Gist options
  • Save franz1981/9905d653394085a06d233a61696bc712 to your computer and use it in GitHub Desktop.
Save franz1981/9905d653394085a06d233a61696bc712 to your computer and use it in GitHub Desktop.
private static final long DOLLAR_PATTERN = '$' * 0x0001_0001_0001_0001L;
private static int firstAnyPattern(long fourChars, long charPattern) {
long input = fourChars ^ charPattern;
long tmp = (input & 0x7FFF_7FFF_7FFF_7FFFL) + 0x7FFF_7FFF_7FFF_7FFFL;
tmp = ~(tmp | input | 0x7FFF_7FFF_7FFF_7FFFL);
final int binaryPosition = Long.numberOfLeadingZeros(tmp);
return binaryPosition >>> 4;
}
private static int searchLastIndexOfOrDollar(String name, char delim) {
int pos = name.length() - 1;
int longTrips = pos / 4;
int off = pos - 1;
final long delimPattern = delim * 0x0001_0001_0001_0001L;
for (int i = 0; i < longTrips; i++) {
final long batch = ((long) name.charAt(off)) << 48 |
((long) name.charAt(off - 1)) << 32 |
name.charAt(off - 2) << 16 |
name.charAt(off - 3);
int delimPos = firstAnyPattern(batch, delimPattern);
if (delimPos < 4) {
return off - delimPos;
}
int dollarPos = firstAnyPattern(batch, DOLLAR_PATTERN);
if (dollarPos < 4) {
return off - dollarPos;
}
off -= 4;
}
while (off >= 0) {
char c = name.charAt(off);
if (c == delim) {
return off;
}
if (c == '$') {
return -off;
}
off--;
}
return -1;
}
private static int lastIndexOf(String name, char delim) {
// Begin at second last position to avoid empty local name
int pos = searchLastIndexOfOrDollar(name, delim);
// avoid splitting on '$' if previous char is a delimiter or the '$'
// is in position 0, because subsequent split would produce an empty
// local name
if (pos >= 0 && name.charAt(pos) == '$' && (pos == 0 || name.charAt(pos - 1) == delim)) {
pos--;
}
return pos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment