File: XmlBinaryDictionaryReader.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (1197 lines) | stat: -rw-r--r-- 31,954 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
//
// XmlBinaryDictionaryReader.cs
//
// Author:
//	Atsushi Enomoto  <atsushi@ximian.com>
//
// Copyright (C) 2005, 2007 Novell, Inc.  http://www.novell.com
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;

using QName = System.Xml.XmlQualifiedName;
using BF = System.Xml.XmlBinaryFormat;

namespace System.Xml
{
	// FIXME:
	//	- support XmlDictionaryReaderQuotas.

	internal class XmlBinaryDictionaryReader : XmlDictionaryReader, IXmlNamespaceResolver
	{
		internal interface ISource
		{
			int Position { get; }
			int ReadByte ();
			int Read (byte [] data, int offset, int count);
			BinaryReader Reader { get; }
		}

		internal class StreamSource : ISource
		{
			BinaryReader reader;

			public StreamSource (Stream stream)
			{
				this.reader = new BinaryReader (stream);
			}

			public int Position {
				get { return (int) reader.BaseStream.Position; }
			}

			public BinaryReader Reader {
				get { return reader; }
			}

			public int ReadByte ()
			{
				return reader.BaseStream.ReadByte ();
			}

			public int Read (byte [] data, int offset, int count)
			{
				return reader.BaseStream.Read (data, offset, count);
			}
		}

		class NodeInfo
		{
			public NodeInfo ()
			{
			}

			public NodeInfo (bool isAttr)
			{
				IsAttributeValue = isAttr;
			}

			public bool IsAttributeValue;
			public int Position;
			public string Prefix;
			public XmlDictionaryString DictLocalName;
			public XmlDictionaryString DictNS;
			public XmlDictionaryString DictValue; // BF.TextIndex
			public XmlNodeType NodeType;
			public object TypedValue;
			public byte ValueType;

			// -1 for nothing,
			// -2 for that of element (only for attribute),
			// 0 or more to fill later
			public int NSSlot;

			string name = String.Empty;
			string local_name = String.Empty;
			string ns = String.Empty;
			string value;

			public string LocalName {
				get { return DictLocalName != null ? DictLocalName.Value : local_name; }
				set {
					DictLocalName = null;
					local_name = value;
				}
			}

			public string NS {
				get { return DictNS != null ? DictNS.Value : ns; }
				set {
					DictNS = null;
					ns = value;
				}
			}

			public string Name {
				get {
					if (name.Length == 0)
						name = Prefix.Length > 0 ?
							String.Concat (Prefix, ":", LocalName) :
							LocalName;
					return name;
				}
			}

			public virtual string Value {
				get {
					switch (ValueType) {
					case 0:
					case BF.Comment:
					case BF.Chars8:
					case BF.Chars16:
					case BF.Chars32:
					case BF.EmptyText:
					case BF.Utf16_8:
					case BF.Utf16_16:
					case BF.Utf16_32:
						return value;
					case BF.TextIndex:
						return DictValue.Value;
					case BF.Zero:
						return "0";
					case BF.One:
						return "1";
					case BF.BoolTrue:
						return "true";
					case BF.BoolFalse:
						return "false";
					case BF.Int8:
						return XmlConvert.ToString ((byte) TypedValue);
					case BF.Int16:
						return XmlConvert.ToString ((short) TypedValue);
					case BF.Int32:
						return XmlConvert.ToString ((int) TypedValue);
					case BF.Int64:
						return XmlConvert.ToString ((long) TypedValue);
					case BF.Single:
						return XmlConvert.ToString ((float) TypedValue);
					case BF.Double:
						return XmlConvert.ToString ((double) TypedValue);
					case BF.Decimal:
						return XmlConvert.ToString ((decimal) TypedValue);
					case BF.DateTime:
						return XmlConvert.ToString ((DateTime) TypedValue, XmlDateTimeSerializationMode.RoundtripKind);
					case BF.TimeSpan:
						return XmlConvert.ToString ((TimeSpan) TypedValue);
					case BF.Guid:
						return XmlConvert.ToString ((Guid) TypedValue);
					case BF.UniqueId:
						return TypedValue.ToString ();
					case BF.Bytes8:
					case BF.Bytes16:
					case BF.Bytes32:
						return Convert.ToBase64String ((byte []) TypedValue);
					case BF.QNameIndex:
						return Name;
					default:
						throw new NotImplementedException ("ValueType " + ValueType + " on node " + NodeType);
					}
				}
				set { this.value = value; }
			}

