Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8153637

MethodHandles.countedLoop/3 initialises loop counter to 1 instead of 0

    Details

      Description

      A loop corresponding to the following code should return 10:

      int x = 0; for (int i = 0; i < 5; ++i) { x += i; } return x;

      However, the loop assembled as follows returns 15:

      MethodHandle iter = MethodHandles.constant(int.class, 5);
      MethodHandle init = MethodHandles.constant(int.class, 0);
      MethodHandle body = ...; // handle to a method int m(int c, int x) { return x + c; }
      MethodHandle loop = MethodHandles.countedLoop(iter, init, body);
      assertEquals(10, loop.invoke());

      The reason for this is that the MHs.countedLoop/3 combinator indeed initialises the loop counter to 0, but increments it right away before the first invocation of the body handle. This should be fixable by reordering clauses, or by initialising the counter to -1.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                mhaupt Michael Haupt
                Reporter:
                mhaupt Michael Haupt
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: