2 // Based on the C implementation from the RFC:
3 // http://tools.ietf.org/html/rfc3492
5 // Compilation Options:
6 // MONO_PUNYCODE_PUBLIC:
7 // Makes the class public instead of the default internal.
9 // Copyright (C) 2010 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 #if MONO_PUNYCODE_PUBLIC
40 static class Punycode {
47 // 0..25 map to ASCII a..z or A..Z
48 // 26..35 map to ASCII 0..9
49 static char encode_digit (int d)
51 return (char) (d + 22 + (d < 26 ? 75 : 0));
54 /* Bias adaptation function */
55 static int adapt (int delta, int numpoints, bool firsttime)
59 delta = firsttime ? delta / DAMP : delta >> 1;
60 /* delta >> 1 is a faster way of doing delta / 2 */
61 delta += delta / numpoints;
63 for (k = 0; delta > ((BASE - TMIN) * TMAX) / 2; k += BASE)
66 return k + (BASE - TMIN + 1) * delta / (delta + SKEW);
69 public static string Encode (string input)
71 var result = new StringBuilder ();
73 foreach (char c in input){
78 h = b = result.Length;
80 if (h != input.Length)
87 while (h < input.Length) {
88 int m = Int32.MaxValue;
90 // Find the next code point
91 foreach (char c in input){
97 if (m - n > (Int32.MaxValue - delta) / (h + 1))
98 throw new OverflowException ();
100 delta += (m - n) * (h + 1);
103 foreach (char c in input){
106 // Punycode does not need to check whether input[j] is basic
109 throw new OverflowException ();
111 /* Represent delta as a generalized variable-length integer: */
114 for (int k = BASE; ; k += BASE) {
115 int t = k <= bias ? TMIN : k >= bias + TMAX ? TMAX : k - bias;
118 result.Append (encode_digit (t + (q - t) % (BASE - t)));
119 q = (q - t) / (BASE - t);
122 result.Append (encode_digit (q));
123 bias = adapt (delta, h + 1, h == b);
132 return result.ToString ();