~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json/JsonTextReader.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#region License
 
2
// Copyright (c) 2007 James Newton-King
 
3
//
 
4
// Permission is hereby granted, free of charge, to any person
 
5
// obtaining a copy of this software and associated documentation
 
6
// files (the "Software"), to deal in the Software without
 
7
// restriction, including without limitation the rights to use,
 
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
 
9
// copies of the Software, and to permit persons to whom the
 
10
// Software is furnished to do so, subject to the following
 
11
// conditions:
 
12
//
 
13
// The above copyright notice and this permission notice shall be
 
14
// included in all copies or substantial portions of the Software.
 
15
//
 
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 
23
// OTHER DEALINGS IN THE SOFTWARE.
 
24
#endregion
 
25
 
 
26
using System;
 
27
using System.Collections.Generic;
 
28
using System.Diagnostics;
 
29
using System.Text;
 
30
using System.IO;
 
31
using System.Xml;
 
32
using System.Globalization;
 
33
using Newtonsoft.Json.Utilities;
 
34
 
 
35
namespace Newtonsoft.Json
 
36
{
 
37
  internal enum ReadType
 
38
  {
 
39
    Read,
 
40
    ReadAsInt32,
 
41
    ReadAsBytes,
 
42
    ReadAsString,
 
43
    ReadAsDecimal,
 
44
    ReadAsDateTime,
 
45
#if !NET20
 
46
    ReadAsDateTimeOffset
 
47
#endif
 
48
  }
 
49
 
 
50
  /// <summary>
 
51
  /// Represents a reader that provides fast, non-cached, forward-only access to JSON text data.
 
52
  /// </summary>
 
53
  public class JsonTextReader : JsonReader, IJsonLineInfo
 
54
  {
 
55
    private const char UnicodeReplacementChar = '\uFFFD';
 
56
 
 
57
    private readonly TextReader _reader;
 
58
    private char[] _chars;
 
59
    private int _charsUsed;
 
60
    private int _charPos;
 
61
    private int _lineStartPos;
 
62
    private int _lineNumber;
 
63
    private bool _isEndOfFile;
 
64
    private StringBuffer _buffer;
 
65
    private StringReference _stringReference;
 
66
 
 
67
    /// <summary>
 
68
    /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
 
69
    /// </summary>
 
70
    /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
 
71
    public JsonTextReader(TextReader reader)
 
72
    {
 
73
      if (reader == null)
 
74
        throw new ArgumentNullException("reader");
 
75
 
 
76
      _reader = reader;
 
77
      _lineNumber = 1;
 
78
      _chars = new char[4097];
 
79
    }
 
80
 
 
81
    internal void SetCharBuffer(char[] chars)
 
82
    {
 
83
      _chars = chars;
 
84
    }
 
85
 
 
86
    private StringBuffer GetBuffer()
 
87
    {
 
88
      if (_buffer == null)
 
89
      {
 
90
        _buffer = new StringBuffer(4096);
 
91
      }
 
92
      else
 
93
      {
 
94
        _buffer.Position = 0;
 
95
      }
 
96
 
 
97
      return _buffer;
 
98
    }
 
99
 
 
100
    private void OnNewLine(int pos)
 
101
    {
 
102
      _lineNumber++;
 
103
      _lineStartPos = pos - 1;
 
104
    }
 
105
 
 
106
    private void ParseString(char quote)
 
107
    {
 
108
      _charPos++;
 
109
 
 
110
      ShiftBufferIfNeeded();
 
111
      ReadStringIntoBuffer(quote);
 
112
 
 
113
      if (_readType == ReadType.ReadAsBytes)
 
114
      {
 
115
        byte[] data;
 
116
        if (_stringReference.Length == 0)
 
117
        {
 
118
          data = new byte[0];
 
119
        }
 
120
        else
 
121
        {
 
122
          data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
 
123
        }
 
124
 
 
125
        SetToken(JsonToken.Bytes, data);
 
126
      }
 
127
      else if (_readType == ReadType.ReadAsString)
 
128
      {
 
129
        string text = _stringReference.ToString();
 
130
 
 
131
        SetToken(JsonToken.String, text);
 
132
        QuoteChar = quote;
 
133
      }
 
134
      else
 
135
      {
 
136
        string text = _stringReference.ToString();
 
137
 
 
138
        if (_dateParseHandling != DateParseHandling.None)
 
139
        {
 
140
          if (text.Length > 0)
 
141
          {
 
142
            if (text[0] == '/')
 
143
            {
 
144
              if (text.StartsWith("/Date(", StringComparison.Ordinal) && text.EndsWith(")/", StringComparison.Ordinal))
 
145
              {
 
146
                ParseDateMicrosoft(text);
 
147
                return;
 
148
              }
 
149
            }
 
150
            else if (char.IsDigit(text[0]) && text.Length >= 19 && text.Length <= 40)
 
151
            {
 
152
              if (ParseDateIso(text))
 
153
                return;
 
154
            }
 
155
          }
 
156
        }
 
157
 
 
158
        SetToken(JsonToken.String, text);
 
159
        QuoteChar = quote;
 
160
      }
 
161
    }
 
162
 
 
163
    private bool ParseDateIso(string text)
 
164
    {
 
165
      const string isoDateFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK";
 
166
 
 
167
#if !NET20
 
168
      if (_readType == ReadType.ReadAsDateTimeOffset || (_readType == ReadType.Read && _dateParseHandling == DateParseHandling.DateTimeOffset))
 
169
      {
 
170
        DateTimeOffset dateTimeOffset;
 
171
        if (DateTimeOffset.TryParseExact(text, isoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateTimeOffset))
 
172
        {
 
173
          SetToken(JsonToken.Date, dateTimeOffset);
 
174
          return true;
 
175
        }
 
176
      }
 
177
      else
 
178
#endif
 
179
      {
 
180
        DateTime dateTime;
 
181
        if (DateTime.TryParseExact(text, isoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateTime))
 
182
        {
 
183
          dateTime = JsonConvert.EnsureDateTime(dateTime, DateTimeZoneHandling);
 
184
 
 
185
          SetToken(JsonToken.Date, dateTime);
 
186
          return true;
 
187
        }
 
188
      }
 
189
 
 
190
      return false;
 
191
    }
 
192
 
 
193
    private void ParseDateMicrosoft(string text)
 
194
    {
 
195
      string value = text.Substring(6, text.Length - 8);
 
196
      DateTimeKind kind = DateTimeKind.Utc;
 
197
 
 
198
      int index = value.IndexOf('+', 1);
 
199
 
 
200
      if (index == -1)
 
201
        index = value.IndexOf('-', 1);
 
202
 
 
203
      TimeSpan offset = TimeSpan.Zero;
 
204
 
 
205
      if (index != -1)
 
206
      {
 
207
        kind = DateTimeKind.Local;
 
208
        offset = ReadOffset(value.Substring(index));
 
209
        value = value.Substring(0, index);
 
210
      }
 
211
 
 
212
      long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);
 
213
 
 
214
      DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
 
215
 
 
216
#if !NET20
 
217
      if (_readType == ReadType.ReadAsDateTimeOffset || (_readType == ReadType.Read && _dateParseHandling == DateParseHandling.DateTimeOffset))
 
218
      {
 
219
        SetToken(JsonToken.Date, new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset));
 
220
      }
 
221
      else
 
222
#endif
 
223
      {
 
224
        DateTime dateTime;
 
225
 
 
226
        switch (kind)
 
227
        {
 
228
          case DateTimeKind.Unspecified:
 
229
            dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
 
230
            break;
 
231
          case DateTimeKind.Local:
 
232
            dateTime = utcDateTime.ToLocalTime();
 
233
            break;
 
234
          default:
 
235
            dateTime = utcDateTime;
 
236
            break;
 
237
        }
 
238
 
 
239
        dateTime = JsonConvert.EnsureDateTime(dateTime, DateTimeZoneHandling);
 
240
 
 
241
        SetToken(JsonToken.Date, dateTime);
 
242
      }
 
243
    }
 
244
 
 
245
    private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count)
 
246
    {
 
247
      const int charByteCount = 2;
 
248
 
 
249
      Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount);
 
250
    }
 
251
 
 
252
    private void ShiftBufferIfNeeded()
 
253
    {
 
254
      // once in the last 10% of the buffer shift the remainling content to the start to avoid
 
255
      // unnessesarly increasing the buffer size when reading numbers/strings
 
256
      int length = _chars.Length;
 
257
      if (length - _charPos <= length * 0.1)
 
258
      {
 
259
        int count = _charsUsed - _charPos;
 
260
        if (count > 0)
 
261
          BlockCopyChars(_chars, _charPos, _chars, 0, count);
 
262
 
 
263
        _lineStartPos -= _charPos;
 
264
        _charPos = 0;
 
265
        _charsUsed = count;
 
266
        _chars[_charsUsed] = '\0';
 
267
      }
 
268
    }
 
269
 
 
270
    private int ReadData(bool append)
 
271
    {
 
272
      return ReadData(append, 0);
 
273
    }
 
274
 
 
275
    private int ReadData(bool append, int charsRequired)
 
276
    {
 
277
      if (_isEndOfFile)
 
278
        return 0;
 
279
 
 
280
      // char buffer is full
 
281
      if (_charsUsed + charsRequired >= _chars.Length - 1)
 
282
      {
 
283
        if (append)
 
284
        {
 
285
          // copy to new array either double the size of the current or big enough to fit required content
 
286
          int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1);
 
287
 
 
288
          // increase the size of the buffer
 
289
          char[] dst = new char[newArrayLength];
 
290
 
 
291
          BlockCopyChars(_chars, 0, dst, 0, _chars.Length);
 
292
 
 
293
          _chars = dst;
 
294
        }
 
295
        else
 
296
        {
 
297
          int remainingCharCount = _charsUsed - _charPos;
 
298
 
 
299
          if (remainingCharCount + charsRequired + 1 >= _chars.Length)
 
300
          {
 
301
            // the remaining count plus the required is bigger than the current buffer size
 
302
            char[] dst = new char[remainingCharCount + charsRequired + 1];
 
303
 
 
304
            if (remainingCharCount > 0)
 
305
              BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount);
 
306
 
 
307
            _chars = dst;
 
308
          }
 
309
          else
 
310
          {
 
311
            // copy any remaining data to the beginning of the buffer if needed and reset positions
 
312
            if (remainingCharCount > 0)
 
313
              BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount);
 
314
          }
 
315
 
 
316
          _lineStartPos -= _charPos;
 
317
          _charPos = 0;
 
318
          _charsUsed = remainingCharCount;
 
319
        }
 
320
      }
 
321
 
 
322
      int attemptCharReadCount = _chars.Length - _charsUsed - 1;
 
323
 
 
324
      int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount);
 
325
 
 
326
      _charsUsed += charsRead;
 
327
 
 
328
      if (charsRead == 0)
 
329
        _isEndOfFile = true;
 
330
 
 
331
      _chars[_charsUsed] = '\0';
 
332
      return charsRead;
 
333
    }
 
334
 
 
335
    private bool EnsureChars(int relativePosition, bool append)
 
336
    {
 
337
      if (_charPos + relativePosition >= _charsUsed)
 
338
        return ReadChars(relativePosition, append);
 
339
 
 
340
      return true;
 
341
    }
 
342
 
 
343
    private bool ReadChars(int relativePosition, bool append)
 
344
    {
 
345
      if (_isEndOfFile)
 
346
        return false;
 
347
 
 
348
      int charsRequired = _charPos + relativePosition - _charsUsed + 1;
 
349
 
 
350
      int totalCharsRead = 0;
 
351
 
 
352
      // it is possible that the TextReader doesn't return all data at once
 
353
      // repeat read until the required text is returned or the reader is out of content
 
354
      do
 
355
      {
 
356
        int charsRead = ReadData(append, charsRequired - totalCharsRead);
 
357
 
 
358
        // no more content
 
359
        if (charsRead == 0)
 
360
          break;
 
361
 
 
362
        totalCharsRead += charsRead;
 
363
      }
 
364
      while (totalCharsRead < charsRequired);
 
365
 
 
366
      if (totalCharsRead < charsRequired)
 
367
        return false;
 
368
      return true;
 
369
    }
 
370
 
 
371
    private static TimeSpan ReadOffset(string offsetText)
 
372
    {
 
373
      bool negative = (offsetText[0] == '-');
 
374
 
 
375
      int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
 
376
      int minutes = 0;
 
377
      if (offsetText.Length >= 5)
 
378
        minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
 
379
 
 
380
      TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
 
381
      if (negative)
 
382
        offset = offset.Negate();
 
383
 
 
384
      return offset;
 
385
    }
 
386
 
 
387
    /// <summary>
 
388
    /// Reads the next JSON token from the stream.
 
389
    /// </summary>
 
