Merge pull request #4611 from anuraaga/remove-string-move

[Java] Remove unsafe no-copy String allocation since it's not useful in rece…
pull/4505/merge
Feng Xiao 7 years ago committed by GitHub
commit 6dda83dc8c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 27
      java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
  2. 10
      java/core/src/main/java/com/google/protobuf/Utf8.java

@ -33,7 +33,6 @@ package com.google.protobuf;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
@ -72,8 +71,6 @@ final class UnsafeUtil {
private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(bufferAddressField());
private static final long STRING_VALUE_OFFSET = fieldOffset(stringValueField());
private UnsafeUtil() {}
static boolean hasUnsafeArrayOperations() {
@ -149,10 +146,6 @@ final class UnsafeUtil {
return MEMORY_ACCESSOR.getObject(target, offset);
}
static void putObject(Object target, long offset, Object value) {
MEMORY_ACCESSOR.putObject(target, offset, value);
}
static byte getByte(byte[] target, long index) {
return MEMORY_ACCESSOR.getByte(target, BYTE_ARRAY_BASE_OFFSET + index);
}
@ -262,26 +255,6 @@ final class UnsafeUtil {
return MEMORY_ACCESSOR.getLong(buffer, BUFFER_ADDRESS_OFFSET);
}
/**
* Returns a new {@link String} backed by the given {@code chars}. The char array should not
* be mutated any more after calling this function.
*/
static String moveToString(char[] chars) {
if (STRING_VALUE_OFFSET == -1) {
// In the off-chance that this JDK does not implement String as we'd expect, just do a copy.
return new String(chars);
}
final String str;
try {
str = (String) UNSAFE.allocateInstance(String.class);
} catch (InstantiationException e) {
// This should never happen, but return a copy as a fallback just in case.
return new String(chars);
}
putObject(str, STRING_VALUE_OFFSET, chars);
return str;
}
static Object getStaticObject(Field field) {
return MEMORY_ACCESSOR.getStaticObject(field);
}

@ -1474,10 +1474,7 @@ final class Utf8 {
}
}
if (resultPos < resultArr.length) {
resultArr = Arrays.copyOf(resultArr, resultPos);
}
return UnsafeUtil.moveToString(resultArr);
return new String(resultArr, 0, resultPos);
}
@Override
@ -1553,10 +1550,7 @@ final class Utf8 {
}
}
if (resultPos < resultArr.length) {
resultArr = Arrays.copyOf(resultArr, resultPos);
}
return UnsafeUtil.moveToString(resultArr);
return new String(resultArr, 0, resultPos);
}
@Override

Loading…
Cancel
Save