Complex buffer optimization

This commit is contained in:
Alexander Nozik 2019-02-12 12:28:35 +03:00
parent c3989159ab
commit 91207c8c9a
3 changed files with 15 additions and 12 deletions

View File

@ -26,10 +26,16 @@ object ComplexBufferSpec : FixedSizeBufferSpec<Complex> {
/**
* Create a read-only/mutable buffer which ignores boxing
*/
fun Buffer.Companion.complex(size: Int, initializer: ((Int) -> Complex)? = null): Buffer<Complex> =
fun Buffer.Companion.complex(size: Int): Buffer<Complex> =
ObjectBuffer.create(ComplexBufferSpec, size)
inline fun Buffer.Companion.complex(size: Int, crossinline initializer: (Int) -> Complex): Buffer<Complex> =
ObjectBuffer.create(ComplexBufferSpec, size, initializer)
fun MutableBuffer.Companion.complex(size: Int, initializer: ((Int) -> Complex)? = null) =
fun MutableBuffer.Companion.complex(size: Int) =
ObjectBuffer.create(ComplexBufferSpec, size)
inline fun MutableBuffer.Companion.complex(size: Int, crossinline initializer: (Int) -> Complex) =
ObjectBuffer.create(ComplexBufferSpec, size, initializer)
fun NDField.Companion.complex(shape: IntArray) = ComplexNDField(shape)

View File

@ -26,13 +26,14 @@ class ObjectBuffer<T : Any>(private val buffer: ByteBuffer, private val spec: Fi
}
companion object {
fun <T : Any> create(spec: FixedSizeBufferSpec<T>, size: Int, initializer: ((Int) -> T)? = null) =
fun <T : Any> create(spec: FixedSizeBufferSpec<T>, size: Int) =
ObjectBuffer(ByteBuffer.allocate(size * spec.unitSize), spec)
inline fun <T : Any> create(spec: FixedSizeBufferSpec<T>, size: Int, crossinline initializer: (Int) -> T) =
ObjectBuffer(ByteBuffer.allocate(size * spec.unitSize), spec).also { buffer ->
if (initializer != null) {
(0 until size).forEach {
buffer[it] = initializer(it)
}
}
}
}
}

View File

@ -7,11 +7,7 @@ import kotlin.test.assertEquals
class ComplexBufferSpecTest {
@Test
fun testComplexBuffer() {
val buffer = MutableBuffer.complex(20)
(0 until 20).forEach {
buffer[it] = Complex(it.toDouble(), -it.toDouble())
}
val buffer = MutableBuffer.complex(20){Complex(it.toDouble(), -it.toDouble())}
assertEquals(Complex(5.0, -5.0), buffer[5])
}
}