From 9af6d262fe60e5eba6556e210e6cde8bf850d8d2 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Fri, 18 Aug 2023 17:54:52 +0200 Subject: [PATCH] classlib: properly implement ByteOrder.nativeOrder --- .../teavm/classlib/java/nio/TByteOrder.java | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/nio/TByteOrder.java b/classlib/src/main/java/org/teavm/classlib/java/nio/TByteOrder.java index 90058eb29..79ef0e5b4 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/nio/TByteOrder.java +++ b/classlib/src/main/java/org/teavm/classlib/java/nio/TByteOrder.java @@ -15,9 +15,16 @@ */ package org.teavm.classlib.java.nio; +import org.teavm.classlib.PlatformDetector; +import org.teavm.interop.Address; +import org.teavm.jso.typedarrays.ArrayBuffer; +import org.teavm.jso.typedarrays.Int16Array; +import org.teavm.jso.typedarrays.Int8Array; + public final class TByteOrder { public static final TByteOrder BIG_ENDIAN = new TByteOrder("BIG_ENDIAN"); public static final TByteOrder LITTLE_ENDIAN = new TByteOrder("LITTLE_ENDIAN"); + private static TByteOrder nativeOrder; private String name; private TByteOrder(String name) { @@ -25,7 +32,21 @@ public final class TByteOrder { } public static TByteOrder nativeOrder() { - return BIG_ENDIAN; + if (nativeOrder == null) { + if (PlatformDetector.isJavaScript()) { + var buffer = ArrayBuffer.create(2); + var shortArray = Int16Array.create(buffer); + shortArray.set(0, (short) 1); + var byteArray = Int8Array.create(buffer); + nativeOrder = byteArray.get(0) == 0 ? BIG_ENDIAN : LITTLE_ENDIAN; + } else { + var array = new short[1]; + array[0] = 1; + var firstByte = Address.ofData(array).getByte(); + nativeOrder = firstByte == 0 ? BIG_ENDIAN : LITTLE_ENDIAN; + } + } + return nativeOrder; } @Override