Speed up encodeBinaryNode in x100 times if encoding many items in content (#882)

Do not convert to buffer in inner recursion, we need it only at the end
This commit is contained in:
devlikeapro
2024-07-03 14:27:40 +07:00
committed by GitHub
parent 13be112b18
commit f1fe3ea115

View File

@@ -4,10 +4,19 @@ import { FullJid, jidDecode } from './jid-utils'
import type { BinaryNode, BinaryNodeCodingOptions } from './types'
export const encodeBinaryNode = (
{ tag, attrs, content }: BinaryNode,
node: BinaryNode,
opts: Pick<BinaryNodeCodingOptions, 'TAGS' | 'TOKEN_MAP'> = constants,
buffer: number[] = [0]
) => {
): Buffer => {
const encoded = encodeBinaryNodeInner(node, opts, buffer)
return Buffer.from(encoded)
}
const encodeBinaryNodeInner = (
{ tag, attrs, content }: BinaryNode,
opts: Pick<BinaryNodeCodingOptions, 'TAGS' | 'TOKEN_MAP'>,
buffer: number[]
): number[] => {
const { TAGS, TOKEN_MAP } = opts
const pushByte = (value: number) => buffer.push(value & 0xff)
@@ -224,7 +233,7 @@ export const encodeBinaryNode = (
} else if(Array.isArray(content)) {
writeListStart(content.length)
for(const item of content) {
encodeBinaryNode(item, opts, buffer)
encodeBinaryNodeInner(item, opts, buffer)
}
} else if(typeof content === 'undefined') {
// do nothing
@@ -232,5 +241,5 @@ export const encodeBinaryNode = (
throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
}
return Buffer.from(buffer)
return buffer
}