summaryrefslogtreecommitdiff
path: root/java
diff options
context:
space:
mode:
authorWouter van Oortmerssen <wvo@google.com>2016-04-22 11:42:14 -0700
committerWouter van Oortmerssen <wvo@google.com>2016-04-22 11:42:14 -0700
commita0d1161feb49e6db4027066134b212b7446fdc66 (patch)
treeedbc6d671b1e6708dfbbb87e52a28cee54ae8b6c /java
parent828b2680c0d8fdad4638f2985d934895c4fa115c (diff)
parent6908826f9506fc0149d7bb60e0cc45aafa532f4a (diff)
downloadflatbuffers-a0d1161feb49e6db4027066134b212b7446fdc66.tar.gz
flatbuffers-a0d1161feb49e6db4027066134b212b7446fdc66.tar.bz2
flatbuffers-a0d1161feb49e6db4027066134b212b7446fdc66.zip
Merge pull request #3850 from pjulien/3849
Fix for #3849
Diffstat (limited to 'java')
-rwxr-xr-xjava/com/google/flatbuffers/FlatBufferBuilder.java33
1 files changed, 27 insertions, 6 deletions
diff --git a/java/com/google/flatbuffers/FlatBufferBuilder.java b/java/com/google/flatbuffers/FlatBufferBuilder.java
index 107da88d..480bb9d3 100755
--- a/java/com/google/flatbuffers/FlatBufferBuilder.java
+++ b/java/com/google/flatbuffers/FlatBufferBuilder.java
@@ -17,6 +17,11 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
+
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
import java.util.Arrays;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -45,6 +50,8 @@ public class FlatBufferBuilder {
int num_vtables = 0; // Number of entries in `vtables` in use.
int vector_num_elems = 0; // For the current vector being built.
boolean force_defaults = false; // False omits default values from the serialized data.
+ CharsetEncoder encoder = utf8charset.newEncoder();
+ ByteBuffer dst;
/// @endcond
/**
@@ -367,12 +374,26 @@ public class FlatBufferBuilder {
* @return The offset in the buffer where the encoded string starts.
*/
public int createString(String s) {
- byte[] utf8 = s.getBytes(utf8charset);
- addByte((byte)0);
- startVector(1, utf8.length, 1);
- bb.position(space -= utf8.length);
- bb.put(utf8, 0, utf8.length);
- return endVector();
+ int length = s.length();
+ int estimatedDstCapacity = (int) (length * encoder.maxBytesPerChar());
+ if (dst == null || dst.capacity() < estimatedDstCapacity) {
+ dst = ByteBuffer.allocate(Math.max(128, estimatedDstCapacity));
+ }
+
+ dst.clear();
+
+ CharBuffer src = CharBuffer.wrap(s);
+ CoderResult result = encoder.encode(src, dst, true);
+ if (result.isError()) {
+ try {
+ result.throwException();
+ } catch (CharacterCodingException x) {
+ throw new Error(x);
+ }
+ }
+
+ dst.flip();
+ return createString(dst);
}
/**