Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ArrayIndexOutOfBoundsException in BasedSequence.indexOfAll #362

Closed
mattmook opened this issue Aug 18, 2019 · 1 comment
Closed

ArrayIndexOutOfBoundsException in BasedSequence.indexOfAll #362

mattmook opened this issue Aug 18, 2019 · 1 comment

Comments

@mattmook
Copy link
Contributor

RichCharSequenceBase.indexOfAll throws an exception when more than 32 sequences are present in a string:

java.lang.ArrayIndexOutOfBoundsException: Index 32 out of bounds for length 32

	at com.vladsch.flexmark.util.sequence.RichCharSequenceBase.indexOfAll(RichCharSequenceBase.java:1489)
	at com.vladsch.flexmark.util.sequence.BasedSequenceImplTest.test_indexOfAll(BasedSequenceImplTest.java:20)

This occurs in the current master branch. I have also generated the same bug in v0.42.6.

To Reproduce

This can be seen with the following test:

public class BasedSequenceImplTest {

    @Test
    public void test_indexOfAll() throws Exception {
        final String s1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        BasedSequence s = BasedSequenceImpl.of(s1);

        int[] indices = s.indexOfAll("a");

        assertEquals(33, indices.length);

        for (int i = 0; i < indices.length; i++) {
            assertEquals(i, indices[i]);
        }
    }
}

Expected behavior
There should be no limit to the number of matching indices returned.

Additional context

Below I have provided a re-implementation of indexOfAll which internally uses an ArrayList so resizing of the array is no longer an issue:

    @Override
    final public int[] indexOfAll(CharSequence s) {
        int length = s.length();
        if (length == 0) return EMPTY_INDICES;

        ArrayList<Integer> indices = new ArrayList<Integer>();

        int pos = 0;
        while (true) {
            pos = indexOf(s, pos);
            if (pos == -1) break;
            indices.add(pos);
            pos += length;
        }

        int[] arr = new int[indices.size()];
        for(int i = 0; i < indices.size(); i++) {
            arr[i] = indices.get(i);
        }

        return arr;
    }

Using the above implementation would mean expandTo and truncateTo would then longer be necessary and so could be removed.

@vsch
Copy link
Owner

vsch commented Aug 23, 2019

Fix for this is available. Repo updated, maven updated but may take a while to show up in maven central.

@vsch vsch closed this as completed Aug 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants