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

(bf) XBuffer.put(Xbuffer src) can give unexpected result when storage overlaps

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 15
    • 15
    • core-libs
    • None
    • b26
    • generic
    • generic

      When the backing memory of two different buffers is the same then the result can be surprising if put(XBuffer) defaults to the “loopy” implementation

           while (src.hasRemaining())
               dst.put(src.get());

      For example, the output of the following test class is:

      0 1 2 3 0 1 2 3 0 1 2 3 12 13 14 15

      instead of, as might be expected:

      0 1 2 3 0 1 2 3 4 5 6 7 12 13 14 15

      It would be better if this operation behaved like array copy and have a result as if the content of the argument buffer were first copied to a separate location and then copied into the target.

      import java.nio.*;

      public class OverlapTest {
          public static void main(String[] args) throws Throwable {
              byte[] array = new byte[32];
              for (int i = 0; i < array.length; i++) {
                  if (i % 2 == 1)
                      array[i] = (byte)(i/2);;
              }
              ByteBuffer buf = ByteBuffer.wrap(array);

              ShortBuffer shortBuf = buf.asShortBuffer();
              int cap = shortBuf.capacity();
              for (int i = 0; i < cap; i++) {
                  System.out.format("%d ", shortBuf.get(i));
              }

              System.out.println();

              ShortBuffer lower = shortBuf.slice(0, cap/2);
              ShortBuffer middle = shortBuf.slice(cap/4, cap/2);
              middle.put(lower);
              for (int i = 0; i < cap; i++) {
                  System.out.format("%d ", shortBuf.get(i));
              }
              System.out.println();
          }
      }

            bpb Brian Burkhalter
            bpb Brian Burkhalter
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: