
commonMain.de.halfbit.logger.sink.memory.RingArray.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of logger Show documentation
Show all versions of logger Show documentation
Minimalistic, fast and configurable Logger for Kotlin Multiplatform
The newest version!
/** Copyright 2024 Halfbit GmbH, Sergej Shafarenka */
package de.halfbit.logger.sink.memory
import kotlinx.atomicfu.AtomicInt
import kotlinx.atomicfu.atomic
internal class RingArray(bufferSize: Int) : Iterable {
@Suppress("UNCHECKED_CAST")
private val data: Array = arrayOfNulls(bufferSize) as Array
private var tail: Int = -1
private var size: Int = 0
private val head: Int
get() = if (size == data.size) (tail + 1) % size else 0
fun add(item: T) {
tail = (tail + 1) % data.size
data[tail] = item
if (size < data.size) size++
}
operator fun get(index: Int): T =
when {
size == 0 || index < 0 || index >= size -> throw IndexOutOfBoundsException("$index, size: $size")
size == data.size -> checkNotNull(data[(head + index) % data.size])
else -> checkNotNull(data[index])
}
fun toList(): List =
iterator().asSequence().toList()
override fun iterator(): Iterator = object : Iterator {
private val index: AtomicInt = atomic(0)
override fun hasNext(): Boolean =
index.value < size
override fun next(): T =
get(index.getAndAdd(1))
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy