You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
// utils/dynamicArrayBuffer.js
class DynamicArrayBuffer {
constructor ( initialSize = 1024 ) {
this . buffer = new ArrayBuffer ( initialSize ) ; // 初始的ArrayBuffer
this . view = new Uint8Array ( this . buffer ) ; // Uint8Array视图, 用于操作ArrayBuffer
this . offset = 0 ; // 记录当前已写入的字节数
}
// 扩展ArrayBuffer的大小
expandBuffer ( newSize ) {
const newBuffer = new ArrayBuffer ( newSize ) ; // 创建新的ArrayBuffer
const newView = new Uint8Array ( newBuffer ) ; // 创建新的Uint8Array视图
// 复制旧数据到新buffer
newView . set ( this . view ) ;
// 更新当前buffer和视图
this . buffer = newBuffer ;
this . view = newView ;
}
// 向ArrayBuffer添加数据
appendData ( data ) {
const dataLength = data . length ;
// 如果当前的数据空间不足, 扩展buffer
if ( this . offset + dataLength > this . buffer . byteLength ) {
let newSize = Math . max ( this . buffer . byteLength * 2 , this . offset + dataLength ) ;
this . expandBuffer ( newSize ) ; // 扩展buffer
}
// 将数据写入buffer
this . view . set ( data , this . offset ) ;
this . offset += dataLength ; // 更新偏移量
}
// 获取当前缓冲区的内容
getBuffer ( ) {
return this . view . slice ( 0 , this . offset ) ; // 返回有效数据部分
}
}
module . exports = DynamicArrayBuffer ;