			public virtual void Reset ()
			{
				Position = 0;
				DictLocalName = DictNS = null;
				LocalName = NS = Prefix = Value = name = String.Empty;
				NodeType = XmlNodeType.None;
				TypedValue = null;
				ValueType = 0;
				NSSlot = -1;
			}
		}

		class AttrNodeInfo : NodeInfo
		{
			public AttrNodeInfo (XmlBinaryDictionaryReader owner)
			{
				this.owner = owner;
			}

			XmlBinaryDictionaryReader owner;
			public int ValueIndex;

			public override void Reset ()
			{
				base.Reset ();
				ValueIndex = -1;
				NodeType = XmlNodeType.Attribute;
			}

			public override string Value {
				get { return owner.attr_values [ValueIndex].Value; }
			}
		}

		ISource source;
		IXmlDictionary dictionary;
		XmlDictionaryReaderQuotas quota;
		XmlBinaryReaderSession session;
		OnXmlDictionaryReaderClose on_close;
		XmlParserContext context;

		ReadState state = ReadState.Initial;
		NodeInfo node;
		NodeInfo current;
		List<AttrNodeInfo> attributes = new List<AttrNodeInfo> ();
		List<NodeInfo> attr_values = new List<NodeInfo> ();
		List<NodeInfo> node_stack = new List<NodeInfo> ();
		List<QName> ns_store = new List<QName> ();
		Dictionary<int,XmlDictionaryString> ns_dict_store =
			new Dictionary<int,XmlDictionaryString> ();
		int attr_count;
		int attr_value_count;
		int current_attr = -1;
		int depth = 0;
		// used during Read()
		int ns_slot;
		// next byte in the source (one byte token ahead always
		// happens because there is no "end of start element" mark).
		int next = -1;
		bool is_next_end_element;
		// temporary buffer for utf8enc.GetString()
		byte [] tmp_buffer = new byte [128];
		UTF8Encoding utf8enc = new UTF8Encoding ();

		// See comment at Read()
		int array_item_remaining;
		byte array_item_type;
		XmlNodeType array_state;

		public XmlBinaryDictionaryReader (byte [] buffer, int offset,
			int count, IXmlDictionary dictionary,
			XmlDictionaryReaderQuotas quota,
			XmlBinaryReaderSession session,
			OnXmlDictionaryReaderClose onClose)
		{
			source = /*new ArraySource (buffer, offset, count);*/
				new StreamSource (new MemoryStream (buffer, offset, count));
			Initialize (dictionary, quota, session, onClose);
		}

		public XmlBinaryDictionaryReader (Stream stream,
			IXmlDictionary dictionary,
			XmlDictionaryReaderQuotas quota,
			XmlBinaryReaderSession session,
			OnXmlDictionaryReaderClose onClose)
		{
			source = new StreamSource (stream);
			Initialize (dictionary, quota, session, onClose);
		}

		private void Initialize (IXmlDictionary dictionary,
			XmlDictionaryReaderQuotas quotas,
			XmlBinaryReaderSession session,
			OnXmlDictionaryReaderClose onClose)
		{
			if (quotas == null)
				throw new ArgumentNullException ("quotas");
			if (dictionary == null)
				dictionary = new XmlDictionary ();
			this.dictionary = dictionary;

			this.quota = quotas;

			if (session == null)
				session = new XmlBinaryReaderSession ();
			this.session = session;

			on_close = onClose;
			NameTable nt = new NameTable ();
			this.context = new XmlParserContext (nt,
				new XmlNamespaceManager (nt),
				null, XmlSpace.None);

			current = node = new NodeInfo ();
			current.Reset ();
			node_stack.Add (node);
		}

		public override int AttributeCount {
			get { return attr_count; }
		}

		public override string BaseURI {
			get { return context.BaseURI; }
		}

		public override int Depth {
			get { return current == node ? depth : NodeType == XmlNodeType.Attribute ? depth + 1 : depth + 2; }
		}

		public override bool EOF {
			get { return state == ReadState.EndOfFile || state == ReadState.Error; }
		}

		public override bool HasValue {
			get { return Value.Length > 0; }
		}

