fixed tests
[mono.git] / mcs / class / System.Web / System.Web / HttpUtility.cs
1 // 
2 // System.Web.HttpUtility
3 //
4 // Authors:
5 //   Patrik Torstensson (Patrik.Torstensson@labs2.com)
6 //   Wictor WilĂ©n (decode/encode functions) (wictor@ibizkit.se)
7 //   Tim Coleman (tim@timcoleman.com)
8 //   Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 //
10 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.Globalization;
35 using System.IO;
36 using System.Security.Permissions;
37 using System.Text;
38 using System.Web.Util;
39
40 namespace System.Web {
41
42         // CAS - no InheritanceDemand here as the class is sealed
43         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44         public sealed class HttpUtility {
45
46                 #region Fields
47         
48                 static Hashtable entities;
49                 static object lock_ = new object ();
50         
51                 #endregion // Fields
52         
53                 static Hashtable Entities {
54                         get {
55                                 lock (lock_) {
56                                         if (entities == null)
57                                                 InitEntities ();
58
59                                         return entities;
60                                 }
61                         }
62                 }
63                 
64                 #region Constructors
65
66                 static void InitEntities ()
67                 {
68                         // Build the hash table of HTML entity references.  This list comes
69                         // from the HTML 4.01 W3C recommendation.
70                         entities = new Hashtable ();
71                         entities.Add ("nbsp", '\u00A0');
72                         entities.Add ("iexcl", '\u00A1');
73                         entities.Add ("cent", '\u00A2');
74                         entities.Add ("pound", '\u00A3');
75                         entities.Add ("curren", '\u00A4');
76                         entities.Add ("yen", '\u00A5');
77                         entities.Add ("brvbar", '\u00A6');
78                         entities.Add ("sect", '\u00A7');
79                         entities.Add ("uml", '\u00A8');
80                         entities.Add ("copy", '\u00A9');
81                         entities.Add ("ordf", '\u00AA');
82                         entities.Add ("laquo", '\u00AB');
83                         entities.Add ("not", '\u00AC');
84                         entities.Add ("shy", '\u00AD');
85                         entities.Add ("reg", '\u00AE');
86                         entities.Add ("macr", '\u00AF');
87                         entities.Add ("deg", '\u00B0');
88                         entities.Add ("plusmn", '\u00B1');
89                         entities.Add ("sup2", '\u00B2');
90                         entities.Add ("sup3", '\u00B3');
91                         entities.Add ("acute", '\u00B4');
92                         entities.Add ("micro", '\u00B5');
93                         entities.Add ("para", '\u00B6');
94                         entities.Add ("middot", '\u00B7');
95                         entities.Add ("cedil", '\u00B8');
96                         entities.Add ("sup1", '\u00B9');
97                         entities.Add ("ordm", '\u00BA');
98                         entities.Add ("raquo", '\u00BB');
99                         entities.Add ("frac14", '\u00BC');
100                         entities.Add ("frac12", '\u00BD');
101                         entities.Add ("frac34", '\u00BE');
102                         entities.Add ("iquest", '\u00BF');
103                         entities.Add ("Agrave", '\u00C0');
104                         entities.Add ("Aacute", '\u00C1');
105                         entities.Add ("Acirc", '\u00C2');
106                         entities.Add ("Atilde", '\u00C3');
107                         entities.Add ("Auml", '\u00C4');
108                         entities.Add ("Aring", '\u00C5');
109                         entities.Add ("AElig", '\u00C6');
110                         entities.Add ("Ccedil", '\u00C7');
111                         entities.Add ("Egrave", '\u00C8');
112                         entities.Add ("Eacute", '\u00C9');
113                         entities.Add ("Ecirc", '\u00CA');
114                         entities.Add ("Euml", '\u00CB');
115                         entities.Add ("Igrave", '\u00CC');
116                         entities.Add ("Iacute", '\u00CD');
117                         entities.Add ("Icirc", '\u00CE');
118                         entities.Add ("Iuml", '\u00CF');
119                         entities.Add ("ETH", '\u00D0');
120                         entities.Add ("Ntilde", '\u00D1');
121                         entities.Add ("Ograve", '\u00D2');
122                         entities.Add ("Oacute", '\u00D3');
123                         entities.Add ("Ocirc", '\u00D4');
124                         entities.Add ("Otilde", '\u00D5');
125                         entities.Add ("Ouml", '\u00D6');
126                         entities.Add ("times", '\u00D7');
127                         entities.Add ("Oslash", '\u00D8');
128                         entities.Add ("Ugrave", '\u00D9');
129                         entities.Add ("Uacute", '\u00DA');
130                         entities.Add ("Ucirc", '\u00DB');
131                         entities.Add ("Uuml", '\u00DC');
132                         entities.Add ("Yacute", '\u00DD');
133                         entities.Add ("THORN", '\u00DE');
134                         entities.Add ("szlig", '\u00DF');
135                         entities.Add ("agrave", '\u00E0');
136                         entities.Add ("aacute", '\u00E1');
137                         entities.Add ("acirc", '\u00E2');
138                         entities.Add ("atilde", '\u00E3');
139                         entities.Add ("auml", '\u00E4');
140                         entities.Add ("aring", '\u00E5');
141                         entities.Add ("aelig", '\u00E6');
142                         entities.Add ("ccedil", '\u00E7');
143                         entities.Add ("egrave", '\u00E8');
144                         entities.Add ("eacute", '\u00E9');
145                         entities.Add ("ecirc", '\u00EA');
146                         entities.Add ("euml", '\u00EB');
147                         entities.Add ("igrave", '\u00EC');
148                         entities.Add ("iacute", '\u00ED');
149                         entities.Add ("icirc", '\u00EE');
150                         entities.Add ("iuml", '\u00EF');
151                         entities.Add ("eth", '\u00F0');
152                         entities.Add ("ntilde", '\u00F1');
153                         entities.Add ("ograve", '\u00F2');
154                         entities.Add ("oacute", '\u00F3');
155                         entities.Add ("ocirc", '\u00F4');
156                         entities.Add ("otilde", '\u00F5');
157                         entities.Add ("ouml", '\u00F6');
158                         entities.Add ("divide", '\u00F7');
159                         entities.Add ("oslash", '\u00F8');
160                         entities.Add ("ugrave", '\u00F9');
161                         entities.Add ("uacute", '\u00FA');
162                         entities.Add ("ucirc", '\u00FB');
163                         entities.Add ("uuml", '\u00FC');
164                         entities.Add ("yacute", '\u00FD');
165                         entities.Add ("thorn", '\u00FE');
166                         entities.Add ("yuml", '\u00FF');
167                         entities.Add ("fnof", '\u0192');
168                         entities.Add ("Alpha", '\u0391');
169                         entities.Add ("Beta", '\u0392');
170                         entities.Add ("Gamma", '\u0393');
171                         entities.Add ("Delta", '\u0394');
172                         entities.Add ("Epsilon", '\u0395');
173                         entities.Add ("Zeta", '\u0396');
174                         entities.Add ("Eta", '\u0397');
175                         entities.Add ("Theta", '\u0398');
176                         entities.Add ("Iota", '\u0399');
177                         entities.Add ("Kappa", '\u039A');
178                         entities.Add ("Lambda", '\u039B');
179                         entities.Add ("Mu", '\u039C');
180                         entities.Add ("Nu", '\u039D');
181                         entities.Add ("Xi", '\u039E');
182                         entities.Add ("Omicron", '\u039F');
183                         entities.Add ("Pi", '\u03A0');
184                         entities.Add ("Rho", '\u03A1');
185                         entities.Add ("Sigma", '\u03A3');
186                         entities.Add ("Tau", '\u03A4');
187                         entities.Add ("Upsilon", '\u03A5');
188                         entities.Add ("Phi", '\u03A6');
189                         entities.Add ("Chi", '\u03A7');
190                         entities.Add ("Psi", '\u03A8');
191                         entities.Add ("Omega", '\u03A9');
192                         entities.Add ("alpha", '\u03B1');
193                         entities.Add ("beta", '\u03B2');
194                         entities.Add ("gamma", '\u03B3');
195                         entities.Add ("delta", '\u03B4');
196                         entities.Add ("epsilon", '\u03B5');
197                         entities.Add ("zeta", '\u03B6');
198                         entities.Add ("eta", '\u03B7');
199                         entities.Add ("theta", '\u03B8');
200                         entities.Add ("iota", '\u03B9');
201                         entities.Add ("kappa", '\u03BA');
202                         entities.Add ("lambda", '\u03BB');
203                         entities.Add ("mu", '\u03BC');
204                         entities.Add ("nu", '\u03BD');
205                         entities.Add ("xi", '\u03BE');
206                         entities.Add ("omicron", '\u03BF');
207                         entities.Add ("pi", '\u03C0');
208                         entities.Add ("rho", '\u03C1');
209                         entities.Add ("sigmaf", '\u03C2');
210                         entities.Add ("sigma", '\u03C3');
211                         entities.Add ("tau", '\u03C4');
212                         entities.Add ("upsilon", '\u03C5');
213                         entities.Add ("phi", '\u03C6');
214                         entities.Add ("chi", '\u03C7');
215                         entities.Add ("psi", '\u03C8');
216                         entities.Add ("omega", '\u03C9');
217                         entities.Add ("thetasym", '\u03D1');
218                         entities.Add ("upsih", '\u03D2');
219                         entities.Add ("piv", '\u03D6');
220                         entities.Add ("bull", '\u2022');
221                         entities.Add ("hellip", '\u2026');
222                         entities.Add ("prime", '\u2032');
223                         entities.Add ("Prime", '\u2033');
224                         entities.Add ("oline", '\u203E');
225                         entities.Add ("frasl", '\u2044');
226                         entities.Add ("weierp", '\u2118');
227                         entities.Add ("image", '\u2111');
228                         entities.Add ("real", '\u211C');
229                         entities.Add ("trade", '\u2122');
230                         entities.Add ("alefsym", '\u2135');
231                         entities.Add ("larr", '\u2190');
232                         entities.Add ("uarr", '\u2191');
233                         entities.Add ("rarr", '\u2192');
234                         entities.Add ("darr", '\u2193');
235                         entities.Add ("harr", '\u2194');
236                         entities.Add ("crarr", '\u21B5');
237                         entities.Add ("lArr", '\u21D0');
238                         entities.Add ("uArr", '\u21D1');
239                         entities.Add ("rArr", '\u21D2');
240                         entities.Add ("dArr", '\u21D3');
241                         entities.Add ("hArr", '\u21D4');
242                         entities.Add ("forall", '\u2200');
243                         entities.Add ("part", '\u2202');
244                         entities.Add ("exist", '\u2203');
245                         entities.Add ("empty", '\u2205');
246                         entities.Add ("nabla", '\u2207');
247                         entities.Add ("isin", '\u2208');
248                         entities.Add ("notin", '\u2209');
249                         entities.Add ("ni", '\u220B');
250                         entities.Add ("prod", '\u220F');
251                         entities.Add ("sum", '\u2211');
252                         entities.Add ("minus", '\u2212');
253                         entities.Add ("lowast", '\u2217');
254                         entities.Add ("radic", '\u221A');
255                         entities.Add ("prop", '\u221D');
256                         entities.Add ("infin", '\u221E');
257                         entities.Add ("ang", '\u2220');
258                         entities.Add ("and", '\u2227');
259                         entities.Add ("or", '\u2228');
260                         entities.Add ("cap", '\u2229');
261                         entities.Add ("cup", '\u222A');
262                         entities.Add ("int", '\u222B');
263                         entities.Add ("there4", '\u2234');
264                         entities.Add ("sim", '\u223C');
265                         entities.Add ("cong", '\u2245');
266                         entities.Add ("asymp", '\u2248');
267                         entities.Add ("ne", '\u2260');
268                         entities.Add ("equiv", '\u2261');
269                         entities.Add ("le", '\u2264');
270                         entities.Add ("ge", '\u2265');
271                         entities.Add ("sub", '\u2282');
272                         entities.Add ("sup", '\u2283');
273                         entities.Add ("nsub", '\u2284');
274                         entities.Add ("sube", '\u2286');
275                         entities.Add ("supe", '\u2287');
276                         entities.Add ("oplus", '\u2295');
277                         entities.Add ("otimes", '\u2297');
278                         entities.Add ("perp", '\u22A5');
279                         entities.Add ("sdot", '\u22C5');
280                         entities.Add ("lceil", '\u2308');
281                         entities.Add ("rceil", '\u2309');
282                         entities.Add ("lfloor", '\u230A');
283                         entities.Add ("rfloor", '\u230B');
284                         entities.Add ("lang", '\u2329');
285                         entities.Add ("rang", '\u232A');
286                         entities.Add ("loz", '\u25CA');
287                         entities.Add ("spades", '\u2660');
288                         entities.Add ("clubs", '\u2663');
289                         entities.Add ("hearts", '\u2665');
290                         entities.Add ("diams", '\u2666');
291                         entities.Add ("quot", '\u0022');
292                         entities.Add ("amp", '\u0026');
293                         entities.Add ("lt", '\u003C');
294                         entities.Add ("gt", '\u003E');
295                         entities.Add ("OElig", '\u0152');
296                         entities.Add ("oelig", '\u0153');
297                         entities.Add ("Scaron", '\u0160');
298                         entities.Add ("scaron", '\u0161');
299                         entities.Add ("Yuml", '\u0178');
300                         entities.Add ("circ", '\u02C6');
301                         entities.Add ("tilde", '\u02DC');
302                         entities.Add ("ensp", '\u2002');
303                         entities.Add ("emsp", '\u2003');
304                         entities.Add ("thinsp", '\u2009');
305                         entities.Add ("zwnj", '\u200C');
306                         entities.Add ("zwj", '\u200D');
307                         entities.Add ("lrm", '\u200E');
308                         entities.Add ("rlm", '\u200F');
309                         entities.Add ("ndash", '\u2013');
310                         entities.Add ("mdash", '\u2014');
311                         entities.Add ("lsquo", '\u2018');
312                         entities.Add ("rsquo", '\u2019');
313                         entities.Add ("sbquo", '\u201A');
314                         entities.Add ("ldquo", '\u201C');
315                         entities.Add ("rdquo", '\u201D');
316                         entities.Add ("bdquo", '\u201E');
317                         entities.Add ("dagger", '\u2020');
318                         entities.Add ("Dagger", '\u2021');
319                         entities.Add ("permil", '\u2030');
320                         entities.Add ("lsaquo", '\u2039');
321                         entities.Add ("rsaquo", '\u203A');
322                         entities.Add ("euro", '\u20AC');
323                 }
324
325                 public HttpUtility () 
326                 {
327                 }
328         
329                 #endregion // Constructors
330         
331                 #region Methods
332         
333                 public static void HtmlAttributeEncode (string s, TextWriter output) 
334                 {
335                         output.Write(HtmlAttributeEncode(s));
336                 }
337         
338                 public static string HtmlAttributeEncode (string s) 
339                 {
340                         if (null == s) 
341                                 return null;
342         
343                         if (s.IndexOf ('&') == -1 && s.IndexOf ('"') == -1)
344                                 return s;
345
346                         StringBuilder output = new StringBuilder ();
347                         foreach (char c in s) 
348                                 switch (c) {
349                                 case '&' : 
350                                         output.Append ("&");
351                                         break;
352                                 case '"' :
353                                         output.Append (""");
354                                         break;
355                                 default:
356                                         output.Append (c);
357                                         break;
358                                 }
359         
360                         return output.ToString();
361                 }
362         
363                 public static string UrlDecode (string str) 
364                 {
365                         return UrlDecode(str, Encoding.UTF8);
366                 }
367         
368                 private static char [] GetChars (MemoryStream b, Encoding e)
369                 {
370                         return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
371                 }
372
373                 public static string UrlDecode (string s, Encoding e)
374                 {
375                         if (null == s) 
376                                 return null;
377
378                         if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
379                                 return s;
380
381                         if (e == null)
382                                 e = Encoding.UTF8;
383         
384                         StringBuilder output = new StringBuilder ();
385                         long len = s.Length;
386                         MemoryStream bytes = new MemoryStream ();
387                         int xchar;
388         
389                         for (int i = 0; i < len; i++) {
390                                 if (s [i] == '%' && i + 2 < len && s [i + 1] != '%') {
391                                         if (s [i + 1] == 'u' && i + 5 < len) {
392                                                 if (bytes.Length > 0) {
393                                                         output.Append (GetChars (bytes, e));
394                                                         bytes.SetLength (0);
395                                                 }
396
397                                                 xchar = GetChar (s, i + 2, 4);
398                                                 if (xchar != -1) {
399                                                         output.Append ((char) xchar);
400                                                         i += 5;
401                                                 } else {
402                                                         output.Append ('%');
403                                                 }
404                                         } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
405                                                 bytes.WriteByte ((byte) xchar);
406                                                 i += 2;
407                                         } else {
408                                                 output.Append ('%');
409                                         }
410                                         continue;
411                                 }
412
413                                 if (bytes.Length > 0) {
414                                         output.Append (GetChars (bytes, e));
415                                         bytes.SetLength (0);
416                                 }
417
418                                 if (s [i] == '+') {
419                                         output.Append (' ');
420                                 } else {
421                                         output.Append (s [i]);
422                                 }
423                         }
424         
425                         if (bytes.Length > 0) {
426                                 output.Append (GetChars (bytes, e));
427                         }
428
429                         bytes = null;
430                         return output.ToString ();
431                 }
432         
433                 public static string UrlDecode (byte [] bytes, Encoding e)
434                 {
435                         if (bytes == null)
436                                 return null;
437
438                         return UrlDecode (bytes, 0, bytes.Length, e);
439                 }
440
441                 private static int GetInt (byte b)
442                 {
443                         char c = (char) b;
444                         if (c >= '0' && c <= '9')
445                                 return c - '0';
446
447                         if (c >= 'a' && c <= 'f')
448                                 return c - 'a' + 10;
449
450                         if (c >= 'A' && c <= 'F')
451                                 return c - 'A' + 10;
452
453                         return -1;
454                 }
455
456                 private static int GetChar (byte [] bytes, int offset, int length)
457                 {
458                         int value = 0;
459                         int end = length + offset;
460                         for (int i = offset; i < end; i++) {
461                                 int current = GetInt (bytes [i]);
462                                 if (current == -1)
463                                         return -1;
464                                 value = (value << 4) + current;
465                         }
466
467                         return value;
468                 }
469
470                 private static int GetChar (string str, int offset, int length)
471                 {
472                         int val = 0;
473                         int end = length + offset;
474                         for (int i = offset; i < end; i++) {
475                                 char c = str [i];
476                                 if (c > 127)
477                                         return -1;
478
479                                 int current = GetInt ((byte) c);
480                                 if (current == -1)
481                                         return -1;
482                                 val = (val << 4) + current;
483                         }
484
485                         return val;
486                 }
487                 
488                 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
489                 {
490                         if (bytes == null)
491                                 return null;
492                         if (count == 0)
493                                 return String.Empty;
494
495                         if (bytes == null)
496                                 throw new ArgumentNullException ("bytes");
497
498                         if (offset < 0 || offset > bytes.Length)
499                                 throw new ArgumentOutOfRangeException ("offset");
500
501                         if (count < 0 || offset + count > bytes.Length)
502                                 throw new ArgumentOutOfRangeException ("count");
503
504                         StringBuilder output = new StringBuilder ();
505                         MemoryStream acc = new MemoryStream ();
506
507                         int end = count + offset;
508                         int xchar;
509                         for (int i = offset; i < end; i++) {
510                                 if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
511                                         if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
512                                                 if (acc.Length > 0) {
513                                                         output.Append (GetChars (acc, e));
514                                                         acc.SetLength (0);
515                                                 }
516                                                 xchar = GetChar (bytes, i + 2, 4);
517                                                 if (xchar != -1) {
518                                                         output.Append ((char) xchar);
519                                                         i += 5;
520                                                         continue;
521                                                 }
522                                         } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
523                                                 acc.WriteByte ((byte) xchar);
524                                                 i += 2;
525                                                 continue;
526                                         }
527                                 }
528
529                                 if (acc.Length > 0) {
530                                         output.Append (GetChars (acc, e));
531                                         acc.SetLength (0);
532                                 }
533
534                                 if (bytes [i] == '+') {
535                                         output.Append (' ');
536                                 } else {
537                                         output.Append ((char) bytes [i]);
538                                 }
539                         }
540
541                         if (acc.Length > 0) {
542                                 output.Append (GetChars (acc, e));
543                         }
544                         
545                         acc = null;
546                         return output.ToString ();
547                 }
548         
549                 public static byte [] UrlDecodeToBytes (byte [] bytes)
550                 {
551                         if (bytes == null)
552                                 return null;
553
554                         return UrlDecodeToBytes (bytes, 0, bytes.Length);
555                 }
556
557                 public static byte [] UrlDecodeToBytes (string str)
558                 {
559                         return UrlDecodeToBytes (str, Encoding.UTF8);
560                 }
561
562                 public static byte [] UrlDecodeToBytes (string str, Encoding e)
563                 {
564                         if (str == null)
565                                 return null;
566
567                         if (e == null)
568                                 throw new ArgumentNullException ("e");
569
570                         return UrlDecodeToBytes (e.GetBytes (str));
571                 }
572
573                 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
574                 {
575                         if (bytes == null)
576                                 return null;
577                         if (count == 0)
578                                 return new byte [0];
579
580                         int len = bytes.Length;
581                         if (offset < 0 || offset >= len)
582                                 throw new ArgumentOutOfRangeException("offset");
583
584                         if (count < 0 || offset > len - count)
585                                 throw new ArgumentOutOfRangeException("count");
586
587                         MemoryStream result = new MemoryStream ();
588                         int end = offset + count;
589                         for (int i = offset; i < end; i++){
590                                 char c = (char) bytes [i];
591                                 if (c == '+') {
592                                         c = ' ';
593                                 } else if (c == '%' && i < end - 2) {
594                                         int xchar = GetChar (bytes, i + 1, 2);
595                                         if (xchar != -1) {
596                                                 c = (char) xchar;
597                                                 i += 2;
598                                         }
599                                 }
600                                 result.WriteByte ((byte) c);
601                         }
602
603                         return result.ToArray ();
604                 }
605
606                 public static string UrlEncode(string str) 
607                 {
608                         return UrlEncode(str, Encoding.UTF8);
609                 }
610         
611                 public static string UrlEncode (string s, Encoding Enc) 
612                 {
613                         if (s == null)
614                                 return null;
615
616                         if (s == "")
617                                 return "";
618
619                         byte [] bytes = Enc.GetBytes (s);
620                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
621                 }
622           
623                 public static string UrlEncode (byte [] bytes)
624                 {
625                         if (bytes == null)
626                                 return null;
627
628                         if (bytes.Length == 0)
629                                 return "";
630
631                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
632                 }
633
634                 public static string UrlEncode (byte [] bytes, int offset, int count)
635                 {
636                         if (bytes == null)
637                                 return null;
638
639                         if (bytes.Length == 0)
640                                 return "";
641
642                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
643                 }
644
645                 public static byte [] UrlEncodeToBytes (string str)
646                 {
647                         return UrlEncodeToBytes (str, Encoding.UTF8);
648                 }
649
650                 public static byte [] UrlEncodeToBytes (string str, Encoding e)
651                 {
652                         if (str == null)
653                                 return null;
654
655                         if (str == "")
656                                 return new byte [0];
657
658                         byte [] bytes = e.GetBytes (str);
659                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
660                 }
661
662                 public static byte [] UrlEncodeToBytes (byte [] bytes)
663                 {
664                         if (bytes == null)
665                                 return null;
666
667                         if (bytes.Length == 0)
668                                 return new byte [0];
669
670                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
671                 }
672
673                 static char [] hexChars = "0123456789abcdef".ToCharArray ();
674                 const string notEncoded = "!'()*-._";
675
676                 static void UrlEncodeChar (char c, Stream result, bool isUnicode) {
677                         if (c > 255) {
678                                 //FIXME: what happens when there is an internal error?
679                                 //if (!isUnicode)
680                                 //      throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256");
681                                 int idx;
682                                 int i = (int) c;
683
684                                 result.WriteByte ((byte)'%');
685                                 result.WriteByte ((byte)'u');
686                                 idx = i >> 12;
687                                 result.WriteByte ((byte)hexChars [idx]);
688                                 idx = (i >> 8) & 0x0F;
689                                 result.WriteByte ((byte)hexChars [idx]);
690                                 idx = (i >> 4) & 0x0F;
691                                 result.WriteByte ((byte)hexChars [idx]);
692                                 idx = i & 0x0F;
693                                 result.WriteByte ((byte)hexChars [idx]);
694                                 return;
695                         }
696                         
697                         if (c>' ' && notEncoded.IndexOf (c)!=-1) {
698                                 result.WriteByte ((byte)c);
699                                 return;
700                         }
701                         if (c==' ') {
702                                 result.WriteByte ((byte)'+');
703                                 return;
704                         }
705                         if (    (c < '0') ||
706                                 (c < 'A' && c > '9') ||
707                                 (c > 'Z' && c < 'a') ||
708                                 (c > 'z')) {
709                                 if (isUnicode && c > 127) {
710                                         result.WriteByte ((byte)'%');
711                                         result.WriteByte ((byte)'u');
712                                         result.WriteByte ((byte)'0');
713                                         result.WriteByte ((byte)'0');
714                                 }
715                                 else
716                                         result.WriteByte ((byte)'%');
717                                 
718                                 int idx = ((int) c) >> 4;
719                                 result.WriteByte ((byte)hexChars [idx]);
720                                 idx = ((int) c) & 0x0F;
721                                 result.WriteByte ((byte)hexChars [idx]);
722                         }
723                         else
724                                 result.WriteByte ((byte)c);
725                 }
726
727                 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
728                 {
729                         if (bytes == null)
730                                 return null;
731
732                         int len = bytes.Length;
733                         if (len == 0)
734                                 return new byte [0];
735
736                         if (offset < 0 || offset >= len)
737                                 throw new ArgumentOutOfRangeException("offset");
738
739                         if (count < 0 || count > len - offset)
740                                 throw new ArgumentOutOfRangeException("count");
741
742                         MemoryStream result = new MemoryStream (count);
743                         int end = offset + count;
744                         for (int i = offset; i < end; i++)
745                                 UrlEncodeChar ((char)bytes [i], result, false);
746
747                         return result.ToArray();
748                 }
749
750                 public static string UrlEncodeUnicode (string str)
751                 {
752                         if (str == null)
753                                 return null;
754
755                         return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
756                 }
757
758                 public static byte [] UrlEncodeUnicodeToBytes (string str)
759                 {
760                         if (str == null)
761                                 return null;
762
763                         if (str == "")
764                                 return new byte [0];
765
766                         MemoryStream result = new MemoryStream (str.Length);
767                         foreach (char c in str){
768                                 UrlEncodeChar (c, result, true);
769                         }
770                         return result.ToArray ();
771                 }
772
773                 /// <summary>
774                 /// Decodes an HTML-encoded string and returns the decoded string.
775                 /// </summary>
776                 /// <param name="s">The HTML string to decode. </param>
777                 /// <returns>The decoded text.</returns>
778                 public static string HtmlDecode (string s) 
779                 {
780                         if (s == null)
781                                 throw new ArgumentNullException ("s");
782
783                         if (s.IndexOf ('&') == -1)
784                                 return s;
785
786                         StringBuilder entity = new StringBuilder ();
787                         StringBuilder output = new StringBuilder ();
788                         int len = s.Length;
789                         // 0 -> nothing,
790                         // 1 -> right after '&'
791                         // 2 -> between '&' and ';' but no '#'
792                         // 3 -> '#' found after '&' and getting numbers
793                         int state = 0;
794                         int number = 0;
795                         bool have_trailing_digits = false;
796         
797                         for (int i = 0; i < len; i++) {
798                                 char c = s [i];
799                                 if (state == 0) {
800                                         if (c == '&') {
801                                                 entity.Append (c);
802                                                 state = 1;
803                                         } else {
804                                                 output.Append (c);
805                                         }
806                                         continue;
807                                 }
808
809                                 if (c == '&') {
810                                         state = 1;
811                                         if (have_trailing_digits) {
812                                                 entity.Append (number.ToString (CultureInfo.InvariantCulture));
813                                                 have_trailing_digits = false;
814                                         }
815
816                                         output.Append (entity.ToString ());
817                                         entity.Length = 0;
818                                         entity.Append ('&');
819                                         continue;
820                                 }
821
822                                 if (state == 1) {
823                                         if (c == ';') {
824                                                 state = 0;
825                                                 output.Append (entity.ToString ());
826                                                 output.Append (c);
827                                                 entity.Length = 0;
828                                         } else {
829                                                 number = 0;
830                                                 if (c != '#') {
831                                                         state = 2;
832                                                 } else {
833                                                         state = 3;
834                                                 }
835                                                 entity.Append (c);
836                                         }
837                                 } else if (state == 2) {
838                                         entity.Append (c);
839                                         if (c == ';') {
840                                                 string key = entity.ToString ();
841                                                 if (key.Length > 1 && Entities.ContainsKey (key.Substring (1, key.Length - 2)))
842                                                         key = Entities [key.Substring (1, key.Length - 2)].ToString ();
843
844                                                 output.Append (key);
845                                                 state = 0;
846                                                 entity.Length = 0;
847                                         }
848                                 } else if (state == 3) {
849                                         if (c == ';') {
850                                                 if (number > 65535) {
851                                                         output.Append ("&#");
852                                                         output.Append (number.ToString (CultureInfo.InvariantCulture));
853                                                         output.Append (";");
854                                                 } else {
855                                                         output.Append ((char) number);
856                                                 }
857                                                 state = 0;
858                                                 entity.Length = 0;
859                                                 have_trailing_digits = false;
860                                         } else if (Char.IsDigit (c)) {
861                                                 number = number * 10 + ((int) c - '0');
862                                                 have_trailing_digits = true;
863                                         } else {
864                                                 state = 2;
865                                                 if (have_trailing_digits) {
866                                                         entity.Append (number.ToString (CultureInfo.InvariantCulture));
867                                                         have_trailing_digits = false;
868                                                 }
869                                                 entity.Append (c);
870                                         }
871                                 }
872                         }
873
874                         if (entity.Length > 0) {
875                                 output.Append (entity.ToString ());
876                         } else if (have_trailing_digits) {
877                                 output.Append (number.ToString (CultureInfo.InvariantCulture));
878                         }
879                         return output.ToString ();
880                 }
881         
882                 /// <summary>
883                 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
884                 /// </summary>
885                 /// <param name="s">The HTML string to decode</param>
886                 /// <param name="output">The TextWriter output stream containing the decoded string. </param>
887                 public static void HtmlDecode(string s, TextWriter output) 
888                 {
889                         if (s != null)
890                                 output.Write (HtmlDecode (s));
891                 }
892         
893                 /// <summary>
894                 /// HTML-encodes a string and returns the encoded string.
895                 /// </summary>
896                 /// <param name="s">The text string to encode. </param>
897                 /// <returns>The HTML-encoded text.</returns>
898                 public static string HtmlEncode (string s) 
899                 {
900                         if (s == null)
901                                 return null;
902
903                         StringBuilder output = new StringBuilder ();
904                         
905                         foreach (char c in s) 
906                                 switch (c) {
907                                 case '&' :
908                                         output.Append ("&amp;");
909                                         break;
910                                 case '>' : 
911                                         output.Append ("&gt;");
912                                         break;
913                                 case '<' :
914                                         output.Append ("&lt;");
915                                         break;
916                                 case '"' :
917                                         output.Append ("&quot;");
918                                         break;
919                                 default:
920                                         // MS starts encoding with &# from 160 and stops at 255.
921                                         // We don't do that. One reason is the 65308/65310 unicode
922                                         // characters that look like '<' and '>'.
923                                         if (c > 159) {
924                                                 output.Append ("&#");
925                                                 output.Append (((int) c).ToString (CultureInfo.InvariantCulture));
926                                                 output.Append (";");
927                                         } else {
928                                                 output.Append (c);
929                                         }
930                                         break;
931                                 }
932                         return output.ToString ();
933                 }
934         
935                 /// <summary>
936                 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
937                 /// </summary>
938                 /// <param name="s">The string to encode. </param>
939                 /// <param name="output">The TextWriter output stream containing the encoded string. </param>
940                 public static void HtmlEncode(string s, TextWriter output) 
941                 {
942                         if (s != null)
943                                 output.Write (HtmlEncode (s));
944                 }
945
946 #if NET_1_1
947                 public static string UrlPathEncode (string s)
948                 {
949                         if (s == null || s.Length == 0)
950                                 return s;
951
952                         MemoryStream result = new MemoryStream ();
953                         int length = s.Length;
954             for (int i = 0; i < length; i++) {
955                                 UrlPathEncodeChar (s [i], result);
956                         }
957                         return Encoding.ASCII.GetString (result.ToArray ());
958                 }
959                 
960                 static void UrlPathEncodeChar (char c, Stream result) {
961                         if (c > 127) {
962                                 byte [] bIn = Encoding.UTF8.GetBytes (c.ToString ());
963                                 for (int i = 0; i < bIn.Length; i++) {
964                                         result.WriteByte ((byte) '%');
965                                         int idx = ((int) bIn [i]) >> 4;
966                                         result.WriteByte ((byte) hexChars [idx]);
967                                         idx = ((int) bIn [i]) & 0x0F;
968                                         result.WriteByte ((byte) hexChars [idx]);
969                                 }
970                         }
971                         else if (c == ' ') {
972                                 result.WriteByte ((byte) '%');
973                                 result.WriteByte ((byte) '2');
974                                 result.WriteByte ((byte) '0');
975                         }
976                         else
977                                 result.WriteByte ((byte) c);
978                 }
979 #endif
980
981 #if NET_2_0
982                 public static NameValueCollection ParseQueryString (string query)
983                 {
984                         return ParseQueryString (query, Encoding.UTF8);
985                 }
986
987                 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
988                 {
989                         if (query == null)
990                                 throw new ArgumentNullException ("query");
991                         if (encoding == null)
992                                 throw new ArgumentNullException ("encoding");
993                         if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
994                                 return new NameValueCollection ();
995                         if (query[0] == '?')
996                                 query = query.Substring (1);
997                                 
998                         NameValueCollection result = new NameValueCollection ();
999                         ParseQueryString (query, encoding, result);
1000                         return result;
1001                 }                               
1002 #endif
1003
1004                 internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
1005                 {
1006                         if (query.Length == 0)
1007                                 return;
1008
1009                         int namePos = 0;
1010                         while (namePos <= query.Length) {
1011                                 int valuePos = -1, valueEnd = -1;
1012                                 for (int q = namePos; q < query.Length; q++) {
1013                                         if (valuePos == -1 && query[q] == '=') {
1014                                                 valuePos = q + 1;
1015                                         } else if (query[q] == '&') {
1016                                                 valueEnd = q;
1017                                                 break;
1018                                         }
1019                                 }
1020
1021                                 string name, value;
1022                                 if (valuePos == -1) {
1023                                         name = null;
1024                                         valuePos = namePos;
1025                                 } else {
1026                                         name = UrlDecode (query.Substring (namePos, valuePos - namePos - 1), encoding);
1027                                 }
1028                                 if (valueEnd < 0) {
1029                                         namePos = -1;
1030                                         valueEnd = query.Length;
1031                                 } else {
1032                                         namePos = valueEnd + 1;
1033                                 }
1034                                 value = UrlDecode (query.Substring (valuePos, valueEnd - valuePos), encoding);
1035
1036                                 result.Add (name, value);
1037                                 if (namePos == -1) break;
1038                         }
1039                 }
1040                 #endregion // Methods
1041         }
1042 }
1043