Created
November 13, 2020 16:12
-
-
Save sczerwinski/7858d9a34d606960673d0361c22fc841 to your computer and use it in GitHub Desktop.
Creating direct FloatBuffer from List<Float>
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
import java.nio.ByteBuffer | |
import java.nio.ByteOrder | |
import java.nio.FloatBuffer | |
private const val FLOAT_BYTES = 4 | |
fun List<Float>.toDirectFloatBuffer(): FloatBuffer = | |
ByteBuffer.allocateDirect(size * FLOAT_BYTES) | |
.apply { order(ByteOrder.nativeOrder()) } | |
.asFloatBuffer() | |
.put(toFloatArray()) | |
.apply { rewind() } |
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
import org.junit.jupiter.api.Assertions.assertEquals | |
import org.junit.jupiter.api.Assertions.assertTrue | |
import org.junit.jupiter.api.DisplayName | |
import org.junit.jupiter.api.Test | |
import org.junit.jupiter.api.assertAll | |
@DisplayName(value = "Creating direct FloatBuffer") | |
class FloatBufferTest { | |
@Test | |
@DisplayName(value = "GIVEN list of floats, WHEN toDirectFloatBuffer, THEN return direct buffer of floats") | |
fun toDirectFloatBuffer() { | |
val list = listOf(1f, 2f, 3f) | |
val result = list.toDirectFloatBuffer() | |
assertAll( | |
"buffer", | |
{ assertTrue(result.isDirect) }, | |
{ assertEquals(3, result.capacity()) }, | |
{ assertEquals(1f, result[0]) }, | |
{ assertEquals(2f, result[1]) }, | |
{ assertEquals(3f, result[2]) } | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment