@@ -49,20 +49,57 @@ public void fromByteArrayUnsafeAndAsByteArrayUnsafeDoNotCopy() {
49
49
}
50
50
51
51
@ Test
52
- public void fromByteBufferUnsafe_doNotCopy () {
52
+ public void fromByteBufferUnsafe_fullBuffer_doesNotCopy () {
53
53
byte [] inputBytes = {'a' };
54
54
ByteBuffer inputBuffer = ByteBuffer .wrap (inputBytes );
55
55
56
56
ResponseBytes <Object > responseBytes = ResponseBytes .fromByteBufferUnsafe (OBJECT , inputBuffer );
57
-
58
- ByteBuffer outputBuffer = responseBytes .asByteBuffer ();
59
57
byte [] outputBytes = responseBytes .asByteArrayUnsafe ();
60
58
61
- assertThat (outputBuffer ).isEqualTo (inputBuffer );
59
+ assertThat (inputBuffer .hasArray ()).isTrue ();
60
+ assertThat (inputBuffer .isDirect ()).isFalse ();
62
61
assertThat (outputBytes ).isSameAs (inputBytes );
63
62
64
63
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 ();
66
81
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' );
67
104
}
68
105
}
0 commit comments