private static String encode ( String s ) { int n = INITIAL_N ; int delta = 0 ; int bias = INITIAL_BIAS ; StringBuffer output = new StringBuffer ( ) ; // Copy all basic code points to the output. int b = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( basicCodePoint ( c ) ) { output . append ( c ) ; b ++ ; } } if ( b > 0 ) { output . append ( DELIMITER ) ; } int h = b ; while ( h < s . length ( ) ) { int m = Integer . MAX_VALUE ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; if ( c >= n && c < m ) { m = c ; } } if ( m - n > ( Integer . MAX_VALUE - delta ) / ( h + 1 ) ) { // This should probably be a java.text.ParseException, but // IllegalArgumentException is what Android's IDN expects. throw new IllegalArgumentException ( "encoding overflow" ) ; } delta = delta + ( m - n ) * ( h + 1 ) ; n = m ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { int c = s . charAt ( j ) ; if ( c < n ) { delta ++ ; if ( 0 == delta ) { throw new IllegalArgumentException ( "encoding overflow" ) ; } } if ( c == n ) { int q = delta ; for ( int k = BASE ; ; k += BASE ) { int t ; if ( k <= bias ) { t = TMIN ; } else if ( k >= bias + TMAX ) { t = TMAX ; } else { t = k - bias ; } if ( q < t ) { break ; } output . append ( ( char ) encodeDigit ( t + ( q - t ) % ( BASE - t ) ) ) ; q = ( q - t ) / ( BASE - t ) ; } output . append ( ( char ) encodeDigit ( q ) ) ; bias = adapt ( delta , h + 1 , h == b ) ; delta = 0 ; h ++ ; } } delta ++ ; n ++ ; } return output . toString ( ) ; }
Encodes a Unicode string to Punycode ASCII .