		public override bool IsEmptyElement {
			get { return false; }
		}

		public override XmlNodeType NodeType {
			get { return current.NodeType; }
		}

		public override string Prefix {
			get { return current_attr >= 0 ? attributes [current_attr].Prefix : current.Prefix; }
		}

		// looks like it may return attribute's name even if it is on its value node.
		public override string LocalName {
			get { return current_attr >= 0 ? attributes [current_attr].LocalName : current.LocalName; }
		}

		public override string Name {
			get { return current_attr >= 0 ? attributes [current_attr].Name : current.Name; }
		}

		public override string NamespaceURI {
			get { return current_attr >= 0 ? attributes [current_attr].NS : current.NS; }
		}

		public override XmlNameTable NameTable {
			get { return context.NameTable; }
		}

		public override XmlDictionaryReaderQuotas Quotas {
			get { return quota; }
		}

		public override ReadState ReadState {
			get { return state; }
		}

		public override string Value {
			get { return current.Value; }
		}

		public override void Close ()
		{
			if (on_close != null)
				on_close (this);
		}

		public override string GetAttribute (int i)
		{
			if (i >= attr_count)
				throw new ArgumentOutOfRangeException (String.Format ("Specified attribute index is {0} and should be less than {1}", i, attr_count));
			return attributes [i].Value;
		}

		public override string GetAttribute (string name)
		{
			for (int i = 0; i < attr_count; i++)
				if (attributes [i].Name == name)
					return attributes [i].Value;
			return null;
		}

		public override string GetAttribute (string localName, string ns)
		{
			for (int i = 0; i < attr_count; i++)
				if (attributes [i].LocalName == localName &&
					attributes [i].NS == ns)
					return attributes [i].Value;
			return null;
		}

		public IDictionary<string,string> GetNamespacesInScope (
			XmlNamespaceScope scope)
		{
			return context.NamespaceManager.GetNamespacesInScope (scope);
		}

		public string LookupPrefix (string ns)
		{
			return context.NamespaceManager.LookupPrefix (NameTable.Get (ns));
		}

		public override string LookupNamespace (string prefix)
		{
			return context.NamespaceManager.LookupNamespace (
				NameTable.Get (prefix));
		}

		public override bool IsArray (out Type type)
		{
			if (array_state == XmlNodeType.Element) {
				type = GetArrayType (array_item_type);
				return true;
			} else {
				type = null;
				return false;
			}
		}

		public override bool MoveToElement ()
		{
			bool ret = current_attr >= 0;
			current_attr = -1;
			current = node;
			return ret;
		}

		public override bool MoveToFirstAttribute ()
		{
			if (attr_count == 0)
				return false;
			current_attr = 0;
			current = attributes [current_attr];
			return true;
		}

		public override bool MoveToNextAttribute ()
		{
			if (++current_attr < attr_count) {
				current = attributes [current_attr];
				return true;
			} else {
				--current_attr;
				return false;
			}
		}

		public override void MoveToAttribute (int i)
		{
			if (i >= attr_count)
				throw new ArgumentOutOfRangeException (String.Format ("Specified attribute index is {0} and should be less than {1}", i, attr_count));
			current_attr = i;
			current = attributes [i];
		}

		public override bool MoveToAttribute (string name)
		{
			for (int i = 0; i < attributes.Count; i++) {
				if (attributes [i].Name == name) {
					MoveToAttribute (i);
					return true;
				}
			}
			return false;
		}

		public override bool MoveToAttribute (string localName, string ns)
		{
			for (int i = 0; i < attributes.Count; i++) {
				if (attributes [i].LocalName == localName &&
					attributes [i].NS == ns) {
					MoveToAttribute (i);
					return true;
				}
			}
			return false;
		}

		public override bool ReadAttributeValue ()
		{
			if (current_attr < 0)
				return false;
			int start = attributes [current_attr].ValueIndex;
			int end = current_attr + 1 == attr_count ? attr_value_count : attributes [current_attr + 1].ValueIndex;
			if (start == end)
				return false;
			if (!current.IsAttributeValue) {
				current = attr_values [start];
				return true;
			}
			// Actually there is no case for attribute whose value is split to more than two nodes. We could simplify the node structure.
			return false;
		}

