Skip to content

Commit c654747

Browse files
author
Bytekeeper
committed
Added a unit test for string put/get. (And changed the implementation, although it is at most ~10% faster in local benchmarking)
1 parent 7c74271 commit c654747

File tree

2 files changed

+47
-8
lines changed

2 files changed

+47
-8
lines changed

src/main/java/bwapi/WrappedBuffer.java

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,17 @@ void putDouble(final int offset, final double value) {
7272
}
7373

7474
String getString(final int offset, final int maxLen) {
75-
final byte[] buf = new byte[maxLen];
76-
77-
unsafe.copyMemory(null, address + offset, buf, Unsafe.ARRAY_BYTE_BASE_OFFSET, maxLen);
78-
79-
int len = 0;
80-
while (len < maxLen && buf[len] != 0) {
81-
++len;
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);
8283
}
83-
return new String(buf, 0, len, charSet);
84+
source.flip();
85+
return charSet.decode(source).toString();
8486
}
8587

8688
void putString(final int offset, final int maxLen, final String string) {
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package bwapi;
2+
3+
import org.junit.Test;
4+
5+
import java.nio.ByteBuffer;
6+
7+
import static org.assertj.core.api.Assertions.assertThat;
8+
9+
public class WrappedBufferTest {
10+
private WrappedBuffer sut = new WrappedBuffer(ByteBuffer.allocateDirect(1024));
11+
12+
@Test
13+
public void shouldGetAndSetStrings() {
14+
// GIVEN
15+
String testString = "Test";
16+
sut.putString(123, 100, testString);
17+
18+
// WHEN
19+
String readString = sut.getString(123, 100);
20+
21+
// THEN
22+
assertThat(readString).isEqualTo(testString);
23+
}
24+
25+
@Test
26+
public void shouldCutOffAtMaxLength() {
27+
// GIVEN
28+
String testString = "Test";
29+
sut.putString(123, 100, testString);
30+
31+
// WHEN
32+
String readString = sut.getString(123, 3);
33+
34+
// THEN
35+
assertThat(readString).isEqualTo(testString.substring(0, 3));
36+
}
37+
}

0 commit comments

Comments
 (0)