@@ -306,30 +306,38 @@ abstract class Chunk[+O] extends Serializable with ChunkPlatform[O] with ChunkRu
306306 case _ => Chunk .ArraySlice (toArray, 0 , size)
307307 }
308308
309- /** Converts this chunk to a `java.nio.ByteBuffer`. */
309+ /** Converts this chunk to a `java.nio.ByteBuffer`.
310+ * @note that even "read-only" interaction with a `ByteBuffer` may increment its `position`,
311+ * so this method should be considered as unsafely allocating mutable state.
312+ */
310313 def toByteBuffer [B >: O ](implicit ev : B =:= Byte ): JByteBuffer =
311314 this match {
312315 case c : Chunk .ArraySlice [_] if c.values.isInstanceOf [Array [Byte ]] =>
313316 JByteBuffer .wrap(c.values.asInstanceOf [Array [Byte ]], c.offset, c.length)
314317 case c : Chunk .ByteBuffer =>
315- val b = c.buf.asReadOnlyBuffer
318+ val b = c.buf.duplicate // share contents, independent position/limit
316319 if (c.offset == 0 && b.position() == 0 && c.size == b.limit()) b
317320 else {
318321 (b : JBuffer ).position(c.offset.toInt)
319322 (b : JBuffer ).limit(c.offset.toInt + c.size)
320323 b
321324 }
325+ case c : Chunk .ByteVectorChunk =>
326+ c.bv.toByteBuffer
322327 case _ =>
323328 JByteBuffer .wrap(this .asInstanceOf [Chunk [Byte ]].toArray, 0 , size)
324329 }
325330
326- /** Converts this chunk to a `java.nio.CharBuffer`. */
331+ /** Converts this chunk to a `java.nio.CharBuffer`.
332+ * @note that even "read-only" interaction with a `CharBuffer` may increment its position,
333+ * so this method should be considered as unsafely allocating mutable state.
334+ */
327335 def toCharBuffer [B >: O ](implicit ev : B =:= Char ): JCharBuffer =
328336 this match {
329337 case c : Chunk .ArraySlice [_] if c.values.isInstanceOf [Array [Char ]] =>
330338 JCharBuffer .wrap(c.values.asInstanceOf [Array [Char ]], c.offset, c.length)
331339 case c : Chunk .CharBuffer =>
332- val b = c.buf.asReadOnlyBuffer
340+ val b = c.buf.duplicate // share contents, independent position/limit
333341 if (c.offset == 0 && b.position() == 0 && c.size == b.limit()) b
334342 else {
335343 (b : JBuffer ).position(c.offset.toInt)
0 commit comments