390
    /// <returns>
 
391
    /// true if the next token was read successfully; false if there are no more tokens to read.
 
392
    /// </returns>
 
393
    [DebuggerStepThrough]
 
394
    public override bool Read()
 
395
    {
 
396
      _readType = ReadType.Read;
 
397
      if (!ReadInternal())
 
398
      {
 
399
        SetToken(JsonToken.None);
 
400
        return false;
 
401
      }
 
402
 
 
403
      return true;
 
404
    }
 
405
 
 
406
    /// <summary>
 
407
    /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
 
408
    /// </summary>
 
409
    /// <returns>
 
410
    /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.
 
411
    /// </returns>
 
412
    public override byte[] ReadAsBytes()
 
413
    {
 
414
      return ReadAsBytesInternal();
 
415
    }
 
416
 
 
417
    /// <summary>
 
418
    /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
 
419
    /// </summary>
 
420
    /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
 
421
    public override decimal? ReadAsDecimal()
 
422
    {
 
423
      return ReadAsDecimalInternal();
 
424
    }
 
425
 
 
426
    /// <summary>
 
427
    /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
 
428
    /// </summary>
 
429
    /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
 
430
    public override int? ReadAsInt32()
 
431
    {
 
432
      return ReadAsInt32Internal();
 
433
    }
 
434
 
 
435
    /// <summary>
 
436
    /// Reads the next JSON token from the stream as a <see cref="String"/>.
 
437
    /// </summary>
 
438
    /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
 
439
    public override string ReadAsString()
 
440
    {
 
441
      return ReadAsStringInternal();
 
442
    }
 
443
 
 
444
    /// <summary>
 
445
    /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
 
446
    /// </summary>
 
447
    /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
 
448
    public override DateTime? ReadAsDateTime()
 
449
    {
 
450
      return ReadAsDateTimeInternal();
 
451
    }
 
452
 
 
453
#if !NET20
 
454
    /// <summary>
 
455
    /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
 
456
    /// </summary>
 
457
    /// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
 
458
    public override DateTimeOffset? ReadAsDateTimeOffset()
 
459
    {
 
460
      return ReadAsDateTimeOffsetInternal();
 
461
    }
 
462
#endif
 
463
 
 
464
    internal override bool ReadInternal()
 
465
    {
 
466
      while (true)
 
467
      {
 
468
        switch (_currentState)
 
469
        {
 
470
          case State.Start:
 
471
          case State.Property:
 
472
          case State.Array:
 
473
          case State.ArrayStart:
 
474
          case State.Constructor:
 
475
          case State.ConstructorStart:
 
476
            return ParseValue();
 
477
          case State.Complete:
 
478
            break;
 
479
          case State.Object:
 
480
          case State.ObjectStart:
 
481
            return ParseObject();
 
482
          case State.PostValue:
 
483
            // returns true if it hits
 
484
            // end of object or array
 
485
            if (ParsePostValue())
 
486
              return true;
 
487
            break;
 
488
          case State.Finished:
 
489
            if (EnsureChars(0, false))
 
490
            {
 
491
              EatWhitespace(false);
 
492
              if (_isEndOfFile)
 
493
              {
 
494
                return false;
 
495
              }
 
496
              if (_chars[_charPos] == '/')
 
497
              {
 
498
                ParseComment();
 
499
                return true;
 
500
              }
 
501
              else
 
502
              {
 
503
                throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
 
504
              }
 
505
            }
 
506
            return false;
 
507
          case State.Closed:
 
508
            break;
 
509
          case State.Error:
 
510
            break;
 
511
          default:
 
512
            throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
 
513
        }
 
514
      }
 
515
    }
 
516
 
 
517
    private void ReadStringIntoBuffer(char quote)
 
518
    {
 
519
      int charPos = _charPos;
 
520
      int initialPosition = _charPos;
 
521
      int lastWritePosition = _charPos;
 
522
      StringBuffer buffer = null;
 
523
 
 
524
      while (true)
 
525
      {
 
526
        switch (_chars[charPos++])
 
527
        {
 
528
          case '\0':
 
529
            if (_charsUsed == charPos - 1)
 
530
            {
 
531
              charPos--;
 
532
 
 
533
              if (ReadData(true) == 0)
 
534
              {
 
535
                _charPos = charPos;
 
536
                throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
 
537
              }
 
538
            }
 
539
            break;
 
540
          case '\\':
 
541
            _charPos = charPos;
 
542
            if (!EnsureChars(0, true))
 
543
            {
 
544
              _charPos = charPos;
 
545
              throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
 
546
            }
 
547
 
 
548
            // start of escape sequence
 
549
            int escapeStartPos = charPos - 1;
 
550
 
 
551
            char currentChar = _chars[charPos];
 
552
 
 
553
            char writeChar;
 
554
 
 
555
            switch (currentChar)
 
556
            {
 
557
              case 'b':
 
558
                charPos++;
 
559
                writeChar = '\b';
 
560
                break;
 
561
              case 't':
 
562
                charPos++;
 
563
                writeChar = '\t';
 
564
                break;
 
565
              case 'n':
 
566
                charPos++;
 
567
                writeChar = '\n';
 
568
                break;
 
569
              case 'f':
 
570
                charPos++;
 
571
                writeChar = '\f';
 
572
                break;
 
573
              case 'r':
 
574
                charPos++;
 
575
                writeChar = '\r';
 
576
                break;
 
577
              case '\\':
 
578
                charPos++;
 
579
                writeChar = '\\';
 
580
                break;
 
581
              case '"':
 
582
              case '\'':
 
583
              case '/':
 
584
                writeChar = currentChar;
 
585
                charPos++;
 
586
                break;
 
587
              case 'u':
 
588
                charPos++;
 
589
                _charPos = charPos;
 
590
                writeChar = ParseUnicode();
 
591
                
 
592
                if (StringUtils.IsLowSurrogate(writeChar))
 
593
                {
 
594
                  // low surrogate with no preceding high surrogate; this char is replaced
 
595
                  writeChar = UnicodeReplacementChar;
 
596
                }
 
597
                else if (StringUtils.IsHighSurrogate(writeChar))
 
598
                {
 
599
                  bool anotherHighSurrogate;
 
600
 
 
601
                  // loop for handling situations where there are multiple consecutive high surrogates
 
602
                  do
 
603
                  {
 
604
                    anotherHighSurrogate = false;
 
605
 
 
606
                    // potential start of a surrogate pair
 
607
                    if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
 
608
                    {
 
609
                      char highSurrogate = writeChar;
 
610
 
 
611
                      _charPos += 2;
 
612
                      writeChar = ParseUnicode();
 
613
 
 
614
                      if (StringUtils.IsLowSurrogate(writeChar))
 
615
                      {
 
616
                        // a valid surrogate pair!
 
617
                      }
 
618
                      else if (StringUtils.IsHighSurrogate(writeChar))
 
619
                      {
 
620
                        // another high surrogate; replace current and start check over
 
621
                        highSurrogate = UnicodeReplacementChar;
 
622
                        anotherHighSurrogate = true;
 
623
                      }
 
624
                      else
 
625
                      {
 
626
                        // high surrogate not followed by low surrogate; original char is replaced
 
627
                        highSurrogate = UnicodeReplacementChar;
 
628
                      }
 
629
 
 
630
                      if (buffer == null)
 
631
                        buffer = GetBuffer();
 
632
 
 
633
                      WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos);
 
634
                      lastWritePosition = _charPos;
 
635
                    }
 
636
                    else
 
637
                    {
 
638
                      // there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
 
639
                      // replace high surrogate and continue on as usual
 
640
                      writeChar = UnicodeReplacementChar;
 
641
                    }
 
642
                  } while (anotherHighSurrogate);
 
643
                }
 
644
 
 
645
                charPos = _charPos;
 
646
                break;
 
647
              default:
 
648
                charPos++;
 
649
                _charPos = charPos;
 
650
                throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
 
651
            }
 
652
 
 
653
            if (buffer == null)
 
654
              buffer = GetBuffer();
 
655
 
 
656
            WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos);
 
657
 
 
658
            lastWritePosition = charPos;
 
659
            break;
 
660
          case StringUtils.CarriageReturn:
 
661
            _charPos = charPos - 1;
 
662
            ProcessCarriageReturn(true);
 
663
            charPos = _charPos;
 
664
            break;
 
665
          case StringUtils.LineFeed:
 
666
            _charPos = charPos - 1;
 
667
            ProcessLineFeed();
 
668
            charPos = _charPos;
 
669
            break;
 
670
          case '"':
 
671
          case '\'':
 
672
            if (_chars[charPos - 1] == quote)
 
673
            {
 
674
              charPos--;
 
675
 
 
676
              if (initialPosition == lastWritePosition)
 
677
              {
 
678
                _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
 
679
              }
 
680
              else
 
681
              {
 
682
                if (buffer == null)
 
683
                  buffer = GetBuffer();
 
684
 
 
685
                if (charPos > lastWritePosition)
 
686
                  buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition);
 
687
 
 
688
                _stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position);
 
689
              }
 
