XMLTreeUtil { public static int indexOf(byte[] src, byte[] target, int fromIdx) { final int to = src.length - target.length + 1; for (int i = fromIdx; i < to; i++) { if (src[i] == target[0]) { boolean equals = true; for (int j = 1, k = i + 1; j < target.length && equals; j++, k++) { if (src[k] != target[j]) { equals = false; } } if (equals) { return i; } } } return -1; } private  XMLTreeUtil(); static byte[] insertBetween(byte[] src, int left, int right, String content); static byte[] insertInto(byte[] src, int pos, String content); static T single(List<T> target); static int lastIndexOf(byte[] src, char c, int fromIdx); static int level(Element element); static int openTagLength(NewElement element); static int closeTagLength(NewElement element); static int attributeLength(NewAttribute attribute); static String tabulate(String src, int tabsCount); static Element asElement(Node node); static List<Element> asElements(NodeList list); static List<R> asElements(NodeList list, ElementMapper<? extends R> mapper); static int indexOf(byte[] src, byte[] target, int fromIdx); static int indexOfAttributeName(byte[] src, byte[] target, int fromIdx); static byte[] replaceAll(byte[] src, byte[] target, byte[] replacement); static int rootStart(byte[] xml); static final Charset UTF_8; static final int SPACES_IN_TAB; }
@Test public void shouldBeAbleToGetIndexOf() { final String src = "<element attribute1=\"value1\" attribute2=\"value2\" attribute3=\"value3\">text</element>"; final byte[] byteSrc = src.getBytes(); assertEquals(indexOf(byteSrc, "attribute1".getBytes(), 0), src.indexOf("attribute1")); assertEquals(indexOf(byteSrc, "attribute2".getBytes(), 0), src.indexOf("attribute2")); assertEquals(indexOf(byteSrc, "attribute3".getBytes(), 0), src.indexOf("attribute3")); }
@Test public void shouldReturnMinusOneIfTargetBytesWereNotFound() { final String src = "source string"; final byte[] byteSrc = src.getBytes(); assertNotEquals(indexOf(byteSrc, "string".getBytes(), 0), -1); assertEquals(indexOf(byteSrc, "strings".getBytes(), 0), -1); }