XmlBinaryDictionaryReader.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. //
  2. // XmlBinaryDictionaryReader.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 QName = System.Xml.XmlQualifiedName;
  37. using BF = System.Xml.XmlBinaryFormat;
  38. namespace System.Xml
  39. {
  40. // FIXME:
  41. // - support XmlDictionaryReaderQuotas.
  42. internal class XmlBinaryDictionaryReader : XmlDictionaryReader, IXmlNamespaceResolver
  43. {
  44. internal interface ISource
  45. {
  46. int Position { get; }
  47. int ReadByte ();
  48. int Read (byte [] data, int offset, int count);
  49. BinaryReader Reader { get; }
  50. }
  51. internal class StreamSource : ISource
  52. {
  53. BinaryReader stream;
  54. int position;
  55. public StreamSource (Stream stream)
  56. {
  57. this.stream = new BinaryReader (stream);
  58. }
  59. public int Position {
  60. get { return position - 1; }
  61. }
  62. public BinaryReader Reader {
  63. get { return stream; }
  64. }
  65. public int ReadByte ()
  66. {
  67. if (stream.PeekChar () < 0)
  68. return -1;
  69. position++;
  70. return stream.ReadByte ();
  71. }
  72. public int Read (byte [] data, int offset, int count)
  73. {
  74. int ret = stream.Read (data, offset, count);
  75. position += ret;
  76. return ret;
  77. }
  78. }
  79. class NodeInfo
  80. {
  81. public NodeInfo ()
  82. {
  83. }
  84. public NodeInfo (bool isAttr)
  85. {
  86. IsAttributeValue = isAttr;
  87. }
  88. public bool IsAttributeValue;
  89. public int Position;
  90. public string Prefix;
  91. public XmlDictionaryString DictLocalName;
  92. public XmlDictionaryString DictNS;
  93. public XmlNodeType NodeType;
  94. public object TypedValue;
  95. public byte ValueType;
  96. // -1 for nothing,
  97. // -2 for that of element (only for attribute),
  98. // 0 or more to fill later
  99. public int NSSlot;
  100. string name = String.Empty;
  101. string local_name = String.Empty;
  102. string ns = String.Empty;
  103. string value;
  104. public string LocalName {
  105. get { return DictLocalName != null ? DictLocalName.Value : local_name; }
  106. set {
  107. DictLocalName = null;
  108. local_name = value;
  109. }
  110. }
  111. public string NS {
  112. get { return DictNS != null ? DictNS.Value : ns; }
  113. set {
  114. DictNS = null;
  115. ns = value;
  116. }
  117. }
  118. public string Name {
  119. get {
  120. if (name == null)
  121. name = Prefix.Length > 0 ?
  122. String.Concat (Prefix, ":", LocalName) :
  123. LocalName;
  124. return name;
  125. }
  126. }
  127. public string Value {
  128. get {
  129. if (BF.AttrString <= ValueType && ValueType <= BF.PrefixNAttrIndexEnd)
  130. return value; // attribute
  131. switch (ValueType) {
  132. case 0:
  133. case BF.Comment:
  134. case BF.Chars8:
  135. case BF.Chars16:
  136. case BF.Chars32:
  137. case BF.EmptyText:
  138. case BF.Utf16_8:
  139. case BF.Utf16_16:
  140. case BF.Utf16_32:
  141. return value;
  142. case BF.Zero:
  143. case BF.One:
  144. return XmlConvert.ToString ((int) TypedValue);
  145. case BF.Int8:
  146. return XmlConvert.ToString ((byte) TypedValue);
  147. case BF.Int16:
  148. return XmlConvert.ToString ((short) TypedValue);
  149. case BF.Int32:
  150. return XmlConvert.ToString ((int) TypedValue);
  151. case BF.Int64:
  152. return XmlConvert.ToString ((long) TypedValue);
  153. case BF.Single:
  154. return XmlConvert.ToString ((float) TypedValue);
  155. case BF.Double:
  156. return XmlConvert.ToString ((double) TypedValue);
  157. case BF.DateTime:
  158. return XmlConvert.ToString ((DateTime) TypedValue, XmlDateTimeSerializationMode.RoundtripKind);
  159. case BF.TimeSpan:
  160. return XmlConvert.ToString ((TimeSpan) TypedValue);
  161. case BF.Guid:
  162. return XmlConvert.ToString ((Guid) TypedValue);
  163. case BF.UniqueId:
  164. return TypedValue.ToString ();
  165. case BF.Bytes8:
  166. case BF.Bytes16:
  167. case BF.Bytes32:
  168. return Convert.ToBase64String ((byte []) TypedValue);
  169. default:
  170. throw new NotImplementedException ("ValueType " + ValueType + " on node " + NodeType);
  171. }
  172. }
  173. set { this.value = value; }
  174. }
  175. public virtual void Reset ()
  176. {
  177. Position = 0;
  178. DictLocalName = DictNS = null;
  179. LocalName = NS = Prefix = Value = String.Empty;
  180. NodeType = XmlNodeType.None;
  181. TypedValue = null;
  182. ValueType = 0;
  183. NSSlot = -1;
  184. }
  185. }
  186. class AttrNodeInfo : NodeInfo
  187. {
  188. public int ValueIndex;
  189. public int NSIndex;
  190. public override void Reset ()
  191. {
  192. base.Reset ();
  193. ValueIndex = -1;
  194. NodeType = XmlNodeType.Attribute;
  195. }
  196. }
  197. ISource source;
  198. IXmlDictionary dictionary;
  199. XmlDictionaryReaderQuotas quota;
  200. XmlBinaryReaderSession session;
  201. OnXmlDictionaryReaderClose on_close;
  202. XmlParserContext context;
  203. ReadState state = ReadState.Initial;
  204. NodeInfo node;
  205. NodeInfo current;
  206. List<AttrNodeInfo> attributes = new List<AttrNodeInfo> ();
  207. List<NodeInfo> attr_values = new List<NodeInfo> ();
  208. List<NodeInfo> node_stack = new List<NodeInfo> ();
  209. List<QName> ns_store = new List<QName> ();
  210. Dictionary<int,XmlDictionaryString> ns_dict_store =
  211. new Dictionary<int,XmlDictionaryString> ();
  212. int attr_count;
  213. int attr_value_count;
  214. int current_attr = -1;
  215. int depth = 0;
  216. // used during Read()
  217. int ns_slot;
  218. // next byte in the source (one byte token ahead always
  219. // happens because there is no "end of start element" mark).
  220. int next = -1;
  221. bool is_next_end_element;
  222. // temporary buffer for utf8enc.GetString()
  223. byte [] tmp_buffer = new byte [128];
  224. UTF8Encoding utf8enc = new UTF8Encoding ();
  225. // See comment at Read()
  226. int array_item_remaining;
  227. byte array_item_type;
  228. XmlNodeType array_state;
  229. public XmlBinaryDictionaryReader (byte [] buffer, int offset,
  230. int count, IXmlDictionary dictionary,
  231. XmlDictionaryReaderQuotas quota,
  232. XmlBinaryReaderSession session,
  233. OnXmlDictionaryReaderClose onClose)
  234. {
  235. source = /*new ArraySource (buffer, offset, count);*/
  236. new StreamSource (new MemoryStream (buffer, offset, count));
  237. Initialize (dictionary, quota, session, onClose);
  238. }
  239. public XmlBinaryDictionaryReader (Stream stream,
  240. IXmlDictionary dictionary,
  241. XmlDictionaryReaderQuotas quota,
  242. XmlBinaryReaderSession session,
  243. OnXmlDictionaryReaderClose onClose)
  244. {
  245. source = new StreamSource (stream);
  246. Initialize (dictionary, quota, session, onClose);
  247. }
  248. private void Initialize (IXmlDictionary dictionary,
  249. XmlDictionaryReaderQuotas quotas,
  250. XmlBinaryReaderSession session,
  251. OnXmlDictionaryReaderClose onClose)
  252. {
  253. if (quotas == null)
  254. throw new ArgumentNullException ("quotas");
  255. if (dictionary == null)
  256. dictionary = new XmlDictionary ();
  257. this.dictionary = dictionary;
  258. this.quota = quotas;
  259. if (session == null)
  260. session = new XmlBinaryReaderSession ();
  261. this.session = session;
  262. on_close = onClose;
  263. NameTable nt = new NameTable ();
  264. this.context = new XmlParserContext (nt,
  265. new XmlNamespaceManager (nt),
  266. null, XmlSpace.None);
  267. current = node = new NodeInfo ();
  268. current.Reset ();
  269. }
  270. public override int AttributeCount {
  271. get { return attr_count; }
  272. }
  273. public override string BaseURI {
  274. get { return context.BaseURI; }
  275. }
  276. public override int Depth {
  277. get { return current == node ? depth : NodeType == XmlNodeType.Attribute ? depth + 1 : depth + 2; }
  278. }
  279. public override bool EOF {
  280. get { return state == ReadState.EndOfFile || state == ReadState.Error; }
  281. }
  282. public override bool HasValue {
  283. get { return current.Value.Length > 0; }
  284. }
  285. public override bool IsEmptyElement {
  286. get { return false; }
  287. }
  288. public override XmlNodeType NodeType {
  289. get { return current.NodeType; }
  290. }
  291. public override string Prefix {
  292. get { return current_attr >= 0 ? attributes [current_attr].Prefix : current.Prefix; }
  293. }
  294. // looks like it may return attribute's name even if it is on its value node.
  295. public override string LocalName {
  296. get { return current_attr >= 0 ? attributes [current_attr].LocalName : current.LocalName; }
  297. }
  298. public override string NamespaceURI {
  299. get { return current_attr >= 0 ? attributes [current_attr].NS : current.NS; }
  300. }
  301. public override XmlNameTable NameTable {
  302. get { return context.NameTable; }
  303. }
  304. public override XmlDictionaryReaderQuotas Quotas {
  305. get { return quota; }
  306. }
  307. public override ReadState ReadState {
  308. get { return state; }
  309. }
  310. public override string Value {
  311. get { return current.Value; }
  312. }
  313. public override void Close ()
  314. {
  315. if (on_close != null)
  316. on_close (this);
  317. }
  318. public override string GetAttribute (int i)
  319. {
  320. if (i >= attr_count)
  321. throw new ArgumentOutOfRangeException (String.Format ("Specified attribute index is {0} and should be less than {1}", i, attr_count));
  322. return attributes [i].Value;
  323. }
  324. public override string GetAttribute (string name)
  325. {
  326. for (int i = 0; i < attributes.Count; i++)
  327. if (attributes [i].Name == name)
  328. return attributes [i].Value;
  329. return null;
  330. }
  331. public override string GetAttribute (string localName, string ns)
  332. {
  333. for (int i = 0; i < attributes.Count; i++)
  334. if (attributes [i].LocalName == localName &&
  335. attributes [i].NS == ns)
  336. return attributes [i].Value;
  337. return null;
  338. }
  339. public IDictionary<string,string> GetNamespacesInScope (
  340. XmlNamespaceScope scope)
  341. {
  342. return context.NamespaceManager.GetNamespacesInScope (scope);
  343. }
  344. public string LookupPrefix (string ns)
  345. {
  346. return context.NamespaceManager.LookupPrefix (NameTable.Get (ns));
  347. }
  348. public override string LookupNamespace (string prefix)
  349. {
  350. return context.NamespaceManager.LookupNamespace (
  351. NameTable.Get (prefix));
  352. }
  353. public override bool IsArray (out Type type)
  354. {
  355. if (array_state == XmlNodeType.Element) {
  356. type = GetArrayType (array_item_type);
  357. return true;
  358. } else {
  359. type = null;
  360. return false;
  361. }
  362. }
  363. public override bool MoveToElement ()
  364. {
  365. bool ret = current_attr >= 0;
  366. current_attr = -1;
  367. current = node;
  368. return ret;
  369. }
  370. public override bool MoveToFirstAttribute ()
  371. {
  372. if (attr_count == 0)
  373. return false;
  374. current_attr = 0;
  375. current = attributes [current_attr];
  376. return true;
  377. }
  378. public override bool MoveToNextAttribute ()
  379. {
  380. if (++current_attr < attr_count) {
  381. current = attributes [current_attr];
  382. return true;
  383. } else {
  384. --current_attr;
  385. return false;
  386. }
  387. }
  388. public override void MoveToAttribute (int i)
  389. {
  390. if (i >= attr_count)
  391. throw new ArgumentOutOfRangeException (String.Format ("Specified attribute index is {0} and should be less than {1}", i, attr_count));
  392. current_attr = i;
  393. current = attributes [i];
  394. }
  395. public override bool MoveToAttribute (string name)
  396. {
  397. for (int i = 0; i < attributes.Count; i++) {
  398. if (attributes [i].Name == name) {
  399. MoveToAttribute (i);
  400. return true;
  401. }
  402. }
  403. return false;
  404. }
  405. public override bool MoveToAttribute (string localName, string ns)
  406. {
  407. for (int i = 0; i < attributes.Count; i++) {
  408. if (attributes [i].LocalName == localName &&
  409. attributes [i].NS == ns) {
  410. MoveToAttribute (i);
  411. return true;
  412. }
  413. }
  414. return false;
  415. }
  416. public override bool ReadAttributeValue ()
  417. {
  418. if (current_attr < 0)
  419. return false;
  420. int start = attributes [current_attr].ValueIndex;
  421. int end = current_attr + 1 == attr_count ? attr_value_count : attributes [current_attr + 1].ValueIndex;
  422. if (start == end)
  423. return false;
  424. if (!current.IsAttributeValue) {
  425. current = attr_values [start];
  426. return true;
  427. }
  428. // Actually there is no case for attribute whose value is split to more than two nodes. We could simplify the node structure.
  429. /*
  430. for (int i = start; i < end; i++) {
  431. if (current == attr_values [i] && i + 1 < end) {
  432. current = attr_values [i + 1];
  433. return true;
  434. }
  435. }
  436. */
  437. return false;
  438. }
  439. // When reading an array (0x03), it requires extraneously
  440. // complex procedure for XmlReader. First, it reads element,
  441. // type of operation and length of the items. And this XmlReader
  442. // has to return Element state. On the next Read(), it proceeds
  443. // to the value node of the first item of the array, so it
  444. // reads the value stream. On the next Read(), it proceeds to
  445. // EndElement, so it should not read anything from stream while
  446. // it has to move to the node state to EndElement.
  447. public override bool Read ()
  448. {
  449. switch (state) {
  450. case ReadState.Closed:
  451. case ReadState.EndOfFile:
  452. case ReadState.Error:
  453. return false;
  454. }
  455. // clear.
  456. state = ReadState.Interactive;
  457. attr_count = 0;
  458. attr_value_count = 0;
  459. ns_slot = 0;
  460. current = node;
  461. if (node.NodeType == XmlNodeType.Element) {
  462. // push element scope
  463. depth++;
  464. if (node_stack.Count <= depth) {
  465. node_stack.Add (node);
  466. node = new NodeInfo ();
  467. }
  468. else
  469. node = node_stack [depth];
  470. current = node;
  471. }
  472. if (is_next_end_element) {
  473. is_next_end_element = false;
  474. ProcessEndElement ();
  475. return true;
  476. }
  477. // process array node after preparing node stack.
  478. switch (array_state) {
  479. case XmlNodeType.Element:
  480. ReadArrayItem ();
  481. return true;
  482. case XmlNodeType.Text:
  483. ShiftToArrayItemEndElement ();
  484. return true;
  485. case XmlNodeType.EndElement:
  486. if (--array_item_remaining == 0) {
  487. array_state = XmlNodeType.None;
  488. break;
  489. } else {
  490. ShiftToArrayItemElement ();
  491. return true;
  492. }
  493. }
  494. // array consumer does not expect Reset whlie it's on reading. So call it later than array check.
  495. node.Reset ();
  496. int ident = next >= 0 ? next : source.ReadByte ();
  497. next = -1;
  498. // check end of source.
  499. if (ident < 0) {
  500. state = ReadState.EndOfFile;
  501. current.Reset ();
  502. return false;
  503. }
  504. is_next_end_element = ident > 0x80 && (ident & 1) == 1;
  505. ident -= is_next_end_element ? 1 : 0;
  506. switch (ident) {
  507. case BF.EndElement:
  508. ProcessEndElement ();
  509. break;
  510. case BF.Comment:
  511. node.Value = ReadUTF8 ();
  512. node.ValueType = BF.Comment;
  513. node.NodeType = XmlNodeType.Comment;
  514. break;
  515. case BF.ElemString:
  516. case BF.ElemStringPrefix:
  517. case BF.ElemIndex:
  518. case BF.ElemIndexPrefix:
  519. ReadElementBinary ((byte) ident);
  520. break;
  521. case BF.Array:
  522. ident = ReadByteOrError ();
  523. ReadElementBinary ((byte) ident);
  524. ident = ReadByteOrError ();
  525. if (ident != 0x01)
  526. throw new XmlException (String.Format ("EndElement is expected after element in an array. The actual byte was {0:X} in hexadecimal", ident));
  527. ident = ReadByteOrError () - 1; // -1 becauseit contains EndElement
  528. VerifyValidArrayItemType (ident);
  529. if (ident < 0)
  530. throw new XmlException ("The stream has ended where the array item type is expected");
  531. array_item_type = (byte) ident;
  532. array_item_remaining = ReadVariantSize ();
  533. array_state = XmlNodeType.Element;
  534. break;
  535. default:
  536. if (BF.PrefixNElemIndexStart <= ident && ident <= BF.PrefixNElemIndexEnd ||
  537. BF.PrefixNElemStringStart <= ident && ident <= BF.PrefixNElemStringEnd)
  538. goto case BF.ElemString;
  539. ReadTextOrValue ((byte) ident, node, false);
  540. break;
  541. }
  542. return true;
  543. }
  544. void ReadArrayItem ()
  545. {
  546. ReadTextOrValue (array_item_type, node, false);
  547. array_state = XmlNodeType.Text;
  548. }
  549. void ShiftToArrayItemEndElement ()
  550. {
  551. ProcessEndElement ();
  552. array_state = XmlNodeType.EndElement;
  553. }
  554. void ShiftToArrayItemElement ()
  555. {
  556. node.NodeType = XmlNodeType.Element;
  557. context.NamespaceManager.PushScope ();
  558. array_state = XmlNodeType.Element;
  559. }
  560. void VerifyValidArrayItemType (int ident)
  561. {
  562. if (GetArrayType (ident) == null)
  563. throw new XmlException (String.Format ("Unexpected array item type {0:X} in hexadecimal", ident));
  564. }
  565. Type GetArrayType (int ident)
  566. {
  567. switch (ident) {
  568. case BF.Bool:
  569. return typeof (bool);
  570. case BF.Int16:
  571. return typeof (short);
  572. case BF.Int32:
  573. return typeof (int);
  574. case BF.Int64:
  575. return typeof (long);
  576. case BF.Single:
  577. return typeof (float);
  578. case BF.Double:
  579. return typeof (double);
  580. case BF.Decimal:
  581. return typeof (decimal);
  582. case BF.DateTime:
  583. return typeof (DateTime);
  584. case BF.TimeSpan:
  585. return typeof (TimeSpan);
  586. case BF.Guid:
  587. return typeof (Guid);
  588. }
  589. return null;
  590. }
  591. private void ProcessEndElement ()
  592. {
  593. if (depth == 0)
  594. throw new XmlException ("Unexpected end of element while there is no element started.");
  595. current = node = node_stack [--depth];
  596. node.NodeType = XmlNodeType.EndElement;
  597. context.NamespaceManager.PopScope ();
  598. }
  599. private void ReadElementBinary (int ident)
  600. {
  601. // element
  602. node.NodeType = XmlNodeType.Element;
  603. node.Prefix = String.Empty;
  604. context.NamespaceManager.PushScope ();
  605. switch (ident) {
  606. case BF.ElemString:
  607. node.LocalName = ReadUTF8 ();
  608. break;
  609. case BF.ElemStringPrefix:
  610. node.Prefix = ReadUTF8 ();
  611. node.NSSlot = ns_slot++;
  612. goto case BF.ElemString;
  613. case BF.ElemIndex:
  614. node.DictLocalName = ReadDictName ();
  615. break;
  616. case BF.ElemIndexPrefix:
  617. node.Prefix = ReadUTF8 ();
  618. node.NSSlot = ns_slot++;
  619. goto case BF.ElemIndex;
  620. default:
  621. if (BF.PrefixNElemIndexStart <= ident && ident <= BF.PrefixNElemIndexEnd) {
  622. node.Prefix = ((char) (ident - BF.PrefixNElemIndexStart + 'a')).ToString ();
  623. node.DictLocalName = ReadDictName ();
  624. } else if (BF.PrefixNElemStringStart <= ident && ident <= BF.PrefixNElemStringEnd) {
  625. node.Prefix = ((char) (ident - BF.PrefixNElemStringStart + 'a')).ToString ();
  626. node.LocalName = ReadUTF8 ();
  627. }
  628. else
  629. throw new XmlException (String.Format ("Invalid element node type {0:X02} in hexadecimal", ident));
  630. break;
  631. }
  632. bool loop = true;
  633. do {
  634. ident = ReadByteOrError ();
  635. switch (ident) {
  636. case BF.AttrString:
  637. case BF.AttrStringPrefix:
  638. case BF.AttrIndex:
  639. case BF.AttrIndexPrefix:
  640. ReadAttribute ((byte) ident);
  641. break;
  642. case BF.DefaultNSString:
  643. case BF.PrefixNSString:
  644. case BF.DefaultNSIndex:
  645. case BF.PrefixNSIndex:
  646. ReadNamespace ((byte) ident);
  647. break;
  648. default:
  649. if (BF.PrefixNAttrStringStart <= ident && ident <= BF.PrefixNAttrStringEnd ||
  650. BF.PrefixNAttrIndexStart <= ident && ident <= BF.PrefixNAttrIndexEnd)
  651. ReadAttribute ((byte) ident);
  652. else {
  653. next = ident;
  654. loop = false;
  655. }
  656. break;
  657. }
  658. } while (loop);
  659. node.NS = context.NamespaceManager.LookupNamespace (node.Prefix) ?? String.Empty;
  660. foreach (AttrNodeInfo a in attributes)
  661. if (a.Prefix.Length > 0)
  662. a.NS = context.NamespaceManager.LookupNamespace (a.Prefix);
  663. ns_store.Clear ();
  664. ns_dict_store.Clear ();
  665. }
  666. private void ReadAttribute (byte ident)
  667. {
  668. if (attributes.Count == attr_count)
  669. attributes.Add (new AttrNodeInfo ());
  670. AttrNodeInfo a = attributes [attr_count++];
  671. a.Reset ();
  672. a.Position = source.Position;
  673. switch (ident) {
  674. case BF.AttrString:
  675. a.LocalName = ReadUTF8 ();
  676. break;
  677. case BF.AttrStringPrefix:
  678. a.Prefix = ReadUTF8 ();
  679. a.NSSlot = ns_slot++;
  680. goto case BF.AttrString;
  681. case BF.AttrIndex:
  682. a.DictLocalName = ReadDictName ();
  683. break;
  684. case BF.AttrIndexPrefix:
  685. a.Prefix = ReadUTF8 ();
  686. a.NSSlot = ns_slot++;
  687. goto case BF.AttrIndex;
  688. default:
  689. if (BF.PrefixNAttrStringStart <= ident && ident <= BF.PrefixNAttrStringEnd) {
  690. a.Prefix = ((char) ('a' + ident)).ToString ();
  691. a.LocalName = ReadUTF8 ();
  692. break;
  693. }
  694. else if (BF.PrefixNAttrIndexStart <= ident && ident <= BF.PrefixNAttrIndexEnd) {
  695. a.Prefix = ((char) ('a' + ident)).ToString ();
  696. a.DictLocalName = ReadDictName ();
  697. break;
  698. }
  699. else throw new XmlException (String.Format ("Unexpected attribute node type: 0x{0:X02}", ident));
  700. }
  701. ReadAttributeValueBinary (a);
  702. }
  703. private void ReadNamespace (byte ident)
  704. {
  705. string prefix = null, ns = null;
  706. XmlDictionaryString dns;
  707. switch (ident) {
  708. case BF.DefaultNSString:
  709. prefix = String.Empty;
  710. ns = ReadUTF8 ();
  711. break;
  712. case BF.PrefixNSString:
  713. prefix = ReadUTF8 ();
  714. ns = ReadUTF8 ();
  715. break;
  716. case BF.DefaultNSIndex:
  717. prefix = String.Empty;
  718. dns = ReadDictName ();
  719. ns_dict_store.Add (ns_store.Count, dns);
  720. ns = dns.Value;
  721. break;
  722. case BF.PrefixNSIndex:
  723. prefix = ReadUTF8 ();
  724. dns = ReadDictName ();
  725. ns_dict_store.Add (ns_store.Count, dns);
  726. ns = dns.Value;
  727. break;
  728. }
  729. ns_store.Add (new QName (prefix, ns));
  730. context.NamespaceManager.AddNamespace (prefix, ns);
  731. }
  732. private void ReadAttributeValueBinary (AttrNodeInfo a)
  733. {
  734. a.ValueIndex = attr_value_count;
  735. do {
  736. if (attr_value_count == attr_values.Count)
  737. attr_values.Add (new NodeInfo (true));
  738. NodeInfo v = attr_values [attr_value_count++];
  739. v.Reset ();
  740. int ident = ReadByteOrError ();
  741. is_next_end_element = ident > 0x80 && (ident & 1) == 1;
  742. ident -= is_next_end_element ? 1 : 0;
  743. if (!ReadTextOrValue ((byte) ident, v, true) || is_next_end_element)
  744. break;
  745. } while (true);
  746. }
  747. private bool ReadTextOrValue (byte ident, NodeInfo node, bool canSkip)
  748. {
  749. node.Value = null;
  750. node.ValueType = ident;
  751. node.NodeType = XmlNodeType.Text;
  752. switch (ident) {
  753. case BF.Zero:
  754. node.TypedValue = 0;
  755. break;
  756. case BF.One:
  757. node.TypedValue = 1;
  758. break;
  759. case BF.BoolFalse:
  760. node.TypedValue = false;
  761. break;
  762. case BF.BoolTrue:
  763. node.TypedValue = true;
  764. break;
  765. case BF.Int8:
  766. node.TypedValue = ReadByteOrError ();
  767. break;
  768. case BF.Int16:
  769. node.TypedValue = source.Reader.ReadInt16 ();
  770. break;
  771. case BF.Int32:
  772. node.TypedValue = source.Reader.ReadInt32 ();
  773. break;
  774. case BF.Int64:
  775. node.TypedValue = source.Reader.ReadInt64 ();
  776. break;
  777. case BF.Single:
  778. node.TypedValue = source.Reader.ReadSingle ();
  779. break;
  780. case BF.Double:
  781. node.TypedValue = source.Reader.ReadDouble ();
  782. break;
  783. case BF.Decimal:
  784. int [] bits = new int [4];
  785. bits [3] = source.Reader.ReadInt32 ();
  786. bits [2] = source.Reader.ReadInt32 ();
  787. bits [0] = source.Reader.ReadInt32 ();
  788. bits [1] = source.Reader.ReadInt32 ();
  789. node.TypedValue = new Decimal (bits);
  790. break;
  791. case BF.DateTime:
  792. node.TypedValue = new DateTime (source.Reader.ReadInt64 ());
  793. break;
  794. //case BF.UniqueId: // identical to .Text
  795. case BF.Bytes8:
  796. case BF.Bytes16:
  797. case BF.Bytes32:
  798. int size =
  799. (ident == BF.Bytes8) ? source.Reader.ReadByte () :
  800. (ident == BF.Bytes16) ? source.Reader.ReadUInt16 () :
  801. source.Reader.ReadInt32 ();
  802. byte [] base64 = new byte [size];
  803. source.Reader.Read (base64, 0, base64.Length);
  804. node.TypedValue = base64;
  805. break;
  806. case BF.TimeSpan:
  807. node.TypedValue = new TimeSpan (source.Reader.ReadInt64 ());
  808. break;
  809. case BF.UniqueId:
  810. byte [] guid = new byte [16];
  811. source.Reader.Read (guid, 0, guid.Length);
  812. node.TypedValue = new UniqueId (new Guid (guid));
  813. break;
  814. case BF.Guid:
  815. guid = new byte [16];
  816. source.Reader.Read (guid, 0, guid.Length);
  817. node.TypedValue = new Guid (guid);
  818. break;
  819. case BF.Chars8:
  820. case BF.Chars16:
  821. case BF.Chars32:
  822. case BF.Utf16_8:
  823. case BF.Utf16_16:
  824. case BF.Utf16_32:
  825. Encoding enc = ident <= BF.Chars32 ? Encoding.UTF8 : Encoding.Unicode;
  826. size =
  827. (ident == BF.Chars8) ? source.Reader.ReadByte () :
  828. (ident == BF.Chars16) ? source.Reader.ReadUInt16 () :
  829. source.Reader.ReadInt32 ();
  830. byte [] bytes = new byte [size];
  831. source.Reader.Read (bytes, 0, size);
  832. node.Value = enc.GetString (bytes, 0, size);
  833. node.NodeType = XmlNodeType.Text;
  834. break;
  835. case BF.EmptyText:
  836. node.Value = String.Empty;
  837. node.NodeType = XmlNodeType.Text;
  838. break;
  839. default:
  840. if (!canSkip)
  841. throw new ArgumentException (String.Format ("Unexpected binary XML data at position {1}: {0:X}", ident + (is_next_end_element ? 1 : 0), source.Position));
  842. next = ident;
  843. return false;
  844. }
  845. return true;
  846. }
  847. private int ReadVariantSize ()
  848. {
  849. int size = 0;
  850. // If sizeSpec < 0, then it is variant size specifier.
  851. // Otherwise it is fixed size s = sizeSpec + 1 byte(s).
  852. int d = 0;
  853. do {
  854. byte got = ReadByteOrError ();
  855. size += (got & 0x7F) << d;
  856. d += 7;
  857. if (got < 0x80)
  858. break;
  859. } while (true);
  860. return size;
  861. }
  862. private string ReadUTF8 ()
  863. {
  864. int size = ReadVariantSize ();
  865. if (size == 0)
  866. return String.Empty;
  867. if (tmp_buffer.Length < size) {
  868. int extlen = tmp_buffer.Length * 2;
  869. tmp_buffer = new byte [size < extlen ? extlen : size];
  870. }
  871. size = source.Read (tmp_buffer, 0, size);
  872. return utf8enc.GetString (tmp_buffer, 0, size);
  873. }
  874. private XmlDictionaryString ReadDictName ()
  875. {
  876. int key = ReadVariantSize ();
  877. XmlDictionaryString s;
  878. if ((key & 1) == 1) {
  879. if (session.TryLookup (key >> 1, out s))
  880. return s;
  881. } else {
  882. if (dictionary.TryLookup (key >> 1, out s))
  883. return s;
  884. }
  885. throw new XmlException (String.Format ("Input XML binary stream is invalid. No matching XML dictionary string entry at {0}. Binary stream position at {1}", key, source.Position));
  886. }
  887. private byte ReadByteOrError ()
  888. {
  889. if (next >= 0) {
  890. byte b = (byte) next;
  891. next = -1;
  892. return b;
  893. }
  894. int ret = source.ReadByte ();
  895. if (ret < 0)
  896. throw new XmlException (String.Format ("Unexpected end of binary stream. Position is at {0}", source.Position));
  897. return (byte) ret;
  898. }
  899. public override void ResolveEntity ()
  900. {
  901. throw new NotSupportedException ("this XmlReader does not support ResolveEntity.");
  902. }
  903. public override bool TryGetBase64ContentLength (out int length)
  904. {
  905. length = 0;
  906. switch (current.ValueType) {
  907. case BF.Bytes8:
  908. case BF.Bytes16:
  909. case BF.Bytes32:
  910. length = ((byte []) current.TypedValue).Length;
  911. return true;
  912. }
  913. return false;
  914. }
  915. public override string ReadContentAsString ()
  916. {
  917. string value = Value;
  918. do {
  919. switch (NodeType) {
  920. case XmlNodeType.Element:
  921. case XmlNodeType.EndElement:
  922. return value;
  923. case XmlNodeType.Text:
  924. value += Value;
  925. break;
  926. }
  927. } while (Read ());
  928. return value;
  929. }
  930. #region read typed content
  931. public override int ReadContentAsInt ()
  932. {
  933. int ret = GetIntValue ();
  934. Read ();
  935. return ret;
  936. }
  937. int GetIntValue ()
  938. {
  939. switch (node.ValueType) {
  940. case BF.Zero:
  941. return 0;
  942. case BF.One:
  943. return 1;
  944. case BF.Int8:
  945. return (byte) current.TypedValue;
  946. case BF.Int16:
  947. return (short) current.TypedValue;
  948. case BF.Int32:
  949. return (int) current.TypedValue;
  950. }
  951. throw new InvalidOperationException ("Current content is not an integer");
  952. }
  953. public override long ReadContentAsLong ()
  954. {
  955. if (node.ValueType == BF.Int64) {
  956. long v = (long) current.TypedValue;
  957. Read ();
  958. return v;
  959. }
  960. return ReadContentAsInt ();
  961. }
  962. public override float ReadContentAsFloat ()
  963. {
  964. if (node.ValueType != BF.Single)
  965. throw new InvalidOperationException ("Current content is not a single");
  966. float v = (float) current.TypedValue;
  967. Read ();
  968. return v;
  969. }
  970. public override double ReadContentAsDouble ()
  971. {
  972. if (node.ValueType != BF.Double)
  973. throw new InvalidOperationException ("Current content is not a double");
  974. double v = (double) current.TypedValue;
  975. Read ();
  976. return v;
  977. }
  978. bool IsBase64Node (byte b)
  979. {
  980. switch (b) {
  981. case BF.Bytes8:
  982. case BF.Bytes16:
  983. case BF.Bytes32:
  984. return true;
  985. }
  986. return false;
  987. }
  988. // FIXME: this is not likely to consume sequential base64 nodes.
  989. public override byte [] ReadContentAsBase64 ()
  990. {
  991. byte [] ret = null;
  992. if (!IsBase64Node (node.ValueType))
  993. throw new InvalidOperationException ("Current content is not base64");
  994. while (NodeType == XmlNodeType.Text && IsBase64Node (node.ValueType)) {
  995. if (ret == null)
  996. ret = (byte []) node.TypedValue;
  997. else {
  998. byte [] tmp = (byte []) node.TypedValue;
  999. byte [] tmp2 = new byte [ret.Length + tmp.Length];
  1000. Array.Copy (ret, tmp2, ret.Length);
  1001. Array.Copy (tmp, 0, tmp2, ret.Length, tmp.Length);
  1002. ret = tmp2;
  1003. }
  1004. Read ();
  1005. //MoveToContent ();
  1006. }
  1007. return ret;
  1008. }
  1009. public override Guid ReadContentAsGuid ()
  1010. {
  1011. if (node.ValueType != BF.Guid)
  1012. throw new InvalidOperationException ("Current content is not a Guid");
  1013. Guid ret = (Guid) node.TypedValue;
  1014. Read ();
  1015. return ret;
  1016. }
  1017. public override UniqueId ReadContentAsUniqueId ()
  1018. {
  1019. switch (node.ValueType) {
  1020. case BF.Chars8:
  1021. case BF.Chars16:
  1022. case BF.Chars32:
  1023. case BF.Utf16_8:
  1024. case BF.Utf16_16:
  1025. case BF.Utf16_32:
  1026. UniqueId ret = new UniqueId (node.Value);
  1027. Read ();
  1028. return ret;
  1029. case BF.UniqueId:
  1030. ret = (UniqueId) node.TypedValue;
  1031. Read ();
  1032. return ret;
  1033. default:
  1034. throw new InvalidOperationException ("Current content is not a UniqueId");
  1035. }
  1036. }
  1037. #endregion
  1038. }
  1039. }