690
 
 
691
              charPos++;
 
692
              _charPos = charPos;
 
693
              return;
 
694
            }
 
695
            break;
 
696
        }
 
697
      }
 
698
    }
 
699
 
 
700
    private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition)
 
701
    {
 
702
      if (writeToPosition > lastWritePosition)
 
703
      {
 
704
        buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition);
 
705
      }
 
706
 
 
707
      buffer.Append(writeChar);
 
708
    }
 
709
 
 
710
    private char ParseUnicode()
 
711
    {
 
712
      char writeChar;
 
713
      if (EnsureChars(4, true))
 
714
      {
 
715
        string hexValues = new string(_chars, _charPos, 4);
 
716
        char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
 
717
        writeChar = hexChar;
 
718
 
 
719
        _charPos += 4;
 
720
      }
 
721
      else
 
722
      {
 
723
        throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character.");
 
724
      }
 
725
      return writeChar;
 
726
    }
 
727
 
 
728
    private void ReadNumberIntoBuffer()
 
729
    {
 
730
      int charPos = _charPos;
 
731
 
 
732
      while (true)
 
733
      {
 
734
        switch (_chars[charPos++])
 
735
        {
 
736
          case '\0':
 
737
            if (_charsUsed == charPos - 1)
 
738
            {
 
739
              charPos--;
 
740
              _charPos = charPos;
 
741
              if (ReadData(true) == 0)
 
742
                return;
 
743
            }
 
744
            break;
 
745
          case '-':
 
746
          case '+':
 
747
          case 'a':
 
748
          case 'A':
 
749
          case 'b':
 
750
          case 'B':
 
751
          case 'c':
 
752
          case 'C':
 
753
          case 'd':
 
754
          case 'D':
 
755
          case 'e':
 
756
          case 'E':
 
757
          case 'f':
 
758
          case 'F':
 
759
          case 'x':
 
760
          case 'X':
 
761
          case '.':
 
762
          case '0':
 
763
          case '1':
 
764
          case '2':
 
765
          case '3':
 
766
          case '4':
 
767
          case '5':
 
768
          case '6':
 
769
          case '7':
 
770
          case '8':
 
771
          case '9':
 
772
            break;
 
773
          default:
 
774
            _charPos = charPos - 1;
 
775
            return;
 
776
        }
 
777
      }
 
778
    }
 
779
 
 
780
    private void ClearRecentString()
 
781
    {
 
782
      if (_buffer != null)
 
783
        _buffer.Position = 0;
 
784
 
 
785
      _stringReference = new StringReference();
 
786
    }
 
787
 
 
788
    private bool ParsePostValue()
 
789
    {
 
790
      while (true)
 
791
      {
 
792
        char currentChar = _chars[_charPos];
 
793
 
 
794
        switch (currentChar)
 
795
        {
 
796
          case '\0':
 
797
            if (_charsUsed == _charPos)
 
798
            {
 
799
              if (ReadData(false) == 0)
 
800
              {
 
801
                _currentState = State.Finished;
 
802
                return false;
 
803
              }
 
804
            }
 
805
            else
 
806
            {
 
807
              _charPos++;
 
808
            }
 
809
            break;
 
810
          case '}':
 
811
            _charPos++;
 
812
            SetToken(JsonToken.EndObject);
 
813
            return true;
 
814
          case ']':
 
815
            _charPos++;
 
816
            SetToken(JsonToken.EndArray);
 
817
            return true;
 
818
          case ')':
 
819
            _charPos++;
 
820
            SetToken(JsonToken.EndConstructor);
 
821
            return true;
 
822
          case '/':
 
823
            ParseComment();
 
824
            return true;
 
825
          case ',':
 
826
            _charPos++;
 
827
 
 
828
            // finished parsing
 
829
            SetStateBasedOnCurrent();
 
830
            return false;
 
831
          case ' ':
 
832
          case StringUtils.Tab:
 
833
            // eat
 
834
            _charPos++;
 
835
            break;
 
836
          case StringUtils.CarriageReturn:
 
837
            ProcessCarriageReturn(false);
 
838
            break;
 
839
          case StringUtils.LineFeed:
 
840
            ProcessLineFeed();
 
841
            break;
 
842
          default:
 
843
            if (char.IsWhiteSpace(currentChar))
 
844
            {
 
845
              // eat
 
846
              _charPos++;
 
847
            }
 
848
            else
 
849
            {
 
850
              throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
 
851
            }
 
852
            break;
 
853
        }
 
854
      }
 
855
    }
 
