Skip to content

Instantly share code, notes, and snippets.

@alexec
Last active December 11, 2015 07:38
Show Gist options
  • Save alexec/4567253 to your computer and use it in GitHub Desktop.
Save alexec/4567253 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.InputStream;
/**
* @author alex.collins
*/
public class SearchAndReplaceInputStream extends InputStream {
private final InputStream is;
private final byte[] search;
private final byte[] replace;
private int len, pos, idx;
private byte ch, buf[];
public SearchAndReplaceInputStream(InputStream is, byte[] search, byte[] replace) {
this.is = is;
this.search = search;
this.replace = replace;
len = this.search.length;
pos = 0;
idx = -1;
ch = this.search[0];
buf = new byte[Math.max(this.search.length, this.replace.length)];
}
@Override
public int read() throws IOException {
if (idx == -1) {
idx = 0;
int i;
while ((i = is.read()) != -1 && (buf[pos] = (byte) i) == ch) {
if (++pos == len) {
break;
}
ch = search[pos];
}
if (pos == len) {
buf = new byte[Math.max(this.search.length, this.replace.length)];
System.arraycopy(replace, 0, buf, 0, replace.length);
}
pos = 0;
ch = search[pos];
}
int toReturn = -1;
if (idx > -1 && buf[idx] != 0) {
toReturn = buf[idx];
buf[idx] = 0;
if (idx < buf.length - 1 && buf[idx + 1] != 0) {
idx++;
} else {
idx = -1;
buf = new byte[Math.max(this.search.length, this.replace.length)];
}
}
return toReturn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment