From 9ad70be1280d065e9edb0668b6b45ce8857527b6 Mon Sep 17 00:00:00 2001 From: Darshan Parajuli Date: Sun, 12 Jul 2020 22:48:10 -0700 Subject: [PATCH] Fix remove bug --- .../logcat/collections/FixedCircularArray.kt | 21 ++++++++----------- .../collections/FixedCircularArrayTest.kt | 17 +++++++++++++++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/collections/src/main/java/com/logcat/collections/FixedCircularArray.kt b/collections/src/main/java/com/logcat/collections/FixedCircularArray.kt index f9eef54a..f390870e 100644 --- a/collections/src/main/java/com/logcat/collections/FixedCircularArray.kt +++ b/collections/src/main/java/com/logcat/collections/FixedCircularArray.kt @@ -1,16 +1,19 @@ package com.logcat.collections +import kotlin.math.min + class FixedCircularArray(val capacity: Int, initialSize: Int = INITIAL_SIZE) : Iterable { companion object { private const val INITIAL_SIZE = 16 } - private var array = arrayOfNulls(Math.min(capacity, initialSize)) - private var head = -1 + private var array = arrayOfNulls(min(capacity, initialSize)) + private var head = 0 private var next = 0 init { + resetHead() if (capacity <= 0) { throw IllegalStateException("capacity (= $capacity) must be > 0") } @@ -65,16 +68,10 @@ class FixedCircularArray(val capacity: Int, initialSize: Int = INITIAL_SIZE) } array[(head + size - 1) % capacity] = null - if (next == 0) { - next = size - 1 - } else { - next-- - } - + next = (head + size - 1) % capacity if (next == head) { - if (head >= 0) { - head-- - } + // empty array, reset + resetHead() } return result @@ -111,7 +108,7 @@ class FixedCircularArray(val capacity: Int, initialSize: Int = INITIAL_SIZE) return } - val newSize = Math.min(array.size * 2, capacity) + val newSize = min(array.size * 2, capacity) val newArray = arrayOfNulls(newSize) System.arraycopy(array, 0, newArray, 0, array.size) array = newArray diff --git a/collections/src/test/java/com/logcat/collections/FixedCircularArrayTest.kt b/collections/src/test/java/com/logcat/collections/FixedCircularArrayTest.kt index dcb456a4..56112a81 100644 --- a/collections/src/test/java/com/logcat/collections/FixedCircularArrayTest.kt +++ b/collections/src/test/java/com/logcat/collections/FixedCircularArrayTest.kt @@ -38,12 +38,29 @@ class FixedCircularArrayTest { array.add(i) } + println("================================") assertEquals(10, array.size) var index = 0 while (array.isNotEmpty()) { assertEquals(91 + index++, array.removeAt(0)) } assertTrue(array.isEmpty()) + + for (i in 0 until 5) { + array.add(i) + } + assertEquals(5, array.size) + + for (i in 0 until 20) { + array.add(i) + } + assertEquals(10, array.size) + + index = 0 + while (array.isNotEmpty()) { + assertEquals(10 + index++, array.removeAt(0)) + } + assertTrue(array.isEmpty()) } @Test