856
 
 
857
    private bool ParseObject()
 
858
    {
 
859
      while (true)
 
860
      {
 
861
        char currentChar = _chars[_charPos];
 
862
 
 
863
        switch (currentChar)
 
864
        {
 
865
          case '\0':
 
866
            if (_charsUsed == _charPos)
 
867
            {
 
868
              if (ReadData(false) == 0)
 
869
                return false;
 
870
            }
 
871
            else
 
872
            {
 
873
              _charPos++;
 
874
            }
 
875
            break;
 
876
          case '}':
 
877
            SetToken(JsonToken.EndObject);
 
878
            _charPos++;
 
879
            return true;
 
880
          case '/':
 
881
            ParseComment();
 
882
            return true;
 
883
          case StringUtils.CarriageReturn:
 
884
            ProcessCarriageReturn(false);
 
885
            break;
 
886
          case StringUtils.LineFeed:
 
887
            ProcessLineFeed();
 
888
            break;
 
889
          case ' ':
 
890
          case StringUtils.Tab:
 
891
            // eat
 
892
            _charPos++;
 
893
            break;
 
894
          default:
 
895
            if (char.IsWhiteSpace(currentChar))
 
896
            {
 
897
              // eat
 
898
              _charPos++;
 
899
            }
 
900
            else
 
901
            {
 
902
              return ParseProperty();
 
903
            }
 
904
            break;
 
905
        }
 
906
      }
 
907
    }
 
908
 
 
909
    private bool ParseProperty()
 
910
    {
 
911
      char firstChar = _chars[_charPos];
 
912
      char quoteChar;
 
913
 
 
914
      if (firstChar == '"' || firstChar == '\'')
 
915
      {
 
916
        _charPos++;
 
917
        quoteChar = firstChar;
 
918
        ShiftBufferIfNeeded();
 
919
        ReadStringIntoBuffer(quoteChar);
 
920
      }
 
921
      else if (ValidIdentifierChar(firstChar))
 
922
      {
 
923
        quoteChar = '\0';
 
924
        ShiftBufferIfNeeded();
 
925
        ParseUnquotedProperty();
 
926
      }
 
927
      else
 
928
      {
 
929
        throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
 
930
      }
 
931
 
 
932
      string propertyName = _stringReference.ToString();
 
933
 
 
934
      EatWhitespace(false);
 
935
 
 
936
      if (_chars[_charPos] != ':')
 
937
        throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
 
938
 
 
939
      _charPos++;
 
940
 
 
941
      SetToken(JsonToken.PropertyName, propertyName);
 
942
      QuoteChar = quoteChar;
 
943
      ClearRecentString();
 
944
 
 
945
      return true;
 
946
    }
 
947
 
 
948
    private bool ValidIdentifierChar(char value)
 
949
    {
 
950
      return (char.IsLetterOrDigit(value) || value == '_' || value == '$');
 
951
    }
 
952
 
 
953
    private void ParseUnquotedProperty()
 
954
    {
 
955
      int initialPosition = _charPos;
 
956
 
 
957
      // parse unquoted property name until whitespace or colon
 
958
      while (true)
 
959
      {
 
960
        switch (_chars[_charPos])
 
961
        {
 
962
          case '\0':
 
963
            if (_charsUsed == _charPos)
 
964
            {
 
965
              if (ReadData(true) == 0)
 
966
                throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
 
967
 
 
968
              break;
 
969
            }
 
970
 
 
971
            _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
 
972
            return;
 
973
          default:
 
974
            char currentChar = _chars[_charPos];
 
975
 
 
976
            if (ValidIdentifierChar(currentChar))
 
977
            {
 
978
              _charPos++;
 
979
              break;
 
980
            }
 
981
            else if (char.IsWhiteSpace(currentChar) || currentChar == ':')
 
982
            {
 
983
              _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
 
984
              return;
 
985
            }
 
986
 
 
987
            throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
 
988
        }
 
989
      }
 
990
    }
 
991
 
 
992
    private bool ParseValue()
 
993
    {
 
994
      while (true)
 
995
      {
 
996
        char currentChar = _chars[_charPos];
 
997
 
 
998
        switch (currentChar)
 
999
        {
 
1000
          case '\0':
 
1001
            if (_charsUsed == _charPos)
 
1002
            {
 
1003
              if (ReadData(false) == 0)
 
1004
                return false;
 
1005
            }
 
1006
            else
 
1007
            {
 
1008
              _charPos++;
 
1009
            }
 
1010
            break;
 
1011
          case '"':
 
1012
          case '\'':
 
1013
            ParseString(currentChar);
 
1014
            return true;
 
1015
          case 't':
 
1016
            ParseTrue();
 
1017
            return true;
 
1018
          case 'f':
 
1019
            ParseFalse();
 
1020
            return true;
 
1021
          case 'n':
 
1022
            if (EnsureChars(1, true))
 
1023
            {
 
1024
              char next = _chars[_charPos + 1];
 
1025
 
 
1026
              if (next == 'u')
 
1027
                ParseNull();
 
1028
              else if (next == 'e')
 
1029
                ParseConstructor();
 
1030
              else
 
1031
                throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
 
1032
            }
 
1033
            else
 
1034
            {
 
1035
              throw JsonReaderException.Create(this, "Unexpected end.");
 
1036
            }
 
1037
            return true;
 
1038
          case 'N':
 
1039
            ParseNumberNaN();
 
1040
            return true;
 
1041
          case 'I':
 
1042
            ParseNumberPositiveInfinity();
 
1043
            return true;
 
1044
          case '-':
 
1045
            if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I')
 
1046
              ParseNumberNegativeInfinity();
 
1047
            else
 
1048
              ParseNumber();
 
1049
            return true;
 
1050
          case '/':
 
1051
            ParseComment();
 
1052
            return true;
 
1053
          case 'u':
 
1054
            ParseUndefined();
 
1055
            return true;
 
1056
          case '{':
 
1057
            _charPos++;
 
1058
            SetToken(JsonToken.StartObject);
 
1059
            return true;
 
1060
          case '[':
 
1061
            _charPos++;
 
1062
            SetToken(JsonToken.StartArray);
 
1063
            return true;
 
1064
          case ']':
 
1065
            _charPos++;
 
1066
            SetToken(JsonToken.EndArray);
 
1067
            return true;
 
1068
          case ',':
 
1069
            // don't increment position, the next call to read will handle comma
 
1070
            // this is done to handle multiple empty comma values
 
1071
            SetToken(JsonToken.Undefined);
 
1072
            return true;
 
1073
          case ')':
 
1074
            _charPos++;
 
1075
            SetToken(JsonToken.EndConstructor);
 
1076
            return true;
 
1077
          case StringUtils.CarriageReturn:
 
1078
            ProcessCarriageReturn(false);
 
1079
            break;
 
1080
          case StringUtils.LineFeed:
 
1081
            ProcessLineFeed();
 
1082
            break;
 
1083
          case ' ':
 
1084
          case StringUtils.Tab:
 
1085
            // eat
 
1086
            _charPos++;
 
1087
            break;
 
1088
          default:
 
1089
            if (char.IsWhiteSpace(currentChar))
 
1090
            {
 
1091
              // eat
 
1092
              _charPos++;
 
1093
              break;
 
1094
            }
 
1095
            else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
 
1096
            {
 
1097
              ParseNumber();
 
1098
              return true;
 
1099
            }
 
1100
            else
 
1101
            {
 
1102
              throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
 
1103
            }
 
1104
        }
 
1105
      }
 
1106
    }
 
