classlib: properly implement ByteOrder.nativeOrder

This commit is contained in:
Alexey Andreev 2023-08-18 17:54:52 +02:00
parent a7f115a541
commit 9af6d262fe

View File

@ -15,9 +15,16 @@
*/ */
package org.teavm.classlib.java.nio; 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 final class TByteOrder {
public static final TByteOrder BIG_ENDIAN = new TByteOrder("BIG_ENDIAN"); public static final TByteOrder BIG_ENDIAN = new TByteOrder("BIG_ENDIAN");
public static final TByteOrder LITTLE_ENDIAN = new TByteOrder("LITTLE_ENDIAN"); public static final TByteOrder LITTLE_ENDIAN = new TByteOrder("LITTLE_ENDIAN");
private static TByteOrder nativeOrder;
private String name; private String name;
private TByteOrder(String name) { private TByteOrder(String name) {
@ -25,7 +32,21 @@ public final class TByteOrder {
} }
public static TByteOrder nativeOrder() { 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 @Override