Skip to content

Commit

Permalink
fix: I think it is better than was
Browse files Browse the repository at this point in the history
  • Loading branch information
nugaon committed Mar 25, 2022
1 parent 7606341 commit 81e0b21
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/file.ts
Expand Up @@ -185,21 +185,17 @@ export function getBmtIndexOfSegment(
spanValue: number,
maxChunkPayloadByteLength = 4096,
): { level: number; chunkIndex: number } {
const maxSegmentCount = maxChunkPayloadByteLength / SEGMENT_SIZE
const maxSegmentCount = Math.floor(maxChunkPayloadByteLength / SEGMENT_SIZE)
const maxChunkIndex = Math.floor(spanValue / maxChunkPayloadByteLength)
const chunkBmtLevels = Math.log2(maxSegmentCount) // 7 by default
// last segment index in the file
const lastSegmentIndex = Math.floor((spanValue - 1) / SEGMENT_SIZE)
// the saturated byte length in the BMT tree (on the left)
const fullBytesLength = spanValue - (spanValue % maxChunkPayloadByteLength)
// the saturated segments length in the BMT tree (on the left)
const fullSegmentsLength = fullBytesLength / SEGMENT_SIZE
let level = 0
if (segmentIndex >= fullSegmentsLength && lastSegmentIndex < fullSegmentsLength + maxSegmentCount) {
do {
segmentIndex >>>= chunkBmtLevels
if (Math.floor(segmentIndex / maxSegmentCount) === maxChunkIndex && maxChunkIndex % maxSegmentCount === 0) {
// segmentIndex in carrier chunk
segmentIndex >>>= chunkBmtLevels
while (segmentIndex % SEGMENT_SIZE === 0) {
level++
} while (segmentIndex % SEGMENT_SIZE === 0)
level--
segmentIndex >>>= chunkBmtLevels
}
} else {
segmentIndex >>>= chunkBmtLevels
}
Expand Down
2 changes: 2 additions & 0 deletions test/unit/file.spec.ts
Expand Up @@ -65,6 +65,8 @@ describe('file', () => {
const carrierChunk = leafChunks.pop()
const segmentIndex = Math.floor((fileBytes.length - 1) / 32)
const segmentIdInTree = getBmtIndexOfSegment(segmentIndex, fileBytes.length)
expect(segmentIdInTree.level).toBe(1)
expect(segmentIdInTree.chunkIndex).toBe(1)
expect(tree[segmentIdInTree.level][segmentIdInTree.chunkIndex].address()).toStrictEqual(
carrierChunk.address(),
)
Expand Down

0 comments on commit 81e0b21

Please sign in to comment.