1107
 
 
1108
    private void ProcessLineFeed()
 
1109
    {
 
1110
      _charPos++;
 
1111
      OnNewLine(_charPos);
 
1112
    }
 
1113
 
 
1114
    private void ProcessCarriageReturn(bool append)
 
1115
    {
 
1116
      _charPos++;
 
1117
 
 
1118
      if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed)
 
1119
        _charPos++;
 
1120
 
 
1121
      OnNewLine(_charPos);
 
1122
    }
 
1123
 
 
1124
    private bool EatWhitespace(bool oneOrMore)
 
1125
    {
 
1126
      bool finished = false;
 
1127
      bool ateWhitespace = false;
 
1128
      while (!finished)
 
1129
      {
 
1130
        char currentChar = _chars[_charPos];
 
1131
 
 
1132
        switch (currentChar)
 
1133
        {
 
1134
          case '\0':
 
1135
            if (_charsUsed == _charPos)
 
1136
            {
 
1137
              if (ReadData(false) == 0)
 
1138
                finished = true;
 
1139
            }
 
1140
            else
 
1141
            {
 
1142
              _charPos++;
 
1143
            }
 
1144
            break;
 
1145
          case StringUtils.CarriageReturn:
 
1146
            ProcessCarriageReturn(false);
 
1147
            break;
 
1148
          case StringUtils.LineFeed:
 
1149
            ProcessLineFeed();
 
1150
            break;
 
1151
          default:
 
1152
            if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
 
1153
            {
 
1154
              ateWhitespace = true;
 
1155
              _charPos++;
 
1156
            }
 
1157
            else
 
1158
            {
 
1159
              finished = true;
 
1160
            }
 
1161
            break;
 
1162
        }
 
1163
      }
 
1164
 
 
1165
      return (!oneOrMore || ateWhitespace);
 
1166
    }
 
1167
 
 
1168
    private void ParseConstructor()
 
1169
    {
 
1170
      if (MatchValueWithTrailingSeperator("new"))
 
1171
      {
 
1172
        EatWhitespace(false);
 
1173
 
 
1174
        int initialPosition = _charPos;
 
1175
        int endPosition;
 
1176
 
 
1177
        while (true)
 
1178
        {
 
1179
          char currentChar = _chars[_charPos];
 
1180
          if (currentChar == '\0')
 
1181
          {
 
1182
            if (_charsUsed == _charPos)
 
1183
            {
 
1184
              if (ReadData(true) == 0)
 
1185
                throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
 
1186
            }
 
1187
            else
 
1188
            {
 
1189
              endPosition = _charPos;
 
1190
              _charPos++;
 
1191
              break;
 
1192
            }
 
1193
          }
 
1194
          else if (char.IsLetterOrDigit(currentChar))
 
1195
          {
 
1196
            _charPos++;
 
1197
          }
 
1198
          else if (currentChar == StringUtils.CarriageReturn)
 
1199
          {
 
1200
            endPosition = _charPos;
 
1201
            ProcessCarriageReturn(true);
 
1202
            break;
 
1203
          }
 
1204
          else if (currentChar == StringUtils.LineFeed)
 
1205
          {
 
1206
            endPosition = _charPos;
 
1207
            ProcessLineFeed();
 
1208
            break;
 
1209
          }
 
1210
          else if (char.IsWhiteSpace(currentChar))
 
1211
          {
 
1212
            endPosition = _charPos;
 
1213
            _charPos++;
 
1214
            break;
 
1215
          }
 
1216
          else if (currentChar == '(')
 
1217
          {
 
1218
            endPosition = _charPos;
 
1219
            break;
 
1220
          }
 
1221
          else
 
1222
          {
 
1223
            throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
 
1224
          }
 
1225
        }
 
1226
 
 
1227
        _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
 
1228
        string constructorName = _stringReference.ToString();
 
1229
 
 
1230
        EatWhitespace(false);
 
1231
 
 
1232
        if (_chars[_charPos] != '(')
 
1233
          throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
 
1234
 
 
1235
        _charPos++;
 
1236
 
 
1237
        ClearRecentString();
 
1238
 
 
1239
        SetToken(JsonToken.StartConstructor, constructorName);
 
1240
      }
 
1241
    }
 
1242
 
 
1243
    private void ParseNumber()
 
