Skip to content

Commit 734634c

Browse files
authored
Merge pull request #39 from JavaBWAPI/fasterGetPutString
Map strings without encoding/decoding them
2 parents cac744f + fdc3868 commit 734634c

File tree

2 files changed

+16
-18
lines changed

2 files changed

+16
-18
lines changed

src/main/java/bwapi/WrappedBuffer.java

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@
1414
* Wrapper around ByteBuffer that makes use of sun.misc.Unsafe if available.
1515
*/
1616
class WrappedBuffer {
17-
private static final Charset charSet = StandardCharsets.ISO_8859_1;
18-
private static final CharsetEncoder enc = charSet.newEncoder();
19-
2017
private final ByteBuffer buffer;
2118
private final long address;
2219
private final Unsafe unsafe;
@@ -72,25 +69,26 @@ void putDouble(final int offset, final double value) {
7269
}
7370

7471
String getString(final int offset, final int maxLen) {
75-
buffer.position(offset);
76-
ByteBuffer source = buffer.slice();
77-
int rem = maxLen - 1;
78-
while (source.get() != 0 && rem > 0) {
79-
rem--;
80-
}
81-
if (rem > 0) {
82-
source.position(source.position() - 1);
72+
char[] buf = new char[maxLen];
73+
long pos = offset + address;
74+
for (int i = 0; i < maxLen; i++) {
75+
byte b = unsafe.getByte(pos);
76+
if (b == 0) break;
77+
buf[i] = (char) (b & 0xff);
78+
pos++;
8379
}
84-
source.flip();
85-
return charSet.decode(source).toString();
80+
return new String(buf, 0, (int) (pos - offset - address));
8681
}
8782

8883
void putString(final int offset, final int maxLen, final String string) {
8984
if (string.length() + 1 >= maxLen) {
9085
throw new StringIndexOutOfBoundsException();
9186
}
92-
buffer.position(offset);
93-
enc.encode(CharBuffer.wrap(string), buffer, true);
94-
buffer.put((byte) 0);
87+
long pos = offset + address;
88+
for (int i = 0; i < string.length(); i++) {
89+
unsafe.putByte(pos, (byte) string.charAt(i));
90+
pos++;
91+
}
92+
unsafe.putByte(pos, (byte) 0);
9593
}
9694
}

src/test/java/bwapi/WrappedBufferTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public class WrappedBufferTest {
1212
@Test
1313
public void shouldGetAndSetStrings() {
1414
// GIVEN
15-
String testString = "Test";
15+
String testString = "@µöú";
1616
sut.putString(123, 100, testString);
1717

1818
// WHEN
@@ -25,7 +25,7 @@ public void shouldGetAndSetStrings() {
2525
@Test
2626
public void shouldCutOffAtMaxLength() {
2727
// GIVEN
28-
String testString = "Test";
28+
String testString = "@µöú";
2929
sut.putString(123, 100, testString);
3030

3131
// WHEN

0 commit comments

Comments
 (0)