		// When reading an array (0x03), it requires extraneously
		// complex procedure for XmlReader. First, it reads element,
		// type of operation and length of the items. And this XmlReader
		// has to return Element state. On the next Read(), it proceeds
		// to the value node of the first item of the array, so it
		// reads the value stream. On the next Read(), it proceeds to
		// EndElement, so it should not read anything from stream while
		// it has to move to the node state to EndElement.
		public override bool Read ()
		{
			switch (state) {
			case ReadState.Closed:
			case ReadState.EndOfFile:
			case ReadState.Error:
				return false;
			}

			// clear.
			state = ReadState.Interactive;
			MoveToElement ();
			attr_count = 0;
			attr_value_count = 0;
			ns_slot = 0;

			if (node.NodeType == XmlNodeType.Element) {
				// push element scope
				if (node_stack.Count <= ++depth) {
					if (depth == quota.MaxDepth)
						throw new XmlException (String.Format ("Binary XML stream quota exceeded. Depth must be less than {0}", quota.MaxDepth));
					node = new NodeInfo ();
					node_stack.Add (node);
				} else {
					node = node_stack [depth]; // reuse
					node.Reset ();
				}
			}
			current = node;

			if (is_next_end_element) {
				is_next_end_element = false;
				node.Reset ();
				ProcessEndElement ();
				return true;
			}

			// process array node after preparing node stack.
			switch (array_state) {
			case XmlNodeType.Element:
				ReadArrayItem ();
				return true;
			case XmlNodeType.Text:
				ShiftToArrayItemEndElement ();
				return true;
			case XmlNodeType.EndElement:
				if (--array_item_remaining == 0) {
					array_state = XmlNodeType.None;
					break;
				} else {
					ShiftToArrayItemElement ();
					return true;
				}
			}

			// array consumer does not expect Reset whlie it's on reading. So call it later than array check.
			node.Reset ();

			int ident = next >= 0 ? next : source.ReadByte ();
			next = -1;

			// check end of source.
			if (ident < 0) {
				state = ReadState.EndOfFile;
				current.Reset ();
				return false;
			}

			is_next_end_element = ident > 0x80 && (ident & 1) == 1;
			ident -= is_next_end_element ? 1 : 0;

			switch (ident) {
			case BF.EndElement:
				ProcessEndElement ();
				break;
			case BF.Comment:
				node.Value = ReadUTF8 ();
				node.ValueType = BF.Comment;
				node.NodeType = XmlNodeType.Comment;
				break;
			case BF.ElemString:
			case BF.ElemStringPrefix:
			case BF.ElemIndex:
			case BF.ElemIndexPrefix:
				ReadElementBinary ((byte) ident);
				break;

			case BF.Array:
				ident = ReadByteOrError ();
				ReadElementBinary ((byte) ident);
				ident = ReadByteOrError ();
				if (ident != 0x01)
					throw new XmlException (String.Format ("EndElement is expected after element in an array. The actual byte was {0:X} in hexadecimal", ident));
				ident = ReadByteOrError () - 1; // -1 becauseit contains EndElement
				VerifyValidArrayItemType (ident);
				if (ident < 0)
					throw new XmlException ("The stream has ended where the array item type is expected");
				array_item_type = (byte) ident;
				array_item_remaining = ReadVariantSize ();
				if (array_item_remaining > quota.MaxArrayLength)
					throw new Exception (String.Format ("Binary xml stream exceeded max array length quota. Items are {0} and should be less than quota.MaxArrayLength", quota.MaxArrayLength));
				array_state = XmlNodeType.Element;
				break;

			default:
				if (BF.PrefixNElemIndexStart <= ident && ident <= BF.PrefixNElemIndexEnd ||
				    BF.PrefixNElemStringStart <= ident && ident <= BF.PrefixNElemStringEnd)
					goto case BF.ElemString;
				ReadTextOrValue ((byte) ident, node, false);
				break;
			}

			return true;
		}

		void ReadArrayItem ()
		{
			ReadTextOrValue (array_item_type, node, false);
			array_state = XmlNodeType.Text;
		}

		void ShiftToArrayItemEndElement ()
		{
			ProcessEndElement ();
			array_state = XmlNodeType.EndElement;
		}

		void ShiftToArrayItemElement ()
		{
			node.NodeType = XmlNodeType.Element;
			context.NamespaceManager.PushScope ();
			array_state = XmlNodeType.Element;
		}

		void VerifyValidArrayItemType (int ident)
		{
			if (GetArrayType (ident) == null)
				throw new XmlException (String.Format ("Unexpected array item type {0:X} in hexadecimal", ident));
		}
		
		Type GetArrayType (int ident)
		{
			switch (ident) {
			case BF.Bool:
				return typeof (bool);
			case BF.Int16:
				return typeof (short);
			case BF.Int32:
				return typeof (int);
			case BF.Int64:
				return typeof (long);
			case BF.Single:
				return typeof (float);
			case BF.Double:
				return typeof (double);
			case BF.Decimal:
				return typeof (decimal);
			case BF.DateTime:
				return typeof (DateTime);
			case BF.TimeSpan:
				return typeof (TimeSpan);
			case BF.Guid:
				return typeof (Guid);
			}
			return null;
		}

		private void ProcessEndElement ()
		{
			if (depth == 0)
				throw new XmlException ("Unexpected end of element while there is no element started.");
			current = node = node_stack [--depth];
			node.NodeType = XmlNodeType.EndElement;
			context.NamespaceManager.PopScope ();
		}

		private void ReadElementBinary (int ident)
		{
			// element
			node.NodeType = XmlNodeType.Element;
			node.Prefix = String.Empty;
			context.NamespaceManager.PushScope ();
			switch (ident) {
			case BF.ElemString:
				node.LocalName = ReadUTF8 ();
				break;
			case BF.ElemStringPrefix:
				node.Prefix = ReadUTF8 ();
				node.NSSlot = ns_slot++;
				goto case BF.ElemString;
			case BF.ElemIndex:
				node.DictLocalName = ReadDictName ();
				break;
			case BF.ElemIndexPrefix:
				node.Prefix = ReadUTF8 ();
				node.NSSlot = ns_slot++;
				goto case BF.ElemIndex;
			default:
				if (BF.PrefixNElemIndexStart <= ident && ident <= BF.PrefixNElemIndexEnd) {
					node.Prefix = ((char) (ident - BF.PrefixNElemIndexStart + 'a')).ToString ();
					node.DictLocalName = ReadDictName ();
				} else if (BF.PrefixNElemStringStart <= ident && ident <= BF.PrefixNElemStringEnd) {
					node.Prefix = ((char) (ident - BF.PrefixNElemStringStart + 'a')).ToString ();
					node.LocalName = ReadUTF8 ();
				}
				else
					throw new XmlException (String.Format ("Invalid element node type {0:X02} in hexadecimal", ident));
				break;
			}

			bool loop = true;
			do {
				ident = ReadByteOrError ();

				switch (ident) {
				case BF.AttrString:
				case BF.AttrStringPrefix:
				case BF.AttrIndex:
				case BF.AttrIndexPrefix:
					ReadAttribute ((byte) ident);
					break;
				case BF.DefaultNSString:
				case BF.PrefixNSString:
				case BF.DefaultNSIndex:
				case BF.PrefixNSIndex:
					ReadNamespace ((byte) ident);
					break;
				default:
					if (BF.PrefixNAttrStringStart <= ident && ident <= BF.PrefixNAttrStringEnd ||
					    BF.PrefixNAttrIndexStart <= ident && ident <= BF.PrefixNAttrIndexEnd)
						ReadAttribute ((byte) ident);
					else {
						next = ident;
						loop = false;
					}
					break;
				}
			} while (loop);

			node.NS = context.NamespaceManager.LookupNamespace (node.Prefix) ?? String.Empty;
			foreach (AttrNodeInfo a in attributes)
				if (a.Prefix.Length > 0)
					a.NS = context.NamespaceManager.LookupNamespace (a.Prefix);

			ns_store.Clear ();
			ns_dict_store.Clear ();
		}

		private void ReadAttribute (byte ident)
		{
			if (attributes.Count == attr_count)
				attributes.Add (new AttrNodeInfo (this));
			AttrNodeInfo a = attributes [attr_count++];
			a.Reset ();
			a.Position = source.Position;

			switch (ident) {
			case BF.AttrString:
				a.LocalName = ReadUTF8 ();
				break;
			case BF.AttrStringPrefix:
				a.Prefix = ReadUTF8 ();
				a.NSSlot = ns_slot++;
				goto case BF.AttrString;
			case BF.AttrIndex:
				a.DictLocalName = ReadDictName ();
				break;
			case BF.AttrIndexPrefix:
				a.Prefix = ReadUTF8 ();
				a.NSSlot = ns_slot++;
				goto case BF.AttrIndex;
			default:
				if (BF.PrefixNAttrStringStart <= ident && ident <= BF.PrefixNAttrStringEnd) {
					a.Prefix = ((char) ('a' + ident - BF.PrefixNAttrStringStart)).ToString ();
					a.LocalName = ReadUTF8 ();
					break;
				}
				else if (BF.PrefixNAttrIndexStart <= ident && ident <= BF.PrefixNAttrIndexEnd) {
					a.Prefix = ((char) ('a' + ident - BF.PrefixNAttrIndexStart)).ToString ();
					a.DictLocalName = ReadDictName ();
					break;
				}
				else throw new XmlException (String.Format ("Unexpected attribute node type: 0x{0:X02}", ident));
			}
			ReadAttributeValueBinary (a);
		}

		private void ReadNamespace (byte ident)
		{
			// create attrubute slot.
			if (attributes.Count == attr_count)
				attributes.Add (new AttrNodeInfo (this));
			AttrNodeInfo a = attributes [attr_count++];
			a.Reset ();
			a.Position = source.Position;

			string prefix = null, ns = null;
			XmlDictionaryString dns = null;

			switch (ident) {
			case BF.DefaultNSString:
				prefix = String.Empty;
				ns = ReadUTF8 ();
				break;
			case BF.PrefixNSString:
				prefix = ReadUTF8 ();
				ns = ReadUTF8 ();
				break;
			case BF.DefaultNSIndex:
				prefix = String.Empty;
				dns = ReadDictName ();
				ns_dict_store.Add (ns_store.Count, dns);
				ns = dns.Value;
				break;
			case BF.PrefixNSIndex:
				prefix = ReadUTF8 ();
				dns = ReadDictName ();
				ns_dict_store.Add (ns_store.Count, dns);
				ns = dns.Value;
				break;
			}

			// fill attribute slot.
			a.Prefix = prefix.Length > 0 ? "xmlns" : String.Empty;
			a.LocalName = prefix.Length > 0 ? prefix : "xmlns";
			a.NS = "http://www.w3.org/2000/xmlns/";
			a.ValueIndex = attr_value_count;
			if (attr_value_count == attr_values.Count)
				attr_values.Add (new NodeInfo (true));
			NodeInfo v = attr_values [attr_value_count++];
			v.Reset ();
			v.Value = ns;
			v.ValueType = BF.Chars8;
			v.NodeType = XmlNodeType.Text;

			ns_store.Add (new QName (prefix, ns));
			context.NamespaceManager.AddNamespace (prefix, ns);
		}

		private void ReadAttributeValueBinary (AttrNodeInfo a)
		{
			a.ValueIndex = attr_value_count;
			if (attr_value_count == attr_values.Count)
				attr_values.Add (new NodeInfo (true));
			NodeInfo v = attr_values [attr_value_count++];
			v.Reset ();
			int ident = ReadByteOrError ();
			bool end = ident > 0x80 && (ident & 1) == 1;
			ident -= end ? 1 : 0;
			ReadTextOrValue ((byte) ident, v, true);
		}

