XmlBinaryDictionaryWriter.cs 27 KB

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