Created
June 8, 2016 01:30
-
-
Save Jire/38fc1392d458a60d502a9fbc73f89e06 to your computer and use it in GitHub Desktop.
Zero-garbage fast iteration collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.acelta.util | |
| import com.acelta.world.mob.Mob | |
| class Indexer<T : Mob>(val capacity: Int) : MutableIterable<T> { | |
| private inner class Iterator : MutableIterator<T> { | |
| internal var cursor = 0 | |
| override fun hasNext() = size > 0 && cursor <= highest | |
| override tailrec fun next(): T = get(cursor++) ?: next() | |
| override fun remove() { | |
| set(cursor, null) | |
| } | |
| } | |
| private var reusableIterator = Iterator() | |
| override fun iterator(): MutableIterator<T> { | |
| reusableIterator.cursor = 0 | |
| return reusableIterator | |
| } | |
| private val arr = arrayOfNulls<Any>(capacity) | |
| var size = 0 | |
| var highest = 0 | |
| operator fun get(id: Int) = arr[id] as? T | |
| operator fun set(id: Int, mob: T?): T? { | |
| val last = arr[id] | |
| arr[id] = mob | |
| if (last == null && mob != null) { | |
| size++ | |
| if (highest < id) highest = id | |
| } else if (last != null && mob == null) { | |
| size-- | |
| if (highest == id) highest-- | |
| } | |
| return last as? T | |
| } | |
| fun nextIndex(): Int { | |
| for (i in 0..size - 1) if (arr[i] != null) return i | |
| throw IllegalStateException("There is no next index because the indexer is filled to capacity!") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment