summaryrefslogtreecommitdiff
path: root/mcs/class/System.XML/System.Xml/XmlInputStream.cs
blob: 457485172d3f57d1d09be2eb370af37a2591d33b (plain)
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
//
// System.Xml.XmlInputStream 
//	encoding-specification-wise XML input stream and reader
//
// Author:
//	Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
//
//	(C)2003 Atsushi Enomoto
//

//
// 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.IO;
using System.Text;
using System.Runtime.InteropServices;

namespace System.Xml
{
	#region XmlStreamReader
	internal class XmlStreamReader : NonBlockingStreamReader
	{
		XmlInputStream input;

		XmlStreamReader (XmlInputStream input)
			: base (input, input.ActualEncoding != null ? input.ActualEncoding : XmlInputStream.StrictUTF8)
		{
			this.input = input;
		}

		public XmlStreamReader (Stream input)
			: this (new XmlInputStream (input))
		{
		}

		public override void Close ()
		{
			this.input.Close ();
		}

		public override int Read ([In, Out] char[] dest_buffer, int index, int count)
		{
			try {
				return base.Read (dest_buffer, index, count);
			}
			catch (System.ArgumentException ex) {
				throw new XmlException ("Invalid data", ex);
			}
		}

		protected override void Dispose (bool disposing)
		{
			base.Dispose (disposing);
			if (disposing) {
				Close ();
			}
		}

	}
	#endregion

	#region NonBlockingStreamReader
	// mostly copied from StreamReader, removing BOM checks, ctor
	// parameter checks and some extra public members.
	internal class NonBlockingStreamReader : TextReader {

		const int DefaultBufferSize = 1024;
		const int DefaultFileBufferSize = 4096;
		const int MinimumBufferSize = 128;

		//
		// The input buffer
		//
		byte [] input_buffer;

		//
		// The decoded buffer from the above input buffer
		//
		char [] decoded_buffer;

		//
		// Decoded bytes in decoded_buffer.
		//
		int decoded_count;

		//
		// Current position in the decoded_buffer
		//
		int pos;

		//
		// The buffer size that we are using
		//
		int buffer_size;

		Encoding encoding;
		Decoder decoder;

		Stream base_stream;
		bool mayBlock;
		StringBuilder line_builder;

		public NonBlockingStreamReader(Stream stream, Encoding encoding)
		{
			int buffer_size = DefaultBufferSize;
			base_stream = stream;
			input_buffer = new byte [buffer_size];
			this.buffer_size = buffer_size;
			this.encoding = encoding;
			decoder = encoding.GetDecoder ();

			decoded_buffer = new char [encoding.GetMaxCharCount (buffer_size)];
			decoded_count = 0;
			pos = 0;
		}

		public Encoding Encoding {
			get { return encoding; }
		}

		public override void Close ()
		{
			Dispose (true);
		}

		protected override void Dispose (bool disposing)
		{
			if (disposing && base_stream != null)
				base_stream.Close ();
			
			input_buffer = null;
			decoded_buffer = null;
			encoding = null;
			decoder = null;
			base_stream = null;
			base.Dispose (disposing);
		}

		public void DiscardBufferedData ()
		{
			pos = decoded_count = 0;
			mayBlock = false;
#if NET_2_0
			decoder.Reset ();
#else
			decoder = encoding.GetDecoder ();
#endif
		}
		
		// the buffer is empty, fill it again
		private int ReadBuffer ()
		{
			pos = 0;
			int cbEncoded = 0;

			// keep looping until the decoder gives us some chars
			decoded_count = 0;
			int parse_start = 0;
			do	
			{
				cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
				
				if (cbEncoded == 0)
					return 0;

				mayBlock = (cbEncoded < buffer_size);
				decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
				parse_start = 0;
			} while (decoded_count == 0);

			return decoded_count;
		}

		public override int Peek ()
		{
			if (base_stream == null)
				throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
			if (pos >= decoded_count && (mayBlock || ReadBuffer () == 0))
				return -1;

			return decoded_buffer [pos];
		}

		public override int Read ()
		{
			if (base_stream == null)
				throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
			if (pos >= decoded_count && ReadBuffer () == 0)
				return -1;

			return decoded_buffer [pos++];
		}

		public override int Read ([In, Out] char[] dest_buffer, int index, int count)
		{
			if (base_stream == null)
				throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
			if (dest_buffer == null)
				throw new ArgumentNullException ("dest_buffer");
			if (index < 0)
				throw new ArgumentOutOfRangeException ("index", "< 0");
			if (count < 0)
				throw new ArgumentOutOfRangeException ("count", "< 0");
			// re-ordered to avoid possible integer overflow
			if (index > dest_buffer.Length - count)
				throw new ArgumentException ("index + count > dest_buffer.Length");

			int chars_read = 0;
//			while (count > 0)
			{
				if (pos >= decoded_count && ReadBuffer () == 0)
					return chars_read > 0 ? chars_read : 0;

				int cch = Math.Min (decoded_count - pos, count);
				Array.Copy (decoded_buffer, pos, dest_buffer, index, cch);
				pos += cch;
				index += cch;
				count -= cch;
				chars_read += cch;
			}
			return chars_read;
		}

