|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 Apple Inc. and the Swift.org project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of Swift.org project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +package com.example.swift; |
| 16 | + |
| 17 | +import org.junit.jupiter.api.Test; |
| 18 | +import org.swift.swiftkit.core.*; |
| 19 | +import org.swift.swiftkit.ffm.*; |
| 20 | + |
| 21 | +import static org.junit.jupiter.api.Assertions.*; |
| 22 | + |
| 23 | +import java.lang.foreign.ValueLayout; |
| 24 | +import java.util.Arrays; |
| 25 | +import java.util.concurrent.atomic.AtomicLong; |
| 26 | +import java.util.stream.IntStream; |
| 27 | + |
| 28 | +public class WithBufferTest { |
| 29 | + @Test |
| 30 | + void test_withBuffer() { |
| 31 | + AtomicLong bufferSize = new AtomicLong(); |
| 32 | + MySwiftLibrary.withBuffer((buf) -> { |
| 33 | + CallTraces.trace("withBuffer{$0.byteSize()}=" + buf.byteSize()); |
| 34 | + bufferSize.set(buf.byteSize()); |
| 35 | + }); |
| 36 | + |
| 37 | + assertEquals(124, bufferSize.get()); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + void test_sumAllByteArrayElements_throughMemorySegment() { |
| 42 | + byte[] bytes = new byte[124]; |
| 43 | + Arrays.fill(bytes, (byte) 1); |
| 44 | + |
| 45 | + try (var arena = AllocatingSwiftArena.ofConfined()) { |
| 46 | + // NOTE: We cannot use MemorySegment.ofArray because that creates a HEAP backed segment and therefore cannot pass into native: |
| 47 | + // java.lang.IllegalArgumentException: Heap segment not allowed: MemorySegment{ kind: heap, heapBase: [B@5b6ec132, address: 0x0, byteSize: 124 } |
| 48 | + // MemorySegment bytesSegment = MemorySegment.ofArray(bytes); // NO COPY (!) |
| 49 | + // MySwiftLibrary.sumAllByteArrayElements(bytesSegment, bytes.length); |
| 50 | + |
| 51 | + var bytesCopy = arena.allocateFrom(ValueLayout.JAVA_BYTE, bytes); |
| 52 | + var swiftSideSum = MySwiftLibrary.sumAllByteArrayElements(bytesCopy, bytes.length); |
| 53 | + |
| 54 | + System.out.println("swiftSideSum = " + swiftSideSum); |
| 55 | + |
| 56 | + int javaSideSum = IntStream.range(0, bytes.length).map(i -> bytes[i]).sum(); |
| 57 | + assertEquals(javaSideSum, swiftSideSum); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments