Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(datastore): fix copyTo/setBytes function of SwByteBuffer #1232

Merged
merged 1 commit into from
Sep 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ public int getBytes(int index, byte[] b, int offset, int len) {
@Override
public void setBytes(int index, byte[] b, int offset, int len) {
this.buf.position(index);
if (len > this.buf.remaining()) {
len = this.buf.remaining();
}
this.buf.put(b, offset, len);
}

Expand All @@ -141,7 +144,7 @@ public SwBuffer slice(int offset, int len) {

@Override
public void copyTo(SwBuffer buf) {
buf.setBytes(0, this.buf.array(), 0, this.buf.limit());
buf.setBytes(0, this.buf.array(), this.buf.arrayOffset(), this.buf.limit());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import ai.starwhale.mlops.memory.SwBuffer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
Expand Down Expand Up @@ -79,4 +80,31 @@ public void testSlice() {
this.buffer.setString(0, "1234567890");
assertThat(buf.asByteBuffer(), is(ByteBuffer.wrap("23456".getBytes(StandardCharsets.UTF_8))));
}

@Test
public void testCopyTo() {
var base = new SwByteBuffer(5);
base.setBytes(0, new byte[]{1, 2, 3, 4, 5}, 0, 5);
// make a SwBuffer with non-zero offset
var src = base.slice(1, base.capacity() - 1);
var dst = new SwByteBuffer(5);
src.copyTo(dst);
assertThat(dst.getByte(0), is(src.getByte(0)));
}

@Test
void testSetBytes() {
final int cap = 3;
var buf = new SwByteBuffer(cap);
var src = new byte[]{1, 2, 3, 4};
buf.setBytes(0, src, 0, src.length);

var b = new byte[5];
assertThat(buf.getBytes(0, b, 0, b.length), is(cap));
assertThat(b, is(new byte[]{1, 2, 3, 0, 0}));

buf.setBytes(1, src, 0, src.length);
assertThat(buf.getBytes(0, b, 0, b.length), is(cap));
assertThat(b, is(new byte[]{1, 1, 2, 0, 0}));
}
}