		bool foundCR;
		int FindNextEOL ()
		{
			char c = '\0';
			for (; pos < decoded_count; pos++) {
				c = decoded_buffer [pos];
				if (c == '\n') {
					pos++;
					int res = (foundCR) ? (pos - 2) : (pos - 1);
					if (res < 0)
						res = 0; // if a new buffer starts with a \n and there was a \r at
							// the end of the previous one, we get here.
					foundCR = false;
					return res;
				} else if (foundCR) {
					foundCR = false;
					return pos - 1;
				}

				foundCR = (c == '\r');
			}

			return -1;
		}

		public override string ReadLine()
		{
			if (base_stream == null)
				throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");

			if (pos >= decoded_count && ReadBuffer () == 0)
				return null;

			int begin = pos;
			int end = FindNextEOL ();
			if (end < decoded_count && end >= begin)
				return new string (decoded_buffer, begin, end - begin);

			if (line_builder == null)
				line_builder = new StringBuilder ();
			else
				line_builder.Length = 0;

			while (true) {
				if (foundCR) // don't include the trailing CR if present
					decoded_count--;

				line_builder.Append (new string (decoded_buffer, begin, decoded_count - begin));
				if (ReadBuffer () == 0) {
					if (line_builder.Capacity > 32768) {
						StringBuilder sb = line_builder;
						line_builder = null;
						return sb.ToString (0, sb.Length);
					}
					return line_builder.ToString (0, line_builder.Length);
				}

				begin = pos;
				end = FindNextEOL ();
				if (end < decoded_count && end >= begin) {
					line_builder.Append (new string (decoded_buffer, begin, end - begin));
					if (line_builder.Capacity > 32768) {
						StringBuilder sb = line_builder;
						line_builder = null;
						return sb.ToString (0, sb.Length);
					}
					return line_builder.ToString (0, line_builder.Length);
				}
			}
		}

		public override string ReadToEnd()
		{
			if (base_stream == null)
				throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");

			StringBuilder text = new StringBuilder ();

			int size = decoded_buffer.Length;
			char [] buffer = new char [size];
			int len;
			
			while ((len = Read (buffer, 0, size)) != 0)
				text.Append (buffer, 0, len);

			return text.ToString ();
		}
	}
	#endregion

	class XmlInputStream : Stream
	{
		internal static readonly Encoding StrictUTF8, Strict1234UTF32, StrictBigEndianUTF16, StrictUTF16;

		static XmlInputStream ()
		{
			StrictUTF8 = new UTF8Encoding (false, true);
			Strict1234UTF32 = new UTF32Encoding (true, false, true);
			StrictBigEndianUTF16 = new UnicodeEncoding (true, false, true);
			StrictUTF16 = new UnicodeEncoding (false, false, true);
		}

		Encoding enc;
		Stream stream;
		byte[] buffer;
		int bufLength;
		int bufPos;

		static XmlException encodingException = new XmlException ("invalid encoding specification.");

		public XmlInputStream (Stream stream)
		{
			Initialize (stream);
		}

		// this returns null, instead of throwing ArgumentOutOfRangeException
		string GetStringFromBytes (int index, int count)
		{
			int posBak = bufPos;
			while (bufPos < index + count)
				if (ReadByteSpecial () < 0)
					return null;
			bufPos = posBak;
			return Encoding.ASCII.GetString (buffer, index, count);
		}

		private void Initialize (Stream stream)
		{
			buffer = new byte [6];
			this.stream = stream;
			enc = StrictUTF8; // Default to UTF8 if we can't guess it
			bufLength = stream.Read (buffer, 0, buffer.Length);
			if (bufLength == -1 || bufLength == 0) {
				return;
			}

			int c = ReadByteSpecial ();
			switch (c) {
			case 0xFF:
				c = ReadByteSpecial ();
				if (c == 0xFE) {
					// BOM-ed little endian utf-16
					enc = Encoding.Unicode;
				} else {
					// It doesn't start from "<?xml" then its encoding is utf-8
					bufPos = 0;
				}
				break;
			case 0xFE:
				c = ReadByteSpecial ();
				if (c == 0xFF) {
					// BOM-ed big endian utf-16
					enc = Encoding.BigEndianUnicode;
					return;
				} else {
					// It doesn't start from "<?xml" then its encoding is utf-8
					bufPos = 0;
				}
				break;
			case 0xEF:
				c = ReadByteSpecial ();
				if (c == 0xBB) {
					c = ReadByteSpecial ();
					if (c != 0xBF) {
						bufPos = 0;
					}
				} else {
					buffer [--bufPos] = 0xEF;
				}
				break;
			case 0:
				// It could still be 1234/2143/3412 variants of UTF32, but only 1234 version is available on .NET.
				c = ReadByteSpecial ();
				if (c == 0)
					enc = Strict1234UTF32;
				else
					enc = StrictBigEndianUTF16;
				break;
			case '<':
				c = ReadByteSpecial ();
				if (c == 0) {
					if (ReadByteSpecial () == 0)
						enc = Encoding.UTF32; // little endian UTF32
					else
						enc = Encoding.Unicode; // little endian UTF16
				} else if (bufLength >= 4 && GetStringFromBytes (1, 4) == "?xml") {
					// try to get encoding name from XMLDecl.
					bufPos += 4;
					c = SkipWhitespace ();

					// version. It is optional here.
					if (c == 'v') {
						while (c >= 0) {
							c = ReadByteSpecial ();
							if (c == '0') { // 0 of 1.0
								ReadByteSpecial ();
								break;
							}
						}
						c = SkipWhitespace ();
					}

					if (c == 'e') {
						if (GetStringFromBytes (bufPos, 7) == "ncoding") {
							bufPos += 7;
							c = SkipWhitespace();
							if (c != '=')
								throw encodingException;
							c = SkipWhitespace ();
							int quoteChar = c;
							StringBuilder sb = new StringBuilder ();
							while (true) {
								c = ReadByteSpecial ();
								if (c == quoteChar)
									break;
								else if (c < 0)
									throw encodingException;

								sb.Append ((char) c);
							}
							string encodingName = sb.ToString ();
							if (!XmlChar.IsValidIANAEncoding (encodingName))
								throw encodingException;
							enc = Encoding.GetEncoding (encodingName);
						}
					}
				}
#if TARGET_JVM
				else {
					if (bufLength >= 10 && Encoding.Unicode.GetString (buffer, 2, 8) == "?xml")
						enc = Encoding.Unicode;
				}
#endif
				bufPos = 0;
				break;
			default:
				if (c == 0)
					enc = StrictUTF16;
				bufPos = 0;
				break;
			}
		}

		// Just like readbyte, but grows the buffer too.
		int ReadByteSpecial ()
		{
			if (bufLength > bufPos)
				return buffer [bufPos++];

			byte [] newbuf = new byte [buffer.Length * 2];
			Buffer.BlockCopy (buffer, 0, newbuf, 0, bufLength);
			int nbytes = stream.Read (newbuf, bufLength, buffer.Length);
			if (nbytes == -1 || nbytes == 0)
				return -1;
				
			bufLength += nbytes;
			buffer = newbuf;
			return buffer [bufPos++];
		}

		// skips whitespace and returns misc char that was read from stream
		private int SkipWhitespace ()
		{
			int c;
			while (true) {
				c = ReadByteSpecial ();
				switch ((char) c) {
				case '\r': goto case ' ';
				case '\n': goto case ' ';
				case '\t': goto case ' ';
				case ' ':
					continue;
				default:
					return c;
				}
			}
		}

		public Encoding ActualEncoding {
			get { return enc; }
		}

		#region Public Overrides
		public override bool CanRead {
			get {
				if (bufLength > bufPos)
					return true;
				else
					return stream.CanRead; 
			}
		}

		// FIXME: It should support base stream's CanSeek.
		public override bool CanSeek {
			get { return false; } // stream.CanSeek; }
		}

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

		public override long Length {
			get {
				return stream.Length;
			}
		}

		public override long Position {
			get {
				return stream.Position - bufLength + bufPos;
			}
			set {
				if(value < bufLength)
					bufPos = (int)value;
				else
					stream.Position = value - bufLength;
			}
		}

		public override void Close ()
		{
			stream.Close ();
		}

		public override void Flush ()
		{
			stream.Flush ();
		}

		public override int Read (byte[] buffer, int offset, int count)
		{
			int ret;
			if (count <= bufLength - bufPos)	{	// all from buffer
				Buffer.BlockCopy (this.buffer, bufPos, buffer, offset, count);
				bufPos += count;
				ret = count;
			} else {
				int bufRest = bufLength - bufPos;
				if (bufLength > bufPos) {
					Buffer.BlockCopy (this.buffer, bufPos, buffer, offset, bufRest);
					bufPos += bufRest;
				}
				ret = bufRest +
					stream.Read (buffer, offset + bufRest, count - bufRest);
			}
			return ret;
		}

		public override int ReadByte ()
		{
			if (bufLength > bufPos) {
				return buffer [bufPos++];
			}
			return stream.ReadByte ();
		}

		public override long Seek (long offset, System.IO.SeekOrigin origin)
		{
			int bufRest = bufLength - bufPos;
			if (origin == SeekOrigin.Current)
				if (offset < bufRest)
					return buffer [bufPos + offset];
				else
					return stream.Seek (offset - bufRest, origin);
			else
				return stream.Seek (offset, origin);
		}

		public override void SetLength (long value)
		{
			stream.SetLength (value);
		}

		public override void Write (byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException ();
		}
		#endregion
	}
}