beehive-lab / TornadoVM

TornadoVM: A practical and efficient heterogeneous programming framework for managed languages
https://www.tornadovm.org
Apache License 2.0
1.16k stars 109 forks source link

Support to construct TornadoNativeArrays from ByteBuffers through memory segment direct copies #402

Closed mikepapadim closed 2 months ago

mikepapadim commented 2 months ago

Description

Currently, we support building TornadoNative arrays directly from primitive arrays and MemorySegments, but we were missing support for Java NIO ByteBuffers.

Example usage:

  // Step 1: Create and populate a FloatBuffer
  FloatBuffer buffer = FloatBuffer.allocate(5); // Allocate a FloatBuffer with capacity for 5 floats
  buffer.put(new float[]{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // Put some values into the buffer
  buffer.flip(); // Reset the position to the start of the buffer to read from it

  // Step 2: Use the fromFloatBuffer method to create a FloatArray
  FloatArray floatArray = FloatArray.fromFloatBuffer(buffer);

Backend/s tested

Mark the backends affected by this PR.

OS tested

Mark the OS where this PR is tested.

Did you check on FPGAs?

If it is applicable, check your changes on FPGAs.

How to test the new patch?

make 

 tornado-test -V uk.ac.manchester.tornado.unittests.api.TestBuildFromByteBuffers
WARNING: Using incubator modules: jdk.incubator.vector

Test: class uk.ac.manchester.tornado.unittests.api.TestBuildFromByteBuffers
    Running test: testBuildFromFloatBuffer   ................  [PASS] 
    Running test: testBuildFromDoubleBuffer  ................  [PASS] 
    Running test: testBuildFromIntBuffer     ................  [PASS] 
    Running test: testBuildFromLongBuffer    ................  [PASS] 
    Running test: testBuildFromShortBuffer   ................  [PASS] 
    Running test: testBuildFromCharBuffer    ................  [PASS] 
Test ran: 6, Failed: 0, Unsupported: 0

jjfumero commented 2 months ago

Thanks Michali. Let's add also unit tests.

mikepapadim commented 2 months ago

Done, I added the unit-tests in a seperate class from the rest of the API constructors in case we want to deprecate/remote in the near future in favour of the Memory segment utilities. So, we can easilty remove it.