Skip to content

Commit

Permalink
expand ExpandingBuffer.#heap in 0x1000 byte chunks when appending new…
Browse files Browse the repository at this point in the history
… data
  • Loading branch information
meszaros-lajos-gyorgy committed Dec 24, 2022
1 parent c7909b9 commit 5e4b207
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
30 changes: 21 additions & 9 deletions src/ExpandingBuffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Buffer } from 'node:buffer'
import { EMPTY_BUFFER } from './constants'
import { clamp } from './functions'

let cntr = 0

export class ExpandingBuffer {
#heap: Buffer
#startIndex: number = 0
Expand All @@ -28,18 +30,28 @@ export class ExpandingBuffer {
}

heapSize() {
return this.#heap.length
return this.#heap.byteLength
}

append(buffer: Buffer) {
if (this.#endIndex + buffer.length < this.heapSize()) {
buffer.copy(this.#heap, this.#endIndex)
this.#endIndex += buffer.length
} else {
this.#heap = Buffer.concat([this.#getActualData(), buffer])
this.#startIndex = 0
this.#endIndex = this.heapSize()
append(newData: Buffer) {
if (this.#endIndex + newData.byteLength < this.heapSize()) {
newData.copy(this.#heap, this.#endIndex)
this.#endIndex += newData.byteLength
return
}

const blockSize = 0x1000

const currentData = this.#getActualData()

this.#heap = Buffer.allocUnsafe(
(Math.ceil((currentData.byteLength + newData.byteLength) / blockSize) + 1) * blockSize,
)
currentData.copy(this.#heap, 0)
newData.copy(this.#heap, currentData.byteLength)

this.#startIndex = 0
this.#endIndex = currentData.byteLength + newData.byteLength
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Explode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export class Explode {
#asciiTable2D34: number[] = repeat(0, 0x100)
#asciiTable2E34: number[] = repeat(0, 0x80)
#asciiTable2EB4: number[] = repeat(0, 0x100)
#reusableByte: Buffer = Buffer.alloc(1)
#reusableByte: Buffer = Buffer.allocUnsafe(1)

constructor(config: Config = {}) {
this.#verbose = config?.verbose ?? false
Expand Down
2 changes: 1 addition & 1 deletion src/Implode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class Implode {
#outBits: number = 0
#nChBits: number[] = repeat(0, 0x306)
#nChCodes: number[] = repeat(0, 0x306)
#reusableByte: Buffer = Buffer.alloc(1)
#reusableByte: Buffer = Buffer.allocUnsafe(1)

constructor(compressionType: Compression, dictionarySize: DictionarySize, config: Config) {
if (!(compressionType in Compression) || compressionType === Compression.Unknown) {
Expand Down

0 comments on commit 5e4b207

Please sign in to comment.