// i must point at the (possibly imaginary) opening bracket ("{") // index returned is index of closing bracket + 1 (or l(tok)) // version using iterator (much faster than v1!) static int tok_findEndOfBlock_IContentsIndexedList2_v2(IContentsIndexedList2 tok, int i) { int n = l(tok); // find opening & closing brackets after start index HasIndex start = new(i); TreeSet openers = tok.indicesOf_treeSetOfHasIndex("{"); Iterator iOpener = openers?.tailSet(start, false).iterator(); TreeSet closers = tok.indicesOf_treeSetOfHasIndex("}"); Iterator iCloser = closers?.tailSet(start, false).iterator(); // now step through both sets int level = 1; HasIndex nextOpener = iOpener != null && iOpener.hasNext() ? iOpener.next() : null; HasIndex nextCloser = iCloser != null && iCloser.hasNext() ? iCloser.next() : null; while true { if (nextCloser == null) ret n; // block isn't closed if (nextOpener != null && nextOpener.idx < nextCloser.idx) { // process opener ++level; nextOpener = iOpener.hasNext() ? iOpener.next() : null; } else { // process closer if (--level == 0) ret nextCloser.idx+1; nextCloser = iCloser.hasNext() ? iCloser.next() : null; } } }