@@ -49,20 +49,57 @@ public void fromByteArrayUnsafeAndAsByteArrayUnsafeDoNotCopy() {
4949 }
5050
5151 @ Test
52- public void fromByteBufferUnsafe_doNotCopy () {
52+ public void fromByteBufferUnsafe_fullBuffer_doesNotCopy () {
5353 byte [] inputBytes = {'a' };
5454 ByteBuffer inputBuffer = ByteBuffer .wrap (inputBytes );
5555
5656 ResponseBytes <Object > responseBytes = ResponseBytes .fromByteBufferUnsafe (OBJECT , inputBuffer );
57-
58- ByteBuffer outputBuffer = responseBytes .asByteBuffer ();
5957 byte [] outputBytes = responseBytes .asByteArrayUnsafe ();
6058
61- assertThat (outputBuffer ).isEqualTo (inputBuffer );
59+ assertThat (inputBuffer .hasArray ()).isTrue ();
60+ assertThat (inputBuffer .isDirect ()).isFalse ();
6261 assertThat (outputBytes ).isSameAs (inputBytes );
6362
6463 inputBytes [0 ] = 'b' ;
65- assertThat (outputBuffer ).isEqualTo (inputBuffer );
64+ assertThat (outputBytes [0 ]).isEqualTo ((byte ) 'b' );
65+ }
66+
67+ @ Test
68+ public void fromByteBufferUnsafe_directBuffer_createsCopy () {
69+ byte [] inputBytes = {'a' };
70+ ByteBuffer directBuffer = ByteBuffer .allocateDirect (1 );
71+ directBuffer .put (inputBytes );
72+ directBuffer .flip ();
73+
74+ ResponseBytes <Object > responseBytes = ResponseBytes .fromByteBufferUnsafe (OBJECT , directBuffer );
75+ ByteBuffer outputBuffer = responseBytes .asByteBuffer ();
76+ byte [] outputBytes = responseBytes .asByteArrayUnsafe ();
77+
78+ assertThat (directBuffer .hasArray ()).isFalse ();
79+ assertThat (directBuffer .isDirect ()).isTrue ();
80+ assertThat (outputBuffer .isDirect ()).isFalse ();
6681 assertThat (outputBytes ).isEqualTo (inputBytes );
82+ assertThat (outputBytes ).isNotSameAs (inputBytes );
83+
84+ inputBytes [0 ] = 'b' ;
85+ assertThat (outputBytes [0 ]).isNotEqualTo ((byte ) 'b' );
86+ }
87+
88+ @ Test
89+ public void fromByteBufferUnsafe_bufferWithOffset_createsCopy () {
90+ byte [] inputBytes = "abcdefgh" .getBytes ();
91+
92+ ByteBuffer slicedBuffer = ByteBuffer .wrap (inputBytes , 2 , 3 ); // "cde"
93+
94+ ResponseBytes <Object > responseBytes = ResponseBytes .fromByteBufferUnsafe (OBJECT , slicedBuffer );
95+ byte [] outputBytes = responseBytes .asByteArrayUnsafe ();
96+
97+ assertThat (slicedBuffer .hasArray ()).isTrue ();
98+ assertThat (outputBytes ).isEqualTo ("cde" .getBytes ());
99+ assertThat (outputBytes .length ).isEqualTo (3 );
100+ assertThat (outputBytes ).isNotSameAs (inputBytes );
101+
102+ inputBytes [0 ] = 'X' ;
103+ assertThat (outputBytes [0 ]).isEqualTo ((byte ) 'c' );
67104 }
68105}
0 commit comments