import * as ref from 'ref-napi' ; export interface BufferType extends ref . Type { size : number ; encoding : BufferEncoding ; } see https ref export function BufferTypeFactory ( length , encoding ? ) { const inst = Object . create ( ref . types . byte , { constructor : { configurable : true , enumerable : false , writable : true , value : BufferTypeFactory , } , } ) as BufferType ; Object . defineProperty ( inst , 'size' , { configurable : true , enumerable : true , writable : false , value : length , } ) ; Object . defineProperty ( inst , 'encoding' , { configurable : true , enumerable : true , writable : true , value : encoding , } ) ; Object . defineProperty ( inst , 'get' , { configurable : true , enumerable : true , writable : true , value : getFn , } ) ; Object . defineProperty ( inst , 'set' , { configurable : true , enumerable : true , writable : true , value : setFn , } ) ; return inst ; } function getFn ( this , buffer , offset ) { const buf = buffer . slice ( offset , offset + this . size ) ; if ( this . encoding ) { const str = buf . toString ( this . encoding ) ; return str ; } return buf ; } function setFn ( this , buffer , offset , value ) { let target ; if ( typeof value === 'string' ) { target = Buffer . from ( value , this . encoding ) ; } else if ( Array . isArray ( value ) ) { target = Buffer . from ( value ) ; } else if ( Buffer . isBuffer ( value ) ) { target = value ; } else { throw new TypeError ( 'Buffer instance expected' ) ; } if ( target . length > this . size ) { throw new Error ( `Buffer given is ${ target . length } bytes, but only ${ this . size } bytes available` ) ; } target . copy ( buffer , offset ) ; }