1244
    {
 
1245
      ShiftBufferIfNeeded();
 
1246
 
 
1247
      char firstChar = _chars[_charPos];
 
1248
      int initialPosition = _charPos;
 
1249
 
 
1250
      ReadNumberIntoBuffer();
 
1251
 
 
1252
      _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
 
1253
 
 
1254
      object numberValue;
 
1255
      JsonToken numberType;
 
1256
 
 
1257
      bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
 
1258
      bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1
 
1259
        && _stringReference.Chars[_stringReference.StartIndex + 1] != '.'
 
1260
        && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e'
 
1261
        && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');
 
1262
 
 
1263
      if (_readType == ReadType.ReadAsInt32)
 
1264
      {
 
1265
        if (singleDigit)
 
1266
        {
 
1267
          // digit char values start at 48
 
1268
          numberValue = firstChar - 48;
 
1269
        }
 
1270
        else if (nonBase10)
 
1271
        {
 
1272
          string number = _stringReference.ToString();
 
1273
 
 
1274
          // decimal.Parse doesn't support parsing hexadecimal values
 
1275
          int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
 
1276
                           ? Convert.ToInt32(number, 16)
 
1277
                           : Convert.ToInt32(number, 8);
 
1278
 
 
1279
          numberValue = integer;
 
1280
        }
 
1281
        else
 
1282
        {
 
1283
          string number = _stringReference.ToString();
 
1284
 
 
1285
          numberValue = Convert.ToInt32(number, CultureInfo.InvariantCulture);
 
1286
        }
 
1287
 
 
1288
        numberType = JsonToken.Integer;
 
1289
      }
 
1290
      else if (_readType == ReadType.ReadAsDecimal)
 
1291
      {
 
1292
        if (singleDigit)
 
1293
        {
 
1294
          // digit char values start at 48
 
1295
          numberValue = (decimal)firstChar - 48;
 
1296
        }
 
1297
        else if (nonBase10)
 
1298
        {
 
1299
          string number = _stringReference.ToString();
 
1300
 
 
1301
          // decimal.Parse doesn't support parsing hexadecimal values
 
1302
          long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
 
1303
                           ? Convert.ToInt64(number, 16)
 
1304
                           : Convert.ToInt64(number, 8);
 
1305
 
 
1306
          numberValue = Convert.ToDecimal(integer);
 
1307
        }
 
1308
        else
 
1309
        {
 
1310
          string number = _stringReference.ToString();
 
1311
 
 
1312
          numberValue = decimal.Parse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
 
1313
        }
 
1314
 
 
1315
        numberType = JsonToken.Float;
 
1316
      }
 
1317
      else
 
1318
      {
 
1319
        if (singleDigit)
 
1320
        {
 
1321
          // digit char values start at 48
 
1322
          numberValue = (long)firstChar - 48;
 
1323
          numberType = JsonToken.Integer;
 
1324
        }
 
1325
        else if (nonBase10)
 
1326
        {
 
1327
          string number = _stringReference.ToString();
 
1328
 
 
1329
          numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
 
1330
                          ? Convert.ToInt64(number, 16)
 
1331
                          : Convert.ToInt64(number, 8);
 
1332
          numberType = JsonToken.Integer;
 
1333
        }
 
1334
        else
 
1335
        {
 
1336
          string number = _stringReference.ToString();
 
1337
 
 
1338
          // it's faster to do 3 indexof with single characters than an indexofany
 
1339
          if (number.IndexOf('.') != -1 || number.IndexOf('E') != -1 || number.IndexOf('e') != -1)
 
1340
          {
 
1341
            numberValue = Convert.ToDouble(number, CultureInfo.InvariantCulture);
 
1342
            numberType = JsonToken.Float;
 
1343
          }
 
1344
          else
 
1345
          {
 
1346
            try
 
1347
            {
 
1348
              numberValue = Convert.ToInt64(number, CultureInfo.InvariantCulture);
 
1349
            }
 
1350
            catch (OverflowException ex)
 
1351
            {
 
1352
              throw JsonReaderException.Create((JsonReader)this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex);
 
1353
            }
 
1354
 
 
1355
            numberType = JsonToken.Integer;
 
1356
          }
 
1357
        }
 
1358
      }
 
1359
 
 
1360
      ClearRecentString();
 
1361
 
 
1362
      SetToken(numberType, numberValue);
 
1363
    }
 
1364
 
 
1365
    private void ParseComment()
 
1366
    {
 
1367
      // should have already parsed / character before reaching this method
 
1368
      _charPos++;
 
1369
 
 
1370
      if (!EnsureChars(1, false) || _chars[_charPos] != '*')
 
1371
        throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
 
1372
      else
 
1373
        _charPos++;
 
1374
 
 
1375
      int initialPosition = _charPos;
 
1376
 
 
1377
      bool commentFinished = false;
 
1378
 
 
1379
      while (!commentFinished)
 
1380
      {
 
1381
        switch (_chars[_charPos])
 
1382
        {
 
1383
          case '\0':
 
1384
            if (_charsUsed == _charPos)
 
1385
            {
 
1386
              if (ReadData(true) == 0)
 
1387
                throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
 
1388
            }
 
1389
            else
 
1390
            {
 
1391
              _charPos++;
 
1392
            }
 
1393
            break;
 
1394
          case '*':
 
1395
            _charPos++;
 
1396
 
 
1397
            if (EnsureChars(0, true))
 
1398
            {
 
1399
              if (_chars[_charPos] == '/')
 
1400
              {
 
1401
                _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1);
 
1402
 
 
1403
                _charPos++;
 
1404
                commentFinished = true;
 
1405
              }
 
1406
            }
 
1407
            break;
 
1408
          case StringUtils.CarriageReturn:
 
1409
            ProcessCarriageReturn(true);
 
1410
            break;
 
1411
          case StringUtils.LineFeed:
 
1412
            ProcessLineFeed();
 
1413
            break;
 
1414
          default:
 
1415
            _charPos++;
 
1416
            break;
 
1417
        }
 
1418
      }
 
1419
 
 
1420
      SetToken(JsonToken.Comment, _stringReference.ToString());
 
1421
 
 
1422
      ClearRecentString();
 
1423
    }
 
1424
 
 
1425
    private bool MatchValue(string value)
 
1426
    {
 
1427
      if (!EnsureChars(value.Length - 1, true))
 
1428
        return false;
 
1429
 
 
1430
      for (int i = 0; i < value.Length; i++)
 
1431
      {
 
1432
        if (_chars[_charPos + i] != value[i])
 
1433
        {
 
1434
          return false;
 
1435
        }
 
1436
      }
 
1437
 
 
1438
      _charPos += value.Length;
 
1439
 
 
1440
      return true;
 
1441
    }
 
1442
 
 
1443
    private bool MatchValueWithTrailingSeperator(string value)
 
1444
    {
 
1445
      // will match value and then move to the next character, checking that it is a seperator character
 
1446
      bool match = MatchValue(value);
 
1447
 
 
1448
      if (!match)
 
1449
        return false;
 
1450
 
 
1451
      if (!EnsureChars(0, false))
 
1452
        return true;
 
1453
 
 
1454
      return IsSeperator(_chars[_charPos]) || _chars[_charPos] == '\0';
 
1455
    }
 
1456
 
 
1457
    private bool IsSeperator(char c)
 
1458
    {
 
1459
      switch (c)
 
1460
      {
 
1461
        case '}':
 
1462
        case ']':
 
1463
        case ',':
 
1464
          return true;
 
1465
        case '/':
 
1466
          // check next character to see if start of a comment
 
1467
          if (!EnsureChars(1, false))
 
1468
            return false;
 
1469
 
 
1470
          return (_chars[_charPos + 1] == '*');
 
1471
        case ')':
 
1472
          if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart)
 
1473
            return true;
 
1474
          break;
 
1475
        case ' ':
 
1476
        case StringUtils.Tab:
 
1477
        case StringUtils.LineFeed:
 
1478
        case StringUtils.CarriageReturn:
 
1479
          return true;
 
1480
        default:
 
1481
          if (char.IsWhiteSpace(c))
 
1482
            return true;
 
1483
          break;
 
1484
      }
 
1485
 
 
1486
      return false;
 
1487
    }
 
1488
 
 
1489
    private void ParseTrue()
 
1490
    {
 
1491
      // check characters equal 'true'
 
1492
      // and that it is followed by either a seperator character
 
1493
      // or the text ends
 
1494
      if (MatchValueWithTrailingSeperator(JsonConvert.True))
 
1495
      {
 
1496
        SetToken(JsonToken.Boolean, true);
 
1497
      }
 
1498
      else
 
1499
      {
 
1500
        throw JsonReaderException.Create(this, "Error parsing boolean value.");
 
1501
      }
 
1502
    }
 
1503
 
 
1504
    private void ParseNull()
 
1505
    {
 
1506
      if (MatchValueWithTrailingSeperator(JsonConvert.Null))
 
1507
      {
 
1508
        SetToken(JsonToken.Null);
 
1509
      }
 
1510
      else
 
1511
      {
 
1512
        throw JsonReaderException.Create(this, "Error parsing null value.");
 
1513
      }
 
1514
    }
 
1515
 
 
1516
    private void ParseUndefined()
 
1517
    {
 
1518
      if (MatchValueWithTrailingSeperator(JsonConvert.Undefined))
 
1519
      {
 
1520
        SetToken(JsonToken.Undefined);
 
1521
      }
 
1522
      else
 
1523
      {
 
1524
        throw JsonReaderException.Create(this, "Error parsing undefined value.");
 
1525
      }
 
1526
    }
 
1527
 
 
1528
    private void ParseFalse()
 
1529
    {
 
1530
      if (MatchValueWithTrailingSeperator(JsonConvert.False))
 
1531
      {
 
1532
        SetToken(JsonToken.Boolean, false);
 
1533
      }
 
1534
      else
 
1535
      {
 
1536
        throw JsonReaderException.Create(this, "Error parsing boolean value.");
 
1537
      }
 
1538
    }
 
1539
 
 
1540
    private void ParseNumberNegativeInfinity()
 
1541
    {
 
1542
      if (MatchValueWithTrailingSeperator(JsonConvert.NegativeInfinity))
 
1543
      {
 
1544
        SetToken(JsonToken.Float, double.NegativeInfinity);
 
1545
      }
 
1546
      else
 
1547
      {
 
1548
        throw JsonReaderException.Create(this, "Error parsing negative infinity value.");
 
1549
      }
 
1550
    }
 
1551
 
 
1552
    private void ParseNumberPositiveInfinity()
 
1553
    {
 
1554
      if (MatchValueWithTrailingSeperator(JsonConvert.PositiveInfinity))
 
1555
      {
 
1556
        SetToken(JsonToken.Float, double.PositiveInfinity);
 
1557
      }
 
1558
      else
 
1559
      {
 
1560
        throw JsonReaderException.Create(this, "Error parsing positive infinity value.");
 
1561
      }
 
1562
    }
 
1563
 
 
1564
    private void ParseNumberNaN()
 
1565
    {
 
1566
      if (MatchValueWithTrailingSeperator(JsonConvert.NaN))
 
1567
      {
 
1568
        SetToken(JsonToken.Float, double.NaN);
 
1569
      }
 
1570
      else
 
1571
      {
 
1572
        throw JsonReaderException.Create(this, "Error parsing NaN value.");
 
1573
      }
 
1574
    }
 
1575
 
 
1576
    /// <summary>
 
1577
    /// Changes the state to closed. 
 
1578
    /// </summary>
 
1579
    public override void Close()
 
1580
    {
 
1581
      base.Close();
 
1582
 
 
1583
      if (CloseInput && _reader != null)
 
1584
#if !(NETFX_CORE || PORTABLE)
 
1585
        _reader.Close();
 
1586
#else
 
1587
        _reader.Dispose();
 
1588
#endif
 
1589
 
 
1590
      if (_buffer != null)
 
1591
        _buffer.Clear();
 
1592
    }
 
1593
 
 
1594
    /// <summary>
 
1595
    /// Gets a value indicating whether the class can return line information.
 
1596
    /// </summary>
 
1597
    /// <returns>
 
1598
    ///         <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>.
 
1599
    /// </returns>
 
1600
    public bool HasLineInfo()
 
1601
    {
 
1602
      return true;
 
1603
    }
 
1604
 
 
1605
    /// <summary>
 
1606
    /// Gets the current line number.
 
1607
    /// </summary>
 
1608
    /// <value>
 
1609
    /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false).
 
1610
    /// </value>
 
1611
    public int LineNumber
 
1612
    {
 
1613
      get
 
1614
      {
 
1615
        if (CurrentState == State.Start && LinePosition == 0)
 
1616
          return 0;
 
1617
 
 
1618
        return _lineNumber;
 
1619
      }
 
1620
    }
 
1621
 
 
1622
    /// <summary>
 
1623
    /// Gets the current line position.
 
1624
    /// </summary>
 
1625
    /// <value>
 
1626
    /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false).
 
1627
    /// </value>
 
1628
    public int LinePosition
 
1629
    {
 
1630
      get { return _charPos - _lineStartPos; }
 
1631
    }
 
1632
  }
 
1633
}
 
 
b'\\ No newline at end of file'