Skip to content

Instantly share code, notes, and snippets.

@stefanofago73
Last active December 3, 2025 10:26
Show Gist options
  • Select an option

  • Save stefanofago73/918bf456947501b4fdaa1a0eb9aa6517 to your computer and use it in GitHub Desktop.

Select an option

Save stefanofago73/918bf456947501b4fdaa1a0eb9aa6517 to your computer and use it in GitHub Desktop.
A possible, not optimized, SWAR approach without Vector API, searching for ASCII char
public class TryingSWAR{
public final static int[] findCharPositions(String input, byte target) {
final byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
final int trail = bytes.length;
final int[] positions = new int[trail];
final long pattern = 0x0101010101010101L * (target & 0xFF);
int i = 0, idx = 0;
if (trail > 8) {
final ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
for (int len = trail - 8; i <= len;) {
long chunk = buf.getLong(i);
long filteredChunk = (chunk ^ pattern) - 0x0101010101010101L & ~(chunk ^ pattern) & 0x8080808080808080L;
if (filteredChunk != 0) {
if ((filteredChunk & 0x0000000000000080L) != 0)
positions[idx++] = i;
if ((filteredChunk & 0x0000000000008000L) != 0)
positions[idx++] = i + 1;
if ((filteredChunk & 0x0000000000800000L) != 0)
positions[idx++] = i + 2;
if ((filteredChunk & 0x0000000080000000L) != 0)
positions[idx++] = i + 3;
if ((filteredChunk & 0x0000008000000000L) != 0)
positions[idx++] = i + 4;
if ((filteredChunk & 0x0000800000000000L) != 0)
positions[idx++] = i + 5;
if ((filteredChunk & 0x0080000000000000L) != 0)
positions[idx++] = i + 6;
if ((filteredChunk & 0x8000000000000000L) != 0)
positions[idx++] = i + 7;
}
i += 8;
}
for (; i < trail; i++) {
if (bytes[i] == target) {
positions[idx++] = i;
}
}
} else {
for (; i < trail; i++) {
if (bytes[i] == target) {
positions[i] = i;
}
}
}
return positions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment