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

Corrected slice() method of BytesList class and added 2 tests #3292

Merged
merged 4 commits into from
Apr 3, 2023
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
18 changes: 11 additions & 7 deletions bytes/bytes_list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,19 @@ export class BytesList {
const startIdx = this.getChunkIndex(start);
const endIdx = this.getChunkIndex(end - 1);
let written = 0;
for (let i = startIdx; i < endIdx; i++) {
const chunk = this.#chunks[i];
const len = chunk.end - chunk.start;
result.set(chunk.value.subarray(chunk.start, chunk.end), written);
for (let i = startIdx; i <= endIdx; i++) {
const {
value: chunkValue,
start: chunkStart,
end: chunkEnd,
offset: chunkOffset,
} = this.#chunks[i];
const readStart = chunkStart + (i === startIdx ? start - chunkOffset : 0);
const readEnd = i === endIdx ? end - chunkOffset + chunkStart : chunkEnd;
const len = readEnd - readStart;
result.set(chunkValue.subarray(readStart, readEnd), written);
written += len;
}
const last = this.#chunks[endIdx];
const rest = end - start - written;
result.set(last.value.subarray(last.start, last.start + rest), written);
return result;
}
/**
Expand Down
10 changes: 10 additions & 0 deletions bytes/bytes_list_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,16 @@ Deno.test("[bytes] BytesList.add should throw if invalid range", () => {
});
Deno.test("[bytes] BytesList.slice", () => {
const arr = setup();

const arrWithContent = new BytesList();
const te = new TextEncoder();
const td = new TextDecoder();

arrWithContent.add(te.encode("Some dummy example "), 2, 13);
arrWithContent.add(te.encode("to show it does work now"), 5, 20);
assertEquals(td.decode(arrWithContent.slice(5, 9)), "mmy ");
assertEquals(td.decode(arrWithContent.slice(9, 13)), "exow");

assertEquals(
bytes.equals(arr.slice(0, 4), new Uint8Array([0, 1, 2, 3])),
true,
Expand Down