declare function require ( moduleName ) ; declare var window ; import { TextDecoder as TextDecoderFromTE , TextEncoder as TextEncoderFromTE } from 'text-encoding' ; import CharacterSetECI from './../common/CharacterSetECI' ; import Exception from './../Exception' ; export default class StringEncoding { public static decode ( bytes , encoding ) { let encodingString ; if ( typeof encoding === 'string' ) { encodingString = encoding ; } else { encodingString = encoding . getName ( ) ; } if ( StringEncoding . isBrowser ( ) ) { const TextDecoderBrowser = window [ 'TextDecoder' ] ; if ( undefined !== TextDecoderBrowser ) { return new TextDecoderBrowser ( encoding ) . decode ( bytes ) ; } else { return StringEncoding . decodeFallBack ( bytes , encodingString ) ; } } else { const TextDecoderFromTEClass = require ( 'text-encoding' ) . TextDecoder ; return new TextDecoderFromTEClass ( encodingString ) . decode ( bytes ) ; } } public static encode ( s , encoding ) { let encodingString ; if ( typeof encoding === 'string' ) { encodingString = encoding ; } else { encodingString = encoding . getName ( ) ; } if ( StringEncoding . isBrowser ( ) ) { const TextEncoderBrowser = window [ 'TextEncoder' ] ; const ec = CharacterSetECI . getCharacterSetECIByName ( encodingString ) ; if ( undefined !== TextEncoderBrowser ) { return new TextEncoderBrowser ( encoding ) . encode ( s ) ; } else { return StringEncoding . encodeFallBack ( s , encodingString ) ; } } else { const TextEncoderFromTEClass = require ( 'text-encoding' ) . TextEncoder ; return new TextEncoderFromTEClass ( encodingString , { NONSTANDARD_allowLegacyEncoding : true } ) . encode ( s ) ; } } private static isBrowser ( ) { return typeof window !== 'undefined' && ( { } ) . toString . call ( window ) === '[object Window]' ; } private static decodeFallBack ( bytes , encoding ) { const ec = CharacterSetECI . getCharacterSetECIByName ( encoding ) ; if ( ec . equals ( CharacterSetECI . UTF8 ) || ec . equals ( CharacterSetECI . ISO8859_1 ) || ec . equals ( CharacterSetECI . ASCII ) ) { let s = '' ; for ( let i = 0 , length = bytes . length ; i < length ; i ++ ) { let h = bytes [ i ] . toString ( 16 ) ; if ( h . length < 2 ) { h = '0' + h ; } s += '%' + h ; } return decodeURIComponent ( s ) ; } else if ( ec . equals ( CharacterSetECI . UnicodeBigUnmarked ) ) { return String . fromCharCode . apply ( null , new Uint16Array ( bytes . buffer ) ) ; } else { throw new Exception ( Exception . UnsupportedOperationException , `encoding ${ encoding } not supported` ) ; } } private static encodeFallBack ( s , encoding ) { return null ; } }