		private bool ReadTextOrValue (byte ident, NodeInfo node, bool canSkip)
		{
			node.Value = null;
			node.ValueType = ident;
			node.NodeType = XmlNodeType.Text;
			switch (ident) {
			case BF.Zero:
				node.TypedValue = 0;
				break;
			case BF.One:
				node.TypedValue = 1;
				break;
			case BF.BoolFalse:
				node.TypedValue = false;
				break;
			case BF.BoolTrue:
				node.TypedValue = true;
				break;
			case BF.Int8:
				node.TypedValue = ReadByteOrError ();
				break;
			case BF.Int16:
				node.TypedValue = source.Reader.ReadInt16 ();
				break;
			case BF.Int32:
				node.TypedValue = source.Reader.ReadInt32 ();
				break;
			case BF.Int64:
				node.TypedValue = source.Reader.ReadInt64 ();
				break;
			case BF.Single:
				node.TypedValue = source.Reader.ReadSingle ();
				break;
			case BF.Double:
				node.TypedValue = source.Reader.ReadDouble ();
				break;
			case BF.Decimal:
				int [] bits = new int [4];
				bits [3] = source.Reader.ReadInt32 ();
				bits [2] = source.Reader.ReadInt32 ();
				bits [0] = source.Reader.ReadInt32 ();
				bits [1] = source.Reader.ReadInt32 ();
				node.TypedValue = new Decimal (bits);
				break;
			case BF.DateTime:
				node.TypedValue = DateTime.FromBinary (source.Reader.ReadInt64 ());
				break;
			//case BF.UniqueId: // identical to .Text
			case BF.Bytes8:
			case BF.Bytes16:
			case BF.Bytes32:
				int size =
					(ident == BF.Bytes8) ? source.Reader.ReadByte () :
					(ident == BF.Bytes16) ? source.Reader.ReadUInt16 () :
					source.Reader.ReadInt32 ();
				byte [] base64 = Alloc (size);
				source.Reader.Read (base64, 0, base64.Length);
				node.TypedValue = base64;
				break;
			case BF.TimeSpan:
				node.TypedValue = new TimeSpan (source.Reader.ReadInt64 ());
				break;
			case BF.UniqueId:
				byte [] guid = new byte [16];
				source.Reader.Read (guid, 0, guid.Length);
				node.TypedValue = new UniqueId (new Guid (guid));
				break;
			case BF.Guid:
				guid = new byte [16];
				source.Reader.Read (guid, 0, guid.Length);
				node.TypedValue = new Guid (guid);
				break;
			case BF.Chars8:
			case BF.Chars16:
			case BF.Chars32:
			case BF.Utf16_8:
			case BF.Utf16_16:
			case BF.Utf16_32:
				Encoding enc = ident <= BF.Chars32 ? Encoding.UTF8 : Encoding.Unicode;
				size =
					(ident == BF.Chars8 || ident == BF.Utf16_8) ? source.Reader.ReadByte () :
					(ident == BF.Chars16 || ident == BF.Utf16_16) ? source.Reader.ReadUInt16 () :
					source.Reader.ReadInt32 ();
				byte [] bytes = Alloc (size);
				source.Reader.Read (bytes, 0, size);
				node.Value = enc.GetString (bytes, 0, size);
				node.NodeType = XmlNodeType.Text;
				break;
			case BF.EmptyText:
				node.Value = String.Empty;
				node.NodeType = XmlNodeType.Text;
				break;
			case BF.TextIndex:
				node.DictValue = ReadDictName ();
				node.NodeType = XmlNodeType.Text;
				break;
			case BF.QNameIndex:
				node.Prefix = ((char) (ReadByteOrError () + 'a')).ToString ();
				node.DictLocalName = ReadDictName();
				break;	
			default:
				if (!canSkip)
					throw new ArgumentException (String.Format ("Unexpected binary XML data at position {1}: {0:X}", ident + (is_next_end_element ? 1 : 0), source.Position));
				next = ident;
				return false;
			}
			return true;
		}

		byte [] Alloc (int size)
		{
			if (size > quota.MaxStringContentLength || size < 0)
				throw new XmlException (String.Format ("Text content buffer exceeds the quota limitation at {2}. {0} bytes and should be less than {1} bytes", size, quota.MaxStringContentLength, source.Position));
			return new byte [size];
		}

		private int ReadVariantSize ()
		{
			int size = 0;
			// If sizeSpec < 0, then it is variant size specifier.
			// Otherwise it is fixed size s = sizeSpec + 1 byte(s).
			int d = 0;
			do {
				byte got = ReadByteOrError ();
				size += (got & 0x7F) << d;
				d += 7;
				if (got < 0x80)
					break;
			} while (true);
			return size;
		}

		private string ReadUTF8 ()
		{
			int size = ReadVariantSize ();
			if (size == 0)
				return String.Empty;
			if (tmp_buffer.Length < size) {
				int extlen = tmp_buffer.Length * 2;
				tmp_buffer = Alloc (size < extlen ? extlen : size);
			}
			size = source.Read (tmp_buffer, 0, size);
			return utf8enc.GetString (tmp_buffer, 0, size);
		}

