buffer-list.ts
1 export default class BufferList { 2 constructor(public buffers: Buffer[] = []) {} 3 4 public add(buffer: Buffer, front?: boolean) { 5 this.buffers[front ? 'unshift' : 'push'](buffer) 6 return this 7 } 8 9 public addInt16(val: number, front?: boolean) { 10 return this.add(Buffer.from([val >>> 8, val >>> 0]), front) 11 } 12 13 public getByteLength() { 14 return this.buffers.reduce(function (previous, current) { 15 return previous + current.length 16 }, 0) 17 } 18 19 public addInt32(val: number, first?: boolean) { 20 return this.add( 21 Buffer.from([(val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, (val >>> 0) & 0xff]), 22 first 23 ) 24 } 25 26 public addCString(val: string, front?: boolean) { 27 const len = Buffer.byteLength(val) 28 const buffer = Buffer.alloc(len + 1) 29 buffer.write(val) 30 buffer[len] = 0 31 return this.add(buffer, front) 32 } 33 34 public addString(val: string, front?: boolean) { 35 const len = Buffer.byteLength(val) 36 const buffer = Buffer.alloc(len) 37 buffer.write(val) 38 return this.add(buffer, front) 39 } 40 41 public addChar(char: string, first?: boolean) { 42 return this.add(Buffer.from(char, 'utf8'), first) 43 } 44 45 public addByte(byte: number) { 46 return this.add(Buffer.from([byte])) 47 } 48 49 public join(appendLength?: boolean, char?: string): Buffer { 50 let length = this.getByteLength() 51 if (appendLength) { 52 this.addInt32(length + 4, true) 53 return this.join(false, char) 54 } 55 if (char) { 56 this.addChar(char, true) 57 length++ 58 } 59 const result = Buffer.alloc(length) 60 let index = 0 61 this.buffers.forEach(function (buffer) { 62 buffer.copy(result, index, 0) 63 index += buffer.length 64 }) 65 return result 66 } 67 }