2009-04-14 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / class / System.Runtime.Serialization / System.Xml / XmlBinaryDictionaryWriter.cs
1 //
2 // XmlBinaryDictionaryWriter.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2005, 2007 Novell, Inc.  http://www.novell.com
8 //
9
10 //
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:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
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.
29 //
30 using System;
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Collections.Generic;
34 using System.Globalization;
35 using System.IO;
36 using System.Linq;
37 using System.Text;
38
39 using BF = System.Xml.XmlBinaryFormat;
40
41 namespace System.Xml
42 {
43         internal partial class XmlBinaryDictionaryWriter : XmlDictionaryWriter
44         {
45                 class MyBinaryWriter : BinaryWriter
46                 {
47                         public MyBinaryWriter (Stream s)
48                                 : base (s)
49                         {
50                         }
51
52                         public void WriteFlexibleInt (int value)
53                         {
54                                 Write7BitEncodedInt (value);
55                         }
56                 }
57
58                 #region Fields
59                 MyBinaryWriter original, writer, buffer_writer;
60                 IXmlDictionary dict_ext;
61                 XmlDictionary dict_int = new XmlDictionary ();
62                 XmlBinaryWriterSession session;
63                 bool owns_stream;
64                 Encoding utf8Enc = new UTF8Encoding ();
65                 MemoryStream buffer = new MemoryStream ();
66
67                 const string XmlNamespace = "http://www.w3.org/XML/1998/namespace";
68                 const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
69
70                 WriteState state = WriteState.Start;
71                 bool open_start_element = false;
72                 // transient current node info
73                 List<KeyValuePair<string,object>> namespaces = new List<KeyValuePair<string,object>> ();
74                 string xml_lang = null;
75                 XmlSpace xml_space = XmlSpace.None;
76                 int ns_index = 0;
77                 // stacked info
78                 Stack<int> ns_index_stack = new Stack<int> ();
79                 Stack<string> xml_lang_stack = new Stack<string> ();
80                 Stack<XmlSpace> xml_space_stack = new Stack<XmlSpace> ();
81                 Stack<string> element_ns_stack = new Stack<string> ();
82                 string element_ns = String.Empty;
83                 int element_count;
84                 string element_prefix; // only meaningful at Element state
85                 // current attribute info
86                 string attr_value;
87                 string current_attr_prefix;
88                 object current_attr_name, current_attr_ns;
89                 bool attr_typed_value;
90                 SaveTarget save_target;
91
92                 enum SaveTarget {
93                         None,
94                         Namespaces,
95                         XmlLang,
96                         XmlSpace
97                 }
98
99                 // XmlWriterSettings support
100
101                 #endregion
102
103                 #region Constructors
104
105                 public XmlBinaryDictionaryWriter (Stream stream,
106                         IXmlDictionary dictionary,
107                         XmlBinaryWriterSession session, bool ownsStream)
108                 {
109                         if (dictionary == null)
110                                 dictionary = new XmlDictionary ();
111                         if (session == null)
112                                 session = new XmlBinaryWriterSession ();
113
114                         original = new MyBinaryWriter (stream);
115                         this.writer = original;
116                         buffer_writer = new MyBinaryWriter (buffer);
117                         this.dict_ext = dictionary;
118                         this.session = session;
119                         owns_stream = ownsStream;
120
121                         AddNamespace ("xml", "http://www.w3.org/XML/1998/namespace");
122                         AddNamespace ("xml", "http://www.w3.org/2000/xmlns/");
123                         ns_index = 2;
124                 }
125
126                 #endregion
127
128                 #region Properties
129
130                 public override WriteState WriteState {
131                         get { return state; }
132                 }
133                 
134                 public override string XmlLang {
135                         get { return xml_lang; }
136                 }
137
138                 public override XmlSpace XmlSpace {
139                         get { return xml_space; }
140                 }
141
142                 #endregion
143
144                 #region Methods
145
146                 private void AddMissingElementXmlns ()
147                 {
148                         // push new namespaces to manager.
149                         for (int i = ns_index; i < namespaces.Count; i++) {
150                                 var ent = namespaces [i];
151                                 string prefix = (string) ent.Key;
152                                 string ns = ent.Value as string;
153                                 XmlDictionaryString dns = ent.Value as XmlDictionaryString;
154                                 if (ns != null) {
155                                         if (prefix.Length > 0) {
156                                                 writer.Write (BF.PrefixNSString);
157                                                 writer.Write (prefix);
158                                         }
159                                         else
160                                                 writer.Write (BF.DefaultNSString);
161                                         writer.Write (ns);
162                                 } else {
163                                         if (prefix.Length > 0) {
164                                                 writer.Write (BF.PrefixNSIndex);
165                                                 writer.Write (prefix);
166                                         }
167                                         else
168                                                 writer.Write (BF.DefaultNSIndex);
169                                         WriteDictionaryIndex (dns);
170                                 }
171                         }
172                         ns_index = namespaces.Count;
173                 }
174
175                 private void CheckState ()
176                 {
177                         if (state == WriteState.Closed) {
178                                 throw new InvalidOperationException ("The Writer is closed.");
179                         }
180                 }
181
182                 void ProcessStateForContent ()
183                 {
184                         CheckState ();
185
186                         if (state == WriteState.Element)
187                                 CloseStartElement ();
188
189                         ProcessPendingBuffer (false, false);
190                         if (state != WriteState.Attribute)
191                                 writer = buffer_writer;
192                 }
193
194                 void ProcessTypedValue ()
195                 {
196                         ProcessStateForContent ();
197                         if (state == WriteState.Attribute) {
198                                 if (attr_typed_value)
199                                         throw new InvalidOperationException (String.Format ("A typed value for the attribute '{0}' in namespace '{1}' was already written", current_attr_name, current_attr_ns));
200                                 attr_typed_value = true;
201                         }
202                 }
203
204                 void ProcessPendingBuffer (bool last, bool endElement)
205                 {
206                         if (buffer.Position > 0) {
207                                 byte [] arr = buffer.GetBuffer ();
208                                 if (endElement)
209                                         arr [0]++;
210                                 original.Write (arr, 0, (int) buffer.Position);
211                                 buffer.SetLength (0);
212                         }
213                         if (last)
214                                 writer = original;
215                 }
216
217                 public override void Close ()
218                 {
219                         CloseOpenAttributeAndElements ();
220
221                         if (owns_stream)
222                                 writer.Close ();
223                         else if (state != WriteState.Closed)
224                                 writer.Flush ();
225                         state = WriteState.Closed;
226                 }
227
228                 private void CloseOpenAttributeAndElements ()
229                 {
230                         CloseStartElement ();
231
232                          while (element_count > 0)
233                                 WriteEndElement ();
234                 }
235
236                 private void CloseStartElement ()
237                 {
238                         if (!open_start_element)
239                                 return;
240
241                         if (state == WriteState.Attribute)
242                                 WriteEndAttribute ();
243
244                         AddMissingElementXmlns ();
245
246                         state = WriteState.Content;
247                         open_start_element = false;
248                 }
249
250                 public override void Flush ()
251                 {
252                         writer.Flush ();
253                 }
254
255                 public override string LookupPrefix (string ns)
256                 {
257                         if (ns == null || ns == String.Empty)
258                                 throw new ArgumentException ("The Namespace cannot be empty.");
259
260                         var de = namespaces.LastOrDefault (i => i.Value.ToString () == ns);
261                         return de.Key; // de is KeyValuePair and its default key is null.
262                 }
263
264                 public override void WriteBase64 (byte[] buffer, int index, int count)
265                 {
266                         if (count < 0)
267                                 throw new IndexOutOfRangeException ("Negative count");
268                         ProcessStateForContent ();
269
270                         if (count < 0x100) {
271                                 writer.Write (BF.Bytes8);
272                                 writer.Write ((byte) count);
273                                 writer.Write (buffer, index, count);
274                         } else if (count < 0x10000) {
275                                 writer.Write (BF.Bytes8);
276                                 writer.Write ((ushort) count);
277                                 writer.Write (buffer, index, count);
278                         } else {
279                                 writer.Write (BF.Bytes32);
280                                 writer.Write (count);
281                                 writer.Write (buffer, index, count);
282                         }
283                 }
284
285                 public override void WriteCData (string text)
286                 {
287                         if (text.IndexOf ("]]>") >= 0)
288                                 throw new ArgumentException ("CDATA section cannot contain text \"]]>\".");
289
290                         ProcessStateForContent ();
291
292                         WriteTextBinary (text);
293                 }
294
295                 public override void WriteCharEntity (char ch)
296                 {
297                         WriteChars (new char [] {ch}, 0, 1);
298                 }
299
300                 public override void WriteChars (char[] buffer, int index, int count)
301                 {
302                         ProcessStateForContent ();
303
304                         int blen = Encoding.UTF8.GetByteCount (buffer, index, count);
305
306                         if (blen == 0)
307                                 writer.Write (BF.EmptyText);
308                         else if (blen < 0x100) {
309                                 writer.Write (BF.Chars8);
310                                 writer.Write ((byte) blen);
311                                 writer.Write (buffer, index, count);
312                         } else if (blen < 0x10000) {
313                                 writer.Write (BF.Chars16);
314                                 writer.Write ((ushort) blen);
315                                 writer.Write (buffer, index, count);
316                         } else {
317                                 writer.Write (BF.Chars32);
318                                 writer.Write (blen);
319                                 writer.Write (buffer, index, count);
320                         }
321                 }
322
323                 public override void WriteComment (string text)
324                 {
325                         if (text.EndsWith("-"))
326                                 throw new ArgumentException ("An XML comment cannot contain \"--\" inside.");
327                         else if (text.IndexOf("--") > 0)
328                                 throw new ArgumentException ("An XML comment cannot end with \"-\".");
329
330                         ProcessStateForContent ();
331
332                         if (state == WriteState.Attribute)
333                                 throw new InvalidOperationException ("Comment node is not allowed inside an attribute");
334
335                         writer.Write (BF.Comment);
336                         writer.Write (text);
337                 }
338
339                 public override void WriteDocType (string name, string pubid, string sysid, string subset)
340                 {
341                         throw new NotSupportedException ("This XmlWriter implementation does not support document type.");
342                 }
343
344                 public override void WriteEndAttribute ()
345                 {
346                         if (state != WriteState.Attribute)
347                                 throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
348
349                         CheckState ();
350
351                         if (attr_value == null)
352                                 attr_value = String.Empty;
353
354                         switch (save_target) {
355                         case SaveTarget.XmlLang:
356                                 xml_lang = attr_value;
357                                 goto default;
358                         case SaveTarget.XmlSpace:
359                                 switch (attr_value) {
360                                 case "preserve":
361                                         xml_space = XmlSpace.Preserve;
362                                         break;
363                                 case "default":
364                                         xml_space = XmlSpace.Default;
365                                         break;
366                                 default:
367                                         throw new ArgumentException (String.Format ("Invalid xml:space value: '{0}'", attr_value));
368                                 }
369                                 goto default;
370                         case SaveTarget.Namespaces:
371                                 if (current_attr_name.ToString ().Length > 0 && attr_value.Length == 0)
372                                         throw new ArgumentException ("Cannot use prefix with an empty namespace.");
373
374                                 AddNamespaceChecked (current_attr_name.ToString (), attr_value);
375                                 break;
376                         default:
377                                 if (!attr_typed_value)
378                                         WriteTextBinary (attr_value);
379                                 break;
380                         }
381
382                         if (current_attr_prefix.Length > 0 && save_target != SaveTarget.Namespaces)
383                                 AddNamespaceChecked (current_attr_prefix, current_attr_ns);
384
385                         state = WriteState.Element;
386                         current_attr_prefix = null;
387                         current_attr_name = null;
388                         current_attr_ns = null;
389                         attr_value = null;
390                         attr_typed_value = false;
391                 }
392
393                 public override void WriteEndDocument ()
394                 {
395                         CloseOpenAttributeAndElements ();
396
397                         switch (state) {
398                         case WriteState.Start:
399                                 throw new InvalidOperationException ("Document has not started.");
400                         case WriteState.Prolog:
401                                 throw new ArgumentException ("This document does not have a root element.");
402                         }
403
404                         state = WriteState.Start;
405                 }
406
407                 bool SupportsCombinedEndElementSupport (byte operation)
408                 {
409                         switch (operation) {
410                         case BF.Comment:
411                                 return false;
412                         }
413                         return true;
414                 }
415
416                 public override void WriteEndElement ()
417                 {
418                         if (element_count-- == 0)
419                                 throw new InvalidOperationException("There was no XML start tag open.");
420
421                         if (state == WriteState.Attribute)
422                                 WriteEndAttribute ();
423
424                         // Comment+EndElement does not exist
425                         bool needExplicitEndElement = buffer.Position == 0 || !SupportsCombinedEndElementSupport (buffer.GetBuffer () [0]);
426                         ProcessPendingBuffer (true, !needExplicitEndElement);
427                         CheckState ();
428                         AddMissingElementXmlns ();
429
430                         if (needExplicitEndElement)
431                                 writer.Write (BF.EndElement);
432
433                         element_ns = element_ns_stack.Pop ();
434                         xml_lang = xml_lang_stack.Pop ();
435                         xml_space = xml_space_stack.Pop ();
436                         int cur = namespaces.Count;
437                         ns_index = ns_index_stack.Pop ();
438                         namespaces.RemoveRange (ns_index, cur - ns_index);
439                         open_start_element = false;
440
441                         Depth--;
442                 }
443
444                 public override void WriteEntityRef (string name)
445                 {
446                         throw new NotSupportedException ("This XmlWriter implementation does not support entity references.");
447                 }
448
449                 public override void WriteFullEndElement ()
450                 {
451                         WriteEndElement ();
452                 }
453
454                 public override void WriteProcessingInstruction (string name, string text)
455                 {
456                         if (name != "xml")
457                                 throw new ArgumentException ("Processing instructions are not supported. ('xml' is allowed for XmlDeclaration; this is because of design problem of ECMA XmlWriter)");
458                         // Otherwise, silently ignored. WriteStartDocument()
459                         // is still callable after this method(!)
460                 }
461
462                 public override void WriteQualifiedName (XmlDictionaryString local, XmlDictionaryString ns)
463                 {
464                         string prefix = namespaces.LastOrDefault (i => i.Value.ToString () == ns.ToString ()).Key;
465                         bool use_dic = prefix != null;
466                         if (prefix == null)
467                                 prefix = LookupPrefix (ns.Value);
468                         if (prefix == null)
469                                 throw new ArgumentException (String.Format ("Namespace URI '{0}' is not bound to any of the prefixes", ns));
470
471                         ProcessTypedValue ();
472
473                         if (use_dic && prefix.Length == 1) {
474                                 writer.Write (BF.QNameIndex);
475                                 writer.Write ((byte) (prefix [0] - 'a'));
476                                 WriteDictionaryIndex (local);
477                         } else {
478                                 // QNameIndex is not applicable.
479                                 WriteString (prefix);
480                                 WriteString (":");
481                                 WriteString (local);
482                         }
483                 }
484
485                 public override void WriteRaw (string data)
486                 {
487                         WriteString (data);
488                 }
489
490                 public override void WriteRaw (char[] buffer, int index, int count)
491                 {
492                         WriteChars (buffer, index, count);
493                 }
494
495                 void CheckStateForAttribute ()
496                 {
497                         CheckState ();
498
499                         if (state != WriteState.Element)
500                                 throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
501                 }
502
503                 string CreateNewPrefix ()
504                 {
505                         return CreateNewPrefix (String.Empty);
506                 }
507                 
508                 string CreateNewPrefix (string p)
509                 {
510                         for (char c = 'a'; c <= 'z'; c++)
511                                 if (!namespaces.Any (iter => iter.Key == p + c))
512                                         return p + c;
513                         for (char c = 'a'; c <= 'z'; c++) {
514                                 var s = CreateNewPrefix (c.ToString ());
515                                 if (s != null)
516                                         return s;
517                         }
518                         throw new InvalidOperationException ("too many prefix population");
519                 }
520
521                 bool CollectionContains (ICollection col, string value)
522                 {
523                         foreach (string v in col)
524                                 if (v == value)
525                                         return true;
526                         return false;
527                 }
528
529                 void ProcessStartAttributeCommon (ref string prefix, string localName, string ns, object nameObj, object nsObj)
530                 {
531                         // dummy prefix is created here, while the caller
532                         // still uses empty string as the prefix there.
533                         if (prefix.Length == 0 && ns.Length > 0) {
534                                 prefix = LookupPrefix (ns);
535                                 // Not only null but also ""; when the returned
536                                 // string is empty, then it still needs a dummy
537                                 // prefix, since default namespace does not
538                                 // apply to attribute
539                                 if (String.IsNullOrEmpty (prefix))
540                                         prefix = CreateNewPrefix ();
541                         }
542                         else if (prefix.Length > 0 && ns.Length == 0)
543                                 throw new ArgumentException ("Cannot use prefix with an empty namespace.");
544                         // here we omit such cases that it is used for writing
545                         // namespace-less xml, unlike XmlTextWriter.
546                         if (prefix == "xmlns" && ns != XmlnsNamespace)
547                                 throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
548
549                         CheckStateForAttribute ();
550
551                         state = WriteState.Attribute;
552
553                         save_target = SaveTarget.None;
554                         switch (prefix) {
555                         case "xml":
556                                 // MS.NET looks to allow other names than 
557                                 // lang and space (e.g. xml:link, xml:hack).
558                                 ns = XmlNamespace;
559                                 switch (localName) {
560                                 case "lang":
561                                         save_target = SaveTarget.XmlLang;
562                                         break;
563                                 case "space":
564                                         save_target = SaveTarget.XmlSpace;
565                                         break;
566                                 }
567                                 break;
568                         case "xmlns":
569                                 save_target = SaveTarget.Namespaces;
570                                 break;
571                         }
572
573                         current_attr_prefix = prefix;
574                         current_attr_name = nameObj;
575                         current_attr_ns = nsObj;
576                 }
577
578                 public override void WriteStartAttribute (string prefix, string localName, string ns)
579                 {
580                         if (prefix == null)
581                                 prefix = String.Empty;
582                         if (ns == null)
583                                 ns = String.Empty;
584                         if (localName == "xmlns" && prefix.Length == 0) {
585                                 prefix = "xmlns";
586                                 localName = String.Empty;
587                         }
588
589                         ProcessStartAttributeCommon (ref prefix, localName, ns, localName, ns);
590
591                         // for namespace nodes we don't write attribute node here.
592                         if (save_target == SaveTarget.Namespaces)
593                                 return;
594
595                         byte op = prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z' ?
596                                   (byte) (prefix [0] - 'a' + BF.PrefixNAttrStringStart) :
597                                   prefix.Length == 0 ? BF.AttrString :
598                                   BF.AttrStringPrefix;
599
600                         if (BF.PrefixNAttrStringStart <= op && op <= BF.PrefixNAttrStringEnd) {
601                                 writer.Write (op);
602                                 writer.Write (localName);
603                         } else {
604                                 writer.Write (op);
605                                 if (prefix.Length > 0)
606                                         writer.Write (prefix);
607                                 writer.Write (localName);
608                         }
609                 }
610
611                 public override void WriteStartDocument ()
612                 {
613                         WriteStartDocument (false);
614                 }
615
616                 public override void WriteStartDocument (bool standalone)
617                 {
618                         if (state != WriteState.Start)
619                                 throw new InvalidOperationException("WriteStartDocument should be the first call.");
620
621                         CheckState ();
622
623                         // write nothing to stream.
624
625                         state = WriteState.Prolog;
626                 }
627
628                 void PrepareStartElement ()
629                 {
630                         ProcessPendingBuffer (true, false);
631                         CheckState ();
632                         CloseStartElement ();
633
634                         Depth++;
635
636                         element_ns_stack.Push (element_ns);
637                         xml_lang_stack.Push (xml_lang);
638                         xml_space_stack.Push (xml_space);
639                         ns_index_stack.Push (ns_index);
640                 }
641
642                 public override void WriteStartElement (string prefix, string localName, string ns)
643                 {
644                         PrepareStartElement ();
645
646                         if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
647                                 throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
648
649                         if (ns == null)
650                                 ns = String.Empty;
651                         if (ns == String.Empty)
652                                 prefix = String.Empty;
653                         if (prefix == null)
654                                 prefix = String.Empty;
655
656                         byte op = prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z' ?
657                                   (byte) (prefix [0] - 'a' + BF.PrefixNElemStringStart) :
658                                   prefix.Length == 0 ? BF.ElemString :
659                                   BF.ElemStringPrefix;
660
661                         if (BF.PrefixNElemStringStart <= op && op <= BF.PrefixNElemStringEnd) {
662                                 writer.Write (op);
663                                 writer.Write (localName);
664                         } else {
665                                 writer.Write (op);
666                                 if (prefix.Length > 0)
667                                         writer.Write (prefix);
668                                 writer.Write (localName);
669                         }
670
671                         OpenElement (prefix, ns);
672                 }
673
674                 void OpenElement (string prefix, object nsobj)
675                 {
676                         string ns = nsobj.ToString ();
677
678                         state = WriteState.Element;
679                         open_start_element = true;
680                         element_prefix = prefix;
681                         element_count++;
682                         element_ns = nsobj.ToString ();
683
684                         if (element_ns != String.Empty && LookupPrefix (element_ns) != prefix)
685                                 AddNamespace (prefix, nsobj);
686                 }
687
688                 void AddNamespace (string prefix, object nsobj)
689                 {
690                         namespaces.Add (new KeyValuePair<string,object> (prefix, nsobj));
691                 }
692
693                 void CheckIfTextAllowed ()
694                 {
695                         switch (state) {
696                         case WriteState.Start:
697                         case WriteState.Prolog:
698                                 throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
699                         }
700                 }
701
702                 public override void WriteString (string text)
703                 {
704                         if (text == null)
705                                 throw new ArgumentNullException ("text");
706                         CheckIfTextAllowed ();
707
708                         if (text == null)
709                                 text = String.Empty;
710
711                         ProcessStateForContent ();
712
713                         if (state == WriteState.Attribute)
714                                 attr_value += text;
715                         else
716                                 WriteTextBinary (text);
717                 }
718
719                 public override void WriteString (XmlDictionaryString text)
720                 {
721                         if (text == null)
722                                 throw new ArgumentNullException ("text");
723                         CheckIfTextAllowed ();
724
725                         if (text == null)
726                                 text = XmlDictionaryString.Empty;
727
728                         ProcessStateForContent ();
729
730                         if (state == WriteState.Attribute)
731                                 attr_value += text.Value;
732                         else if (text.Equals (XmlDictionary.Empty))
733                                 writer.Write (BF.EmptyText);
734                         else {
735                                 writer.Write (BF.TextIndex);
736                                 WriteDictionaryIndex (text);
737                         }
738                 }
739
740                 public override void WriteSurrogateCharEntity (char lowChar, char highChar)
741                 {
742                         WriteChars (new char [] {highChar, lowChar}, 0, 2);
743                 }
744
745                 public override void WriteWhitespace (string ws)
746                 {
747                         for (int i = 0; i < ws.Length; i++) {
748                                 switch (ws [i]) {
749                                 case ' ': case '\t': case '\r': case '\n':
750                                         continue;
751                                 default:
752                                         throw new ArgumentException ("Invalid Whitespace");
753                                 }
754                         }
755
756                         ProcessStateForContent ();
757
758                         WriteTextBinary (ws);
759                 }
760
761                 public override void WriteXmlnsAttribute (string prefix, string namespaceUri)
762                 {
763                         if (namespaceUri == null)
764                                 throw new ArgumentNullException ("namespaceUri");
765
766                         if (String.IsNullOrEmpty (prefix))
767                                 prefix = CreateNewPrefix ();
768
769                         CheckStateForAttribute ();
770
771                         AddNamespaceChecked (prefix, namespaceUri);
772
773                         state = WriteState.Element;
774                 }
775
776                 void AddNamespaceChecked (string prefix, object ns)
777                 {
778                         switch (ns.ToString ()) {
779                         case XmlnsNamespace:
780                         case XmlNamespace:
781                                 return;
782                         }
783
784                         if (prefix == null)
785                                 throw new InvalidOperationException ();
786                         var o = namespaces.FirstOrDefault (i => i.Key == prefix);
787                         if (o.Key != null) { // i.e. exists
788                                 if (o.Value.ToString () != ns.ToString ())
789                                         throw new ArgumentException (String.Format ("The prefix '{0}' is already mapped to another namespace URI '{1}' in this element scope", prefix ?? "(null)", o.Value ?? "(null)"));
790                         }
791                         else
792                                 AddNamespace  (prefix, ns);
793                 }
794
795                 #region DictionaryString
796
797                 void WriteDictionaryIndex (XmlDictionaryString ds)
798                 {
799                         XmlDictionaryString ds2;
800                         bool isSession = false;
801                         int idx = ds.Key;
802                         if (ds.Dictionary != dict_ext) {
803                                 isSession = true;
804                                 if (dict_int.TryLookup (ds.Value, out ds2))
805                                         ds = ds2;
806                                 if (!session.TryLookup (ds, out idx))
807                                         session.TryAdd (dict_int.Add (ds.Value), out idx);
808                         }
809                         if (idx >= 0x80) {
810                                 writer.Write ((byte) (0x80 + ((idx % 0x80) << 1) + (isSession ? 1 : 0)));
811                                 writer.Write ((byte) ((byte) (idx / 0x80) << 1));
812                         }
813                         else
814                                 writer.Write ((byte) (((idx % 0x80) << 1) + (isSession ? 1 : 0)));
815                 }
816
817                 public override void WriteStartElement (string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
818                 {
819                         PrepareStartElement ();
820
821                         if (prefix == null)
822                                 prefix = String.Empty;
823
824                         byte op = prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z' ?
825                                   (byte) (prefix [0] - 'a' + BF.PrefixNElemIndexStart) :
826                                   prefix.Length == 0 ? BF.ElemIndex :
827                                   BF.ElemIndexPrefix;
828
829                         if (BF.PrefixNElemIndexStart <= op && op <= BF.PrefixNElemIndexEnd) {
830                                 writer.Write (op);
831                                 WriteDictionaryIndex (localName);
832                         } else {
833                                 writer.Write (op);
834                                 if (prefix.Length > 0)
835                                         writer.Write (prefix);
836                                 WriteDictionaryIndex (localName);
837                         }
838
839                         OpenElement (prefix, namespaceUri);
840                 }
841
842                 public override void WriteStartAttribute (string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
843                 {
844                         if (localName == null)
845                                 throw new ArgumentNullException ("localName");
846                         if (prefix == null)
847                                 prefix = String.Empty;
848                         if (ns == null)
849                                 ns = XmlDictionaryString.Empty;
850                         if (localName.Value == "xmlns" && prefix.Length == 0) {
851                                 prefix = "xmlns";
852                                 localName = XmlDictionaryString.Empty;
853                         }
854
855                         ProcessStartAttributeCommon (ref prefix, localName.Value, ns.Value, localName, ns);
856
857                         if (save_target == SaveTarget.Namespaces)
858                                 return;
859
860                         if (prefix.Length == 1 && 'a' <= prefix [0] && prefix [0] <= 'z') {
861                                 writer.Write ((byte) (prefix [0] - 'a' + BF.PrefixNAttrIndexStart));
862                                 WriteDictionaryIndex (localName);
863                         } else {
864                                 byte op = ns.Value.Length == 0 ? BF.AttrIndex :BF.AttrIndexPrefix;
865                                 // Write to Stream
866                                 writer.Write (op);
867                                 if (prefix.Length > 0)
868                                         writer.Write (prefix);
869                                 WriteDictionaryIndex (localName);
870                         }
871                 }
872
873                 public override void WriteXmlnsAttribute (string prefix, XmlDictionaryString namespaceUri)
874                 {
875                         if (namespaceUri == null)
876                                 throw new ArgumentNullException ("namespaceUri");
877
878                         if (String.IsNullOrEmpty (prefix))
879                                 prefix = CreateNewPrefix ();
880
881                         CheckStateForAttribute ();
882
883                         AddNamespaceChecked (prefix, namespaceUri);
884
885                         state = WriteState.Element;
886                 }
887                 #endregion
888
889                 #region WriteValue
890                 public override void WriteValue (bool value)
891                 {
892                         ProcessTypedValue ();
893                         writer.Write ((byte) (value ? BF.BoolTrue : BF.BoolFalse));
894                 }
895
896                 public override void WriteValue (int value)
897                 {
898                         WriteValue ((long) value);
899                 }
900
901                 public override void WriteValue (long value)
902                 {
903                         ProcessTypedValue ();
904
905                         if (value == 0)
906                                 writer.Write (BF.Zero);
907                         else if (value == 1)
908                                 writer.Write (BF.One);
909                         else if (value < 0 || value > uint.MaxValue) {
910                                 writer.Write (BF.Int64);
911                                 for (int i = 0; i < 8; i++) {
912                                         writer.Write ((byte) (value & 0xFF));
913                                         value >>= 8;
914                                 }
915                         } else if (value <= byte.MaxValue) {
916                                 writer.Write (BF.Int8);
917                                 writer.Write ((byte) value);
918                         } else if (value <= short.MaxValue) {
919                                 writer.Write (BF.Int16);
920                                 writer.Write ((byte) (value & 0xFF));
921                                 writer.Write ((byte) (value >> 8));
922                         } else if (value <= int.MaxValue) {
923                                 writer.Write (BF.Int32);
924                                 for (int i = 0; i < 4; i++) {
925                                         writer.Write ((byte) (value & 0xFF));
926                                         value >>= 8;
927                                 }
928                         }
929                 }
930
931                 public override void WriteValue (float value)
932                 {
933                         ProcessTypedValue ();
934                         writer.Write (BF.Single);
935                         WriteValueContent (value);
936                 }
937
938                 void WriteValueContent (float value)
939                 {
940                         writer.Write (value);
941                 }
942
943                 public override void WriteValue (double value)
944                 {
945                         ProcessTypedValue ();
946                         writer.Write (BF.Double);
947                         WriteValueContent (value);
948                 }
949
950                 void WriteValueContent (double value)
951                 {
952                         writer.Write (value);
953                 }
954
955                 public override void WriteValue (decimal value)
956                 {
957                         ProcessTypedValue ();
958                         writer.Write (BF.Decimal);
959                         WriteValueContent (value);
960                 }
961
962                 void WriteValueContent (decimal value)
963                 {
964                         int [] bits = Decimal.GetBits (value);
965                         // so, looks like it is saved as its internal form,
966                         // not the returned order.
967                         // BinaryWriter.Write(Decimal) is useless here.
968                         writer.Write (bits [3]);
969                         writer.Write (bits [2]);
970                         writer.Write (bits [0]);
971                         writer.Write (bits [1]);
972                 }
973
974                 public override void WriteValue (DateTime value)
975                 {
976                         ProcessTypedValue ();
977                         writer.Write (BF.DateTime);
978                         WriteValueContent (value);
979                 }
980
981                 void WriteValueContent (DateTime value)
982                 {
983                         writer.Write (value.Ticks);
984                 }
985
986                 public override void WriteValue (Guid value)
987                 {
988                         ProcessTypedValue ();
989                         writer.Write (BF.Guid);
990                         WriteValueContent (value);
991                 }
992
993                 void WriteValueContent (Guid value)
994                 {
995                         byte [] bytes = value.ToByteArray ();
996                         writer.Write (bytes, 0, bytes.Length);
997                 }
998
999                 public override void WriteValue (UniqueId value)
1000                 {
1001                         if (value == null)
1002                                 throw new ArgumentNullException ("value");
1003
1004                         Guid guid;
1005                         if (value.TryGetGuid (out guid)) {
1006                                 // this conditional branching is required for
1007                                 // attr_typed_value not being true.
1008                                 ProcessTypedValue ();
1009
1010                                 writer.Write (BF.UniqueId);
1011                                 byte [] bytes = guid.ToByteArray ();
1012                                 writer.Write (bytes, 0, bytes.Length);
1013                         } else {
1014                                 WriteValue (value.ToString ());
1015                         }
1016                 }
1017
1018                 public override void WriteValue (TimeSpan value)
1019                 {
1020                         ProcessTypedValue ();
1021
1022                         writer.Write (BF.TimeSpan);
1023                         WriteValueContent (value);
1024                 }
1025
1026                 void WriteValueContent (TimeSpan value)
1027                 {
1028                         WriteBigEndian (value.Ticks, 8);
1029                 }
1030                 #endregion
1031
1032                 private void WriteBigEndian (long value, int digits)
1033                 {
1034                         long v = 0;
1035                         for (int i = 0; i < digits; i++) {
1036                                 v = (v << 8) + (value & 0xFF);
1037                                 value >>= 8;
1038                         }
1039                         for (int i = 0; i < digits; i++) {
1040                                 writer.Write ((byte) (v & 0xFF));
1041                                 v >>= 8;
1042                         }
1043                 }
1044
1045                 private void WriteTextBinary (string text)
1046                 {
1047                         if (text.Length == 0)
1048                                 writer.Write (BF.EmptyText);
1049                         else {
1050                                 char [] arr = text.ToCharArray ();
1051                                 WriteChars (arr, 0, arr.Length);
1052                         }
1053                 }
1054
1055                 #endregion
1056
1057                 #region Write typed array content
1058
1059                 // they are packed in WriteValue(), so we cannot reuse
1060                 // them for array content.
1061
1062                 void WriteValueContent (bool value)
1063                 {
1064                         writer.Write (value ? (byte) 1 : (byte) 0);
1065                 }
1066
1067                 void WriteValueContent (short value)
1068                 {
1069                         writer.Write (value);
1070                 }
1071
1072                 void WriteValueContent (int value)
1073                 {
1074                         writer.Write (value);
1075                 }
1076
1077                 void WriteValueContent (long value)
1078                 {
1079                         writer.Write (value);
1080                 }
1081
1082                 #endregion
1083         }
1084 }