		private XmlDictionaryString ReadDictName ()
		{
			int key = ReadVariantSize ();
			XmlDictionaryString s;
			if ((key & 1) == 1) {
				if (session.TryLookup (key >> 1, out s))
					return s;
			} else {
				if (dictionary.TryLookup (key >> 1, out s))
					return s;
			}
			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));
		}

		private byte ReadByteOrError ()
		{
			if (next >= 0) {
				byte b = (byte) next;
				next = -1;
				return b;
			}
			int ret = source.ReadByte ();
			if (ret < 0)
				throw new XmlException (String.Format ("Unexpected end of binary stream. Position is at {0}", source.Position));
			return (byte) ret;
		}

		public override void ResolveEntity ()
		{
			throw new NotSupportedException ("this XmlReader does not support ResolveEntity.");
		}

		public override bool TryGetBase64ContentLength (out int length)
		{
			length = 0;
			switch (current.ValueType) {
			case BF.Bytes8:
			case BF.Bytes16:
			case BF.Bytes32:
				length = ((byte []) current.TypedValue).Length;
				return true;
			}
			return false;
		}

		public override string ReadContentAsString ()
		{
			string value = String.Empty;
			do {
				switch (NodeType) {
				case XmlNodeType.Element:
				case XmlNodeType.EndElement:
					return value;
				case XmlNodeType.Text:
					value += Value;
					break;
				}
			} while (Read ());
			return value;
		}

		#region read typed content

		public override int ReadContentAsInt ()
		{
			int ret = GetIntValue ();
			Read ();
			return ret;
		}
		
		int GetIntValue ()
		{
			switch (node.ValueType) {
			case BF.Zero:
				return 0;
			case BF.One:
				return 1;
			case BF.Int8:
				return (byte) current.TypedValue;
			case BF.Int16:
				return (short) current.TypedValue;
			case BF.Int32:
				return (int) current.TypedValue;
			}
			throw new InvalidOperationException (String.Format ("Current content is not an integer. (Internal value type:{0:X02})", (int) node.ValueType));
		}

		public override long ReadContentAsLong ()
		{
			if (node.ValueType == BF.Int64) {
				long v = (long) current.TypedValue;
				Read ();
				return v;
			}
			return ReadContentAsInt ();
		}

		public override float ReadContentAsFloat ()
		{
			if (node.ValueType != BF.Single)
				throw new InvalidOperationException ("Current content is not a single");
			float v = (float) current.TypedValue;
			Read ();
			return v;
		}

		public override double ReadContentAsDouble ()
		{
			if (node.ValueType != BF.Double)
				throw new InvalidOperationException ("Current content is not a double");
			double v = (double) current.TypedValue;
			Read ();
			return v;
		}

		bool IsBase64Node (byte b)
		{
			switch (b) {
			case BF.Bytes8:
			case BF.Bytes16:
			case BF.Bytes32:
				return true;
			}
			return false;
		}

		// FIXME: this is not likely to consume sequential base64 nodes.
		public override byte [] ReadContentAsBase64 ()
		{
			byte [] ret = null;
			if (!IsBase64Node (node.ValueType))
				throw new InvalidOperationException ("Current content is not base64");

			while (NodeType == XmlNodeType.Text && IsBase64Node (node.ValueType)) {
				if (ret == null)
					ret = (byte []) node.TypedValue;
				else {
					byte [] tmp = (byte []) node.TypedValue;
					byte [] tmp2 = Alloc (ret.Length + tmp.Length);
					Array.Copy (ret, tmp2, ret.Length);
					Array.Copy (tmp, 0, tmp2, ret.Length, tmp.Length);
					ret = tmp2;
				}
				Read ();
				//MoveToContent ();
			}
			return ret;
		}

		public override Guid ReadContentAsGuid ()
		{
			if (node.ValueType != BF.Guid)
				throw new InvalidOperationException ("Current content is not a Guid");
			Guid ret = (Guid) node.TypedValue;
			Read ();
			return ret;
		}

		public override UniqueId ReadContentAsUniqueId ()
		{
			switch (node.ValueType) {
			case BF.Chars8:
			case BF.Chars16:
			case BF.Chars32:
			case BF.Utf16_8:
			case BF.Utf16_16:
			case BF.Utf16_32:
				UniqueId ret = new UniqueId (node.Value);
				Read ();
				return ret;
			case BF.UniqueId:
				ret = (UniqueId) node.TypedValue;
				Read ();
				return ret;
			default:
				throw new InvalidOperationException ("Current content is not a UniqueId");
			}
		}

		#endregion
	}
}