2
0

XmlBinaryDictionaryWriter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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.Text;
  36. using BF = System.Xml.XmlBinaryFormat;
  37. namespace System.Xml
  38. {
  39. internal class XmlBinaryDictionaryWriter : XmlDictionaryWriter
  40. {
  41. #region Fields
  42. BinaryWriter original, writer, buffer_writer;
  43. IXmlDictionary dict_ext;
  44. XmlDictionary dict_int = new XmlDictionary ();
  45. XmlBinaryWriterSession session;
  46. bool owns_stream;
  47. Encoding utf8Enc = new UTF8Encoding ();
  48. MemoryStream buffer = new MemoryStream ();
  49. const string XmlNamespace = "http://www.w3.org/XML/1998/namespace";
  50. const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
  51. WriteState state = WriteState.Start;
  52. bool open_start_element = false;
  53. // transient current node info
  54. ListDictionary namespaces = new ListDictionary ();
  55. List<string> dummy_namespaces = new List<string> ();
  56. string xml_lang = null;
  57. XmlSpace xml_space = XmlSpace.None;
  58. // stacked info
  59. Stack<string> xml_lang_stack = new Stack<string> ();
  60. Stack<XmlSpace> xml_space_stack = new Stack<XmlSpace> ();
  61. XmlNamespaceManager nsmgr = new XmlNamespaceManager (new NameTable ());
  62. Stack<string> element_ns_stack = new Stack<string> ();
  63. string element_ns = String.Empty;
  64. int element_count;
  65. string element_prefix; // only meaningful at Element state
  66. // current attribute info
  67. string attr_value;
  68. string current_attr_prefix;
  69. object current_attr_name, current_attr_ns;
  70. bool attr_typed_value;
  71. SaveTarget save_target;
  72. enum SaveTarget {
  73. None,
  74. Namespaces,
  75. XmlLang,
  76. XmlSpace
  77. }
  78. // XmlWriterSettings support
  79. #endregion
  80. #region Constructors
  81. public XmlBinaryDictionaryWriter (Stream stream,
  82. IXmlDictionary dictionary,
  83. XmlBinaryWriterSession session, bool ownsStream)
  84. {
  85. if (dictionary == null)
  86. dictionary = new XmlDictionary ();
  87. if (session == null)
  88. session = new XmlBinaryWriterSession ();
  89. original = new BinaryWriter (stream);
  90. this.writer = original;
  91. buffer_writer = new BinaryWriter (buffer);
  92. this.dict_ext = dictionary;
  93. this.session = session;
  94. owns_stream = ownsStream;
  95. // xml_lang_stack.Push (null);
  96. // xml_space_stack.Push (XmlSpace.None);
  97. }
  98. #endregion
  99. #region Properties
  100. public override WriteState WriteState {
  101. get { return state; }
  102. }
  103. public override string XmlLang {
  104. get { return xml_lang; }
  105. }
  106. public override XmlSpace XmlSpace {
  107. get { return xml_space; }
  108. }
  109. #endregion
  110. #region Methods
  111. private void AddMissingElementXmlns ()
  112. {
  113. // push new namespaces to manager.
  114. foreach (DictionaryEntry ent in namespaces) {
  115. string prefix = (string) ent.Key;
  116. string ns = ent.Value as string;
  117. XmlDictionaryString dns = ent.Value as XmlDictionaryString;
  118. if (ns != null) {
  119. if (prefix.Length > 0) {
  120. writer.Write (BF.PrefixNSString);
  121. writer.Write (prefix);
  122. }
  123. else
  124. writer.Write (BF.DefaultNSString);
  125. writer.Write (ns);
  126. } else {
  127. if (prefix.Length > 0) {
  128. writer.Write (BF.PrefixNSIndex);
  129. writer.Write (prefix);
  130. }
  131. else
  132. writer.Write (BF.DefaultNSIndex);
  133. WriteDictionaryIndex (dns);
  134. }
  135. nsmgr.AddNamespace (prefix, ent.Value.ToString ());
  136. }
  137. namespaces.Clear ();
  138. dummy_namespaces.Clear ();
  139. }
  140. private void CheckState ()
  141. {
  142. if (state == WriteState.Closed) {
  143. throw new InvalidOperationException ("The Writer is closed.");
  144. }
  145. }
  146. void ProcessStateForContent ()
  147. {
  148. CheckState ();
  149. if (state == WriteState.Element)
  150. CloseStartElement ();
  151. ProcessPendingBuffer (false, false);
  152. if (state != WriteState.Attribute)
  153. writer = buffer_writer;
  154. }
  155. void ProcessTypedValue ()
  156. {
  157. ProcessStateForContent ();
  158. if (state == WriteState.Attribute) {
  159. if (attr_typed_value)
  160. throw new InvalidOperationException (String.Format ("A typed value for the attribute '{0}' in namespace '{1}' was already written", current_attr_name, current_attr_ns));
  161. attr_typed_value = true;
  162. }
  163. }
  164. void ProcessPendingBuffer (bool last, bool endElement)
  165. {
  166. if (buffer.Position > 0) {
  167. byte [] arr = buffer.GetBuffer ();
  168. if (endElement)
  169. arr [0]++;
  170. original.Write (arr, 0, (int) buffer.Position);
  171. buffer.SetLength (0);
  172. }
  173. if (last)
  174. writer = original;
  175. }
  176. public override void Close ()
  177. {
  178. CloseOpenAttributeAndElements ();
  179. if (owns_stream)
  180. writer.Close ();
  181. else if (state != WriteState.Closed)
  182. writer.Flush ();
  183. state = WriteState.Closed;
  184. }
  185. private void CloseOpenAttributeAndElements ()
  186. {
  187. CloseStartElement ();
  188. while (element_count > 0)
  189. WriteEndElement ();
  190. }
  191. private void CloseStartElement ()
  192. {
  193. if (!open_start_element)
  194. return;
  195. if (state == WriteState.Attribute)
  196. WriteEndAttribute ();
  197. AddMissingElementXmlns ();
  198. state = WriteState.Content;
  199. open_start_element = false;
  200. nsmgr.PushScope ();
  201. }
  202. public override void Flush ()
  203. {
  204. writer.Flush ();
  205. }
  206. public override string LookupPrefix (string ns)
  207. {
  208. if (ns == null || ns == String.Empty)
  209. throw new ArgumentException ("The Namespace cannot be empty.");
  210. throw new NotImplementedException ();
  211. }
  212. public override void WriteBase64 (byte[] buffer, int index, int count)
  213. {
  214. if (count < 0)
  215. throw new IndexOutOfRangeException ("Negative count");
  216. ProcessStateForContent ();
  217. if (count < 0x100) {
  218. writer.Write (BF.Bytes8);
  219. writer.Write ((byte) count);
  220. writer.Write (buffer, index, count);
  221. } else if (count < 0x10000) {
  222. writer.Write (BF.Bytes8);
  223. writer.Write ((ushort) count);
  224. writer.Write (buffer, index, count);
  225. } else {
  226. writer.Write (BF.Bytes32);
  227. writer.Write (count);
  228. writer.Write (buffer, index, count);
  229. }
  230. }
  231. public override void WriteCData (string text)
  232. {
  233. if (text.IndexOf ("]]>") >= 0)
  234. throw new ArgumentException ("CDATA section cannot contain text \"]]>\".");
  235. ProcessStateForContent ();
  236. WriteTextBinary (text);
  237. }
  238. public override void WriteCharEntity (char ch)
  239. {
  240. WriteChars (new char [] {ch}, 0, 1);
  241. }
  242. public override void WriteChars (char[] buffer, int index, int count)
  243. {
  244. ProcessStateForContent ();
  245. int blen = Encoding.UTF8.GetByteCount (buffer, index, count);
  246. if (blen == 0)
  247. writer.Write (BF.EmptyText);
  248. else if (blen < 0x100) {
  249. writer.Write (BF.Chars8);
  250. writer.Write ((byte) blen);
  251. writer.Write (buffer, index, count);
  252. } else if (blen < 0x10000) {
  253. writer.Write (BF.Chars16);
  254. writer.Write ((ushort) blen);
  255. writer.Write (buffer, index, count);
  256. } else {
  257. writer.Write (BF.Chars32);
  258. writer.Write (blen);
  259. writer.Write (buffer, index, count);
  260. }
  261. }
  262. public override void WriteComment (string text)
  263. {
  264. if (text.EndsWith("-"))
  265. throw new ArgumentException ("An XML comment cannot contain \"--\" inside.");
  266. else if (text.IndexOf("--") > 0)
  267. throw new ArgumentException ("An XML comment cannot end with \"-\".");
  268. ProcessStateForContent ();
  269. if (state == WriteState.Attribute)
  270. throw new InvalidOperationException ("Comment node is not allowed inside an attribute");
  271. writer.Write (BF.Comment);
  272. writer.Write (text);
  273. }
  274. public override void WriteDocType (string name, string pubid, string sysid, string subset)
  275. {
  276. throw new NotSupportedException ("This XmlWriter implementation does not support document type.");
  277. }
  278. public override void WriteEndAttribute ()
  279. {
  280. if (state != WriteState.Attribute)
  281. throw new InvalidOperationException("Token EndAttribute in state Start would result in an invalid XML document.");
  282. CheckState ();
  283. if (attr_value == null)
  284. attr_value = String.Empty;
  285. switch (save_target) {
  286. case SaveTarget.XmlLang:
  287. xml_lang = attr_value;
  288. goto default;
  289. case SaveTarget.XmlSpace:
  290. switch (attr_value) {
  291. case "preserve":
  292. xml_space = XmlSpace.Preserve;
  293. break;
  294. case "default":
  295. xml_space = XmlSpace.Default;
  296. break;
  297. default:
  298. throw new ArgumentException (String.Format ("Invalid xml:space value: '{0}'", attr_value));
  299. }
  300. goto default;
  301. case SaveTarget.Namespaces:
  302. if (current_attr_name.ToString ().Length > 0 && attr_value.Length == 0)
  303. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  304. // add namespace
  305. AddNamespaceChecked (current_attr_name.ToString (), attr_value);
  306. break;
  307. default:
  308. if (!attr_typed_value)
  309. WriteTextBinary (attr_value);
  310. break;
  311. }
  312. state = WriteState.Element;
  313. current_attr_prefix = null;
  314. current_attr_name = null;
  315. current_attr_ns = null;
  316. attr_value = null;
  317. attr_typed_value = false;
  318. }
  319. public override void WriteEndDocument ()
  320. {
  321. CloseOpenAttributeAndElements ();
  322. switch (state) {
  323. case WriteState.Start:
  324. throw new InvalidOperationException ("Document has not started.");
  325. case WriteState.Prolog:
  326. throw new ArgumentException ("This document does not have a root element.");
  327. }
  328. state = WriteState.Start;
  329. }
  330. bool SupportsCombinedEndElementSupport (byte operation)
  331. {
  332. switch (operation) {
  333. case BF.Comment:
  334. return false;
  335. }
  336. return true;
  337. }
  338. public override void WriteEndElement ()
  339. {
  340. if (element_count-- == 0)
  341. throw new InvalidOperationException("There was no XML start tag open.");
  342. if (state == WriteState.Attribute)
  343. WriteEndAttribute ();
  344. // Comment+EndElement does not exist
  345. bool needExplicitEndElement = buffer.Position == 0 || !SupportsCombinedEndElementSupport (buffer.GetBuffer () [0]);
  346. ProcessPendingBuffer (true, !needExplicitEndElement);
  347. CheckState ();
  348. AddMissingElementXmlns ();
  349. if (needExplicitEndElement)
  350. writer.Write (BF.EndElement);
  351. nsmgr.PopScope ();
  352. element_ns = element_ns_stack.Pop ();
  353. xml_lang = xml_lang_stack.Pop ();
  354. xml_space = xml_space_stack.Pop ();
  355. open_start_element = false;
  356. Depth--;
  357. }
  358. public override void WriteEntityRef (string name)
  359. {
  360. throw new NotSupportedException ("This XmlWriter implementation does not support entity references.");
  361. }
  362. public override void WriteFullEndElement ()
  363. {
  364. WriteEndElement ();
  365. }
  366. public override void WriteProcessingInstruction (string name, string text)
  367. {
  368. if (name != "xml")
  369. throw new ArgumentException ("Processing instructions are not supported. ('xml' is allowed for XmlDeclaration; this is because of design problem of ECMA XmlWriter)");
  370. // Otherwise, silently ignored. WriteStartDocument()
  371. // is still callable after this method(!)
  372. }
  373. public override void WriteRaw (string data)
  374. {
  375. WriteString (data);
  376. }
  377. public override void WriteRaw (char[] buffer, int index, int count)
  378. {
  379. WriteChars (buffer, index, count);
  380. }
  381. void CheckStateForAttribute ()
  382. {
  383. CheckState ();
  384. if (state != WriteState.Element)
  385. throw new InvalidOperationException ("Token StartAttribute in state " + WriteState + " would result in an invalid XML document.");
  386. }
  387. string CreateNewPrefix ()
  388. {
  389. string s = String.Empty;
  390. for (int n = 0; n < 26; n++) {
  391. for (int i = 0; i < 26; i++) {
  392. string x = s + (char) (0x61 + i);
  393. if (!namespaces.Contains (x))
  394. return x;
  395. }
  396. s = ((char) (0x61 + n)).ToString ();
  397. }
  398. throw new InvalidOperationException ("too many prefix population");
  399. }
  400. bool CollectionContains (ICollection col, string value)
  401. {
  402. foreach (string v in col)
  403. if (v == value)
  404. return true;
  405. return false;
  406. }
  407. void ProcessStartAttributeCommon (string prefix, string localName, string ns, object nameObj, object nsObj)
  408. {
  409. // dummy prefix is created here, while the caller
  410. // still uses empty string as the prefix there.
  411. if (prefix.Length == 0 && ns.Length > 0
  412. // this condition is to exclude duplicate mappings.
  413. // (I assume it is correct, but might be insufficient.)
  414. && !CollectionContains (dummy_namespaces, ns)) {
  415. prefix = CreateNewPrefix ();
  416. dummy_namespaces.Add (ns);
  417. }
  418. else if (prefix.Length > 0 && ns.Length == 0)
  419. throw new ArgumentException ("Cannot use prefix with an empty namespace.");
  420. // here we omit such cases that it is used for writing
  421. // namespace-less xml, unlike XmlTextWriter.
  422. if (prefix == "xmlns" && ns != XmlnsNamespace)
  423. throw new ArgumentException (String.Format ("The 'xmlns' attribute is bound to the reserved namespace '{0}'", XmlnsNamespace));
  424. CheckStateForAttribute ();
  425. state = WriteState.Attribute;
  426. save_target = SaveTarget.None;
  427. switch (prefix) {
  428. case "xml":
  429. // MS.NET looks to allow other names than
  430. // lang and space (e.g. xml:link, xml:hack).
  431. ns = XmlNamespace;
  432. switch (localName) {
  433. case "lang":
  434. save_target = SaveTarget.XmlLang;
  435. break;
  436. case "space":
  437. save_target = SaveTarget.XmlSpace;
  438. break;
  439. }
  440. break;
  441. case "xmlns":
  442. save_target = SaveTarget.Namespaces;
  443. break;
  444. }
  445. current_attr_prefix = prefix;
  446. current_attr_name = nameObj;
  447. current_attr_ns = nsObj;
  448. // for namespace nodes we don't write attribute node here.
  449. if (save_target == SaveTarget.Namespaces)
  450. return;
  451. if (prefix.Length > 0)
  452. AddNamespaceChecked (prefix, nsObj);
  453. }
  454. public override void WriteStartAttribute (string prefix, string localName, string ns)
  455. {
  456. if (prefix == null)
  457. prefix = String.Empty;
  458. if (ns == null)
  459. ns = String.Empty;
  460. if (localName == "xmlns" && prefix.Length == 0) {
  461. prefix = "xmlns";
  462. localName = String.Empty;
  463. }
  464. ProcessStartAttributeCommon (prefix, localName, ns, localName, ns);
  465. // for namespace nodes we don't write attribute node here.
  466. if (save_target == SaveTarget.Namespaces)
  467. return;
  468. int op = prefix.Length > 0 ? BF.AttrStringPrefix : BF.AttrString;
  469. // Write to Stream
  470. int idx = BF.AttrTempIndexPrefixStringStart;
  471. if (prefix.Length == 0 && ns.Length > 0) { // i.e. dummy prefix
  472. foreach (string n in dummy_namespaces) {
  473. if (n == ns) {
  474. writer.Write ((byte) (idx));
  475. writer.Write (localName);
  476. idx = -1;
  477. break;
  478. }
  479. if (++idx > BF.AttrTempIndexPrefixStringEnd)
  480. break;
  481. }
  482. }
  483. if (idx >= 0) {
  484. writer.Write ((byte) op);
  485. if (prefix.Length > 0)
  486. writer.Write (prefix);
  487. writer.Write (localName);
  488. }
  489. }
  490. public override void WriteStartDocument ()
  491. {
  492. WriteStartDocument (false);
  493. }
  494. public override void WriteStartDocument (bool standalone)
  495. {
  496. if (state != WriteState.Start)
  497. throw new InvalidOperationException("WriteStartDocument should be the first call.");
  498. CheckState ();
  499. // write nothing to stream.
  500. state = WriteState.Prolog;
  501. }
  502. void PrepareStartElement ()
  503. {
  504. ProcessPendingBuffer (true, false);
  505. CheckState ();
  506. CloseStartElement ();
  507. Depth++;
  508. element_ns_stack.Push (element_ns);
  509. xml_lang_stack.Push (xml_lang);
  510. xml_space_stack.Push (xml_space);
  511. }
  512. public override void WriteStartElement (string prefix, string localName, string ns)
  513. {
  514. PrepareStartElement ();
  515. if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
  516. throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
  517. if (ns == null)
  518. ns = String.Empty;
  519. if (ns == String.Empty)
  520. prefix = String.Empty;
  521. if (prefix == null)
  522. prefix = String.Empty;
  523. writer.Write ((byte) (prefix.Length > 0 ? BF.ElemStringPrefix : BF.ElemString));
  524. if (prefix.Length > 0)
  525. writer.Write (prefix);
  526. writer.Write (localName);
  527. OpenElement (prefix, ns);
  528. }
  529. void OpenElement (string prefix, object nsobj)
  530. {
  531. string ns = nsobj.ToString ();
  532. // if (prefix.Length == 0 && ns != nsmgr.DefaultNamespace ||
  533. // prefix.Length > 0 && nsmgr.LookupNamespace (prefix) != ns) {
  534. // FIXME: this condition might be still incorrect...
  535. if (nsobj.ToString () != element_ns ||
  536. nsmgr.LookupPrefix (element_ns) != prefix) {
  537. nsmgr.AddNamespace (prefix, ns);
  538. if (nsmgr.LookupPrefix (element_ns) != prefix)
  539. namespaces.Add (prefix, nsobj);
  540. }
  541. state = WriteState.Element;
  542. open_start_element = true;
  543. element_prefix = prefix;
  544. element_count++;
  545. element_ns = nsobj.ToString ();
  546. }
  547. public override void WriteString (string text)
  548. {
  549. switch (state) {
  550. case WriteState.Start:
  551. case WriteState.Prolog:
  552. throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
  553. }
  554. if (text == null)
  555. text = String.Empty;
  556. ProcessStateForContent ();
  557. if (state == WriteState.Attribute)
  558. attr_value += text;
  559. else
  560. WriteTextBinary (text);
  561. }
  562. public override void WriteSurrogateCharEntity (char lowChar, char highChar)
  563. {
  564. WriteChars (new char [] {highChar, lowChar}, 0, 2);
  565. }
  566. public override void WriteWhitespace (string ws)
  567. {
  568. for (int i = 0; i < ws.Length; i++) {
  569. switch (ws [i]) {
  570. case ' ': case '\t': case '\r': case '\n':
  571. continue;
  572. default:
  573. throw new ArgumentException ("Invalid Whitespace");
  574. }
  575. }
  576. ProcessStateForContent ();
  577. WriteTextBinary (ws);
  578. }
  579. public override void WriteXmlnsAttribute (string prefix, string namespaceUri)
  580. {
  581. if (namespaceUri == null)
  582. throw new ArgumentNullException ("namespaceUri");
  583. if (prefix == null)
  584. prefix = ((char)('a' + Depth - 1)).ToString ();
  585. CheckStateForAttribute ();
  586. AddNamespaceChecked (prefix, namespaceUri);
  587. state = WriteState.Element;
  588. }
  589. void AddNamespaceChecked (string prefix, object ns)
  590. {
  591. switch (ns.ToString ()) {
  592. case XmlnsNamespace:
  593. case XmlNamespace:
  594. return;
  595. }
  596. if (prefix == null)
  597. prefix = String.Empty;
  598. if (namespaces.Contains (prefix)) {
  599. if (namespaces [prefix].ToString () != ns.ToString ())
  600. throw new ArgumentException (String.Format ("The prefix '{0}' is already mapped to another namespace URI '{1}' in this element scope", prefix ?? "(null)", namespaces [prefix] ?? "(null)"));
  601. }
  602. else
  603. namespaces.Add (prefix, ns);
  604. }
  605. #region DictionaryString
  606. void WriteDictionaryIndex (XmlDictionaryString ds)
  607. {
  608. XmlDictionaryString ds2;
  609. bool isSession = false;
  610. int idx = ds.Key;
  611. if (ds.Dictionary != dict_ext) {
  612. isSession = true;
  613. if (dict_int.TryLookup (ds.Value, out ds2))
  614. ds = ds2;
  615. if (!session.TryLookup (ds, out idx))
  616. session.TryAdd (dict_int.Add (ds.Value), out idx);
  617. }
  618. if (idx >= 0x80) {
  619. writer.Write ((byte) (0x80 + ((idx % 0x80) << 1) + (isSession ? 1 : 0)));
  620. writer.Write ((byte) ((byte) (idx / 0x80) << 1));
  621. }
  622. else
  623. writer.Write ((byte) (((idx % 0x80) << 1) + (isSession ? 1 : 0)));
  624. }
  625. public override void WriteStartElement (string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
  626. {
  627. PrepareStartElement ();
  628. if (prefix == null)
  629. prefix = String.Empty;
  630. if (prefix.Length == 0)
  631. writer.Write (BF.ElemIndex);
  632. else {
  633. writer.Write (BF.ElemIndexPrefix);
  634. writer.Write (prefix);
  635. }
  636. WriteDictionaryIndex (localName);
  637. OpenElement (prefix, namespaceUri);
  638. }
  639. public override void WriteStartAttribute (string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
  640. {
  641. if (localName == null)
  642. throw new ArgumentNullException ("localName");
  643. if (prefix == null)
  644. prefix = String.Empty;
  645. if (ns == null)
  646. ns = XmlDictionaryString.Empty;
  647. if (localName.Value == "xmlns" && prefix.Length == 0) {
  648. prefix = "xmlns";
  649. localName = XmlDictionaryString.Empty;
  650. }
  651. ProcessStartAttributeCommon (prefix, localName.Value, ns.Value, localName, ns);
  652. if (save_target == SaveTarget.Namespaces)
  653. return;
  654. int op =
  655. ns.Value == nsmgr.LookupNamespace (element_prefix) ? BF.GlobalAttrIndexInElemNS :
  656. ns.Value.Length == 0 ? BF.AttrIndex :
  657. prefix.Length > 0 ? BF.AttrIndexPrefix : BF.GlobalAttrIndex;
  658. // Write to Stream
  659. writer.Write ((byte) op);
  660. if (prefix.Length > 0)
  661. writer.Write (prefix);
  662. WriteDictionaryIndex (localName);
  663. }
  664. public override void WriteXmlnsAttribute (string prefix, XmlDictionaryString namespaceUri)
  665. {
  666. if (prefix == null)
  667. throw new ArgumentNullException ("prefix");
  668. if (namespaceUri == null)
  669. throw new ArgumentNullException ("namespaceUri");
  670. CheckStateForAttribute ();
  671. AddNamespaceChecked (prefix, namespaceUri);
  672. state = WriteState.Element;
  673. }
  674. #endregion
  675. #region WriteValue
  676. public override void WriteValue (bool value)
  677. {
  678. ProcessTypedValue ();
  679. writer.Write ((byte) (value ? BF.BoolTrue : BF.BoolFalse));
  680. }
  681. public override void WriteValue (int value)
  682. {
  683. WriteValue ((long) value);
  684. }
  685. public override void WriteValue (long value)
  686. {
  687. ProcessTypedValue ();
  688. if (value == 0)
  689. writer.Write (BF.Zero);
  690. else if (value == 1)
  691. writer.Write (BF.One);
  692. else if (value < 0 || value > uint.MaxValue) {
  693. writer.Write (BF.Int64);
  694. for (int i = 0; i < 8; i++) {
  695. writer.Write ((byte) (value & 0xFF));
  696. value >>= 8;
  697. }
  698. } else if (value <= byte.MaxValue) {
  699. writer.Write (BF.Int8);
  700. writer.Write ((byte) value);
  701. } else if (value <= short.MaxValue) {
  702. writer.Write (BF.Int16);
  703. writer.Write ((byte) (value & 0xFF));
  704. writer.Write ((byte) (value >> 8));
  705. } else if (value <= int.MaxValue) {
  706. writer.Write (BF.Int32);
  707. for (int i = 0; i < 4; i++) {
  708. writer.Write ((byte) (value & 0xFF));
  709. value >>= 8;
  710. }
  711. }
  712. }
  713. public override void WriteValue (float value)
  714. {
  715. ProcessTypedValue ();
  716. writer.Write (BF.Single);
  717. writer.Write (value);
  718. }
  719. public override void WriteValue (double value)
  720. {
  721. ProcessTypedValue ();
  722. writer.Write (BF.Double);
  723. writer.Write (value);
  724. }
  725. public override void WriteValue (decimal value)
  726. {
  727. ProcessTypedValue ();
  728. writer.Write (BF.Decimal);
  729. int [] bits = Decimal.GetBits (value);
  730. // so, looks like it is saved as its internal form,
  731. // not the returned order.
  732. // BinaryWriter.Write(Decimal) is useless here.
  733. writer.Write (bits [3]);
  734. writer.Write (bits [2]);
  735. writer.Write (bits [0]);
  736. writer.Write (bits [1]);
  737. }
  738. public override void WriteValue (DateTime value)
  739. {
  740. ProcessTypedValue ();
  741. writer.Write (BF.DateTime);
  742. writer.Write (value.Ticks);
  743. }
  744. public override void WriteValue (Guid value)
  745. {
  746. ProcessTypedValue ();
  747. writer.Write (BF.Guid);
  748. byte [] bytes = value.ToByteArray ();
  749. writer.Write (bytes, 0, bytes.Length);
  750. }
  751. public override void WriteValue (UniqueId value)
  752. {
  753. if (value == null)
  754. throw new ArgumentNullException ("value");
  755. Guid guid;
  756. if (value.TryGetGuid (out guid)) {
  757. // this conditional branching is required for
  758. // attr_typed_value not being true.
  759. ProcessTypedValue ();
  760. writer.Write (BF.UniqueId);
  761. byte [] bytes = guid.ToByteArray ();
  762. writer.Write (bytes, 0, bytes.Length);
  763. } else {
  764. WriteValue (value.ToString ());
  765. }
  766. }
  767. public override void WriteValue (TimeSpan value)
  768. {
  769. ProcessTypedValue ();
  770. writer.Write (BF.TimeSpan);
  771. WriteBigEndian (value.Ticks, 8);
  772. }
  773. #endregion
  774. private void WriteBigEndian (long value, int digits)
  775. {
  776. long v = 0;
  777. for (int i = 0; i < digits; i++) {
  778. v = (v << 8) + (value & 0xFF);
  779. value >>= 8;
  780. }
  781. for (int i = 0; i < digits; i++) {
  782. writer.Write ((byte) (v & 0xFF));
  783. v >>= 8;
  784. }
  785. }
  786. private void WriteTextBinary (string text)
  787. {
  788. if (text.Length == 0)
  789. writer.Write (BF.EmptyText);
  790. else {
  791. char [] arr = text.ToCharArray ();
  792. WriteChars (arr, 0, arr.Length);
  793. }
  794. }
  795. #endregion
  796. }
  797. }