Skip to content

Commit 3eb8117

Browse files
authored
Correctly split head segment (#350)
* Fixed how buffer's head is updated after the split
1 parent cc82d10 commit 3eb8117

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

core/common/src/Buffer.kt

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ public class Buffer : Source, Sink {
488488

489489
while (remainingByteCount > 0L) {
490490
// Is a prefix of the source's head segment all that we need to move?
491-
if (remainingByteCount < source.head!!.limit - source.head!!.pos) {
491+
if (remainingByteCount < source.head!!.size) {
492492
val tail = tail
493493
if (tail != null && tail.owner &&
494494
remainingByteCount + tail.limit - (if (tail.shared) 0 else tail.pos) <= Segment.SIZE
@@ -501,17 +501,13 @@ public class Buffer : Source, Sink {
501501
} else {
502502
// We're going to need another segment. Split the source's head
503503
// segment in two, then move the first of those two to this buffer.
504-
val newHead = source.head!!.split(remainingByteCount.toInt())
505-
if (source.head == source.tail) {
506-
source.tail = newHead
507-
}
508-
source.head = newHead
504+
source.head = source.head!!.split(remainingByteCount.toInt())
509505
}
510506
}
511507

512508
// Remove the source's head segment and append it to our tail.
513-
val segmentToMove = source.head
514-
val movedByteCount = (segmentToMove!!.limit - segmentToMove.pos).toLong()
509+
val segmentToMove = source.head!!
510+
val movedByteCount = segmentToMove.size.toLong()
515511
source.head = segmentToMove.pop()
516512
if (source.head == null) {
517513
source.tail = null

core/common/test/CommonBufferTest.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,4 +601,21 @@ class CommonBufferTest {
601601
buffer.clear()
602602
assertEquals(ByteString(), buffer.snapshot())
603603
}
604+
605+
@Test
606+
fun splitHead() {
607+
val dst = Buffer()
608+
val src = Buffer().also { it.write(ByteArray(SEGMENT_SIZE)) }
609+
610+
dst.write(src, src.size / 2)
611+
assertEquals(src.size, dst.size)
612+
613+
assertEquals(src.head, src.tail)
614+
assertEquals(null, src.head?.prev)
615+
assertEquals(null, src.tail?.next)
616+
617+
assertEquals(dst.head, dst.tail)
618+
assertEquals(null, dst.head?.prev)
619+
assertEquals(null, dst.tail?.next)
620+
}
604621
}

0 commit comments

Comments
 (0)