import SeaArray from './SeaArray' ; import { base64 } from './base64' ; function SafeBuffer ( ... props ) { console . warn ( 'new SafeBuffer() is depreciated, please use SafeBuffer.from()' ) ; return ( < any > SafeBuffer ) . from ( ... props ) ; } SafeBuffer . prototype = Object . create ( Array . prototype ) ; Object . assign ( SafeBuffer , { from ( ) { if ( ! Object . keys ( arguments ) . length ) { throw new TypeError ( 'First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.' ) ; } const input = arguments [ 0 ] ; let buf ; if ( typeof input === 'string' ) { const enc = arguments [ 1 ] || 'utf8' ; if ( enc === 'hex' ) { const bytes = ( < any > input ) . match ( /([\da-fA-F]{2})/g ) . map ( ( byte ) => parseInt ( byte , 16 ) ) ; if ( ! bytes || ! bytes . length ) { throw new TypeError ( "Invalid first argument for type 'hex'." ) ; } buf = SeaArray . from ( bytes ) ; } else if ( enc === 'utf8' ) { const length = input . length ; const words = new Uint16Array ( length ) ; for ( let i = 0 ; i < length ; i ++ ) { words [ i ] = input . charCodeAt ( i ) ; } buf = SeaArray . from ( words ) ; } else if ( enc === 'base64' ) { const dec = base64 . atob ( input ) ; const length = dec . length ; const bytes = new Uint8Array ( length ) ; for ( let i = 0 ; i < length ; i ++ ) { bytes [ i ] = dec . charCodeAt ( i ) ; } buf = SeaArray . from ( bytes ) ; } else if ( enc === 'binary' ) { buf = SeaArray . from ( input ) ; } else { console . info ( 'SafeBuffer.from unknown encoding: ' + enc ) ; } return buf ; } const length = input . byteLength ? input . byteLength : input . length ; if ( length ) { let buf ; if ( input instanceof ArrayBuffer ) { buf = new Uint8Array ( input ) ; } return SeaArray . from ( buf || input ) ; } } , alloc ( length , fill = 0 ) { return SeaArray . from ( new Uint8Array ( Array . from ( { length : length } , ( ) => fill ) ) ) ; } , allocUnsafe ( length ) { return SeaArray . from ( new Uint8Array ( Array . from ( { length : length } ) ) ) ; } , concat ( arr ) { if ( ! Array . isArray ( arr ) ) { throw new TypeError ( 'First argument must be Array containing ArrayBuffer or Uint8Array instances.' ) ; } return SeaArray . from ( arr . reduce ( ( ret , item ) => ret . concat ( Array . from ( item ) ) , [ ] ) ) ; } } ) ; SafeBuffer . prototype . from = ( < any > SafeBuffer ) . from ; SafeBuffer . prototype . toString = SeaArray . prototype . toString ; export default < any > SafeBuffer ;