XmlBinaryDictionaryWriter.cs 24 KB

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