JsonTokenizer.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Globalization;
  35. using System.IO;
  36. using System.Text;
  37. namespace Google.Protobuf
  38. {
  39. /// <summary>
  40. /// Simple but strict JSON tokenizer, rigidly following RFC 7159.
  41. /// </summary>
  42. /// <remarks>
  43. /// <para>
  44. /// This tokenizer is stateful, and only returns "useful" tokens - names, values etc.
  45. /// It does not create tokens for the separator between names and values, or for the comma
  46. /// between values. It validates the token stream as it goes - so callers can assume that the
  47. /// tokens it produces are appropriate. For example, it would never produce "start object, end array."
  48. /// </para>
  49. /// <para>Not thread-safe.</para>
  50. /// </remarks>
  51. internal sealed class JsonTokenizer
  52. {
  53. // The set of states in which a value is valid next token.
  54. private static readonly State ValueStates = State.ArrayStart | State.ArrayAfterComma | State.ObjectAfterColon | State.StartOfDocument;
  55. private readonly Stack<ContainerType> containerStack = new Stack<ContainerType>();
  56. private readonly PushBackReader reader;
  57. private JsonToken bufferedToken;
  58. private State state;
  59. private int objectDepth = 0;
  60. /// <summary>
  61. /// Returns the depth of the stack, purely in objects (not collections).
  62. /// Informally, this is the number of remaining unclosed '{' characters we have.
  63. /// </summary>
  64. internal int ObjectDepth { get { return objectDepth; } }
  65. internal JsonTokenizer(TextReader reader)
  66. {
  67. this.reader = new PushBackReader(reader);
  68. state = State.StartOfDocument;
  69. containerStack.Push(ContainerType.Document);
  70. }
  71. // TODO: Why do we allow a different token to be pushed back? It might be better to always remember the previous
  72. // token returned, and allow a parameterless Rewind() method (which could only be called once, just like the current PushBack).
  73. internal void PushBack(JsonToken token)
  74. {
  75. if (bufferedToken != null)
  76. {
  77. throw new InvalidOperationException("Can't push back twice");
  78. }
  79. bufferedToken = token;
  80. if (token.Type == JsonToken.TokenType.StartObject)
  81. {
  82. objectDepth--;
  83. }
  84. else if (token.Type == JsonToken.TokenType.EndObject)
  85. {
  86. objectDepth++;
  87. }
  88. }
  89. /// <summary>
  90. /// Returns the next JSON token in the stream. An EndDocument token is returned to indicate the end of the stream,
  91. /// after which point <c>Next()</c> should not be called again.
  92. /// </summary>
  93. /// <remarks>
  94. /// This method essentially just loops through characters skipping whitespace, validating and
  95. /// changing state (e.g. from ObjectBeforeColon to ObjectAfterColon)
  96. /// until it reaches something which will be a genuine token (e.g. a start object, or a value) at which point
  97. /// it returns the token. Although the method is large, it would be relatively hard to break down further... most
  98. /// of it is the large switch statement, which sometimes returns and sometimes doesn't.
  99. /// </remarks>
  100. /// <returns>The next token in the stream. This is never null.</returns>
  101. /// <exception cref="InvalidOperationException">This method is called after an EndDocument token has been returned</exception>
  102. /// <exception cref="InvalidJsonException">The input text does not comply with RFC 7159</exception>
  103. internal JsonToken Next()
  104. {
  105. if (bufferedToken != null)
  106. {
  107. var ret = bufferedToken;
  108. bufferedToken = null;
  109. if (ret.Type == JsonToken.TokenType.StartObject)
  110. {
  111. objectDepth++;
  112. }
  113. else if (ret.Type == JsonToken.TokenType.EndObject)
  114. {
  115. objectDepth--;
  116. }
  117. return ret;
  118. }
  119. if (state == State.ReaderExhausted)
  120. {
  121. throw new InvalidOperationException("Next() called after end of document");
  122. }
  123. while (true)
  124. {
  125. var next = reader.Read();
  126. if (next == null)
  127. {
  128. ValidateState(State.ExpectedEndOfDocument, "Unexpected end of document in state: ");
  129. state = State.ReaderExhausted;
  130. return JsonToken.EndDocument;
  131. }
  132. switch (next.Value)
  133. {
  134. // Skip whitespace between tokens
  135. case ' ':
  136. case '\t':
  137. case '\r':
  138. case '\n':
  139. break;
  140. case ':':
  141. ValidateState(State.ObjectBeforeColon, "Invalid state to read a colon: ");
  142. state = State.ObjectAfterColon;
  143. break;
  144. case ',':
  145. ValidateState(State.ObjectAfterProperty | State.ArrayAfterValue, "Invalid state to read a colon: ");
  146. state = state == State.ObjectAfterProperty ? State.ObjectAfterComma : State.ArrayAfterComma;
  147. break;
  148. case '"':
  149. string stringValue = ReadString();
  150. if ((state & (State.ObjectStart | State.ObjectAfterComma)) != 0)
  151. {
  152. state = State.ObjectBeforeColon;
  153. return JsonToken.Name(stringValue);
  154. }
  155. else
  156. {
  157. ValidateAndModifyStateForValue("Invalid state to read a double quote: ");
  158. return JsonToken.Value(stringValue);
  159. }
  160. case '{':
  161. ValidateState(ValueStates, "Invalid state to read an open brace: ");
  162. state = State.ObjectStart;
  163. containerStack.Push(ContainerType.Object);
  164. objectDepth++;
  165. return JsonToken.StartObject;
  166. case '}':
  167. ValidateState(State.ObjectAfterProperty | State.ObjectStart, "Invalid state to read a close brace: ");
  168. PopContainer();
  169. objectDepth--;
  170. return JsonToken.EndObject;
  171. case '[':
  172. ValidateState(ValueStates, "Invalid state to read an open square bracket: ");
  173. state = State.ArrayStart;
  174. containerStack.Push(ContainerType.Array);
  175. return JsonToken.StartArray;
  176. case ']':
  177. ValidateState(State.ArrayAfterValue | State.ArrayStart, "Invalid state to read a close square bracket: ");
  178. PopContainer();
  179. return JsonToken.EndArray;
  180. case 'n': // Start of null
  181. ConsumeLiteral("null");
  182. ValidateAndModifyStateForValue("Invalid state to read a null literal: ");
  183. return JsonToken.Null;
  184. case 't': // Start of true
  185. ConsumeLiteral("true");
  186. ValidateAndModifyStateForValue("Invalid state to read a true literal: ");
  187. return JsonToken.True;
  188. case 'f': // Start of false
  189. ConsumeLiteral("false");
  190. ValidateAndModifyStateForValue("Invalid state to read a false literal: ");
  191. return JsonToken.False;
  192. case '-': // Start of a number
  193. case '0':
  194. case '1':
  195. case '2':
  196. case '3':
  197. case '4':
  198. case '5':
  199. case '6':
  200. case '7':
  201. case '8':
  202. case '9':
  203. double number = ReadNumber(next.Value);
  204. ValidateAndModifyStateForValue("Invalid state to read a number token: ");
  205. return JsonToken.Value(number);
  206. default:
  207. throw new InvalidJsonException("Invalid first character of token: " + next.Value);
  208. }
  209. }
  210. }
  211. private void ValidateState(State validStates, string errorPrefix)
  212. {
  213. if ((validStates & state) == 0)
  214. {
  215. throw reader.CreateException(errorPrefix + state);
  216. }
  217. }
  218. /// <summary>
  219. /// Reads a string token. It is assumed that the opening " has already been read.
  220. /// </summary>
  221. private string ReadString()
  222. {
  223. var value = new StringBuilder();
  224. bool haveHighSurrogate = false;
  225. while (true)
  226. {
  227. char c = reader.ReadOrFail("Unexpected end of text while reading string");
  228. if (c < ' ')
  229. {
  230. throw reader.CreateException(string.Format(CultureInfo.InvariantCulture, "Invalid character in string literal: U+{0:x4}", (int) c));
  231. }
  232. if (c == '"')
  233. {
  234. if (haveHighSurrogate)
  235. {
  236. throw reader.CreateException("Invalid use of surrogate pair code units");
  237. }
  238. return value.ToString();
  239. }
  240. if (c == '\\')
  241. {
  242. c = ReadEscapedCharacter();
  243. }
  244. // TODO: Consider only allowing surrogate pairs that are either both escaped,
  245. // or both not escaped. It would be a very odd text stream that contained a "lone" high surrogate
  246. // followed by an escaped low surrogate or vice versa... and that couldn't even be represented in UTF-8.
  247. if (haveHighSurrogate != char.IsLowSurrogate(c))
  248. {
  249. throw reader.CreateException("Invalid use of surrogate pair code units");
  250. }
  251. haveHighSurrogate = char.IsHighSurrogate(c);
  252. value.Append(c);
  253. }
  254. }
  255. /// <summary>
  256. /// Reads an escaped character. It is assumed that the leading backslash has already been read.
  257. /// </summary>
  258. private char ReadEscapedCharacter()
  259. {
  260. char c = reader.ReadOrFail("Unexpected end of text while reading character escape sequence");
  261. switch (c)
  262. {
  263. case 'n':
  264. return '\n';
  265. case '\\':
  266. return '\\';
  267. case 'b':
  268. return '\b';
  269. case 'f':
  270. return '\f';
  271. case 'r':
  272. return '\r';
  273. case 't':
  274. return '\t';
  275. case '"':
  276. return '"';
  277. case '/':
  278. return '/';
  279. case 'u':
  280. return ReadUnicodeEscape();
  281. default:
  282. throw reader.CreateException(string.Format(CultureInfo.InvariantCulture, "Invalid character in character escape sequence: U+{0:x4}", (int) c));
  283. }
  284. }
  285. /// <summary>
  286. /// Reads an escaped Unicode 4-nybble hex sequence. It is assumed that the leading \u has already been read.
  287. /// </summary>
  288. private char ReadUnicodeEscape()
  289. {
  290. int result = 0;
  291. for (int i = 0; i < 4; i++)
  292. {
  293. char c = reader.ReadOrFail("Unexpected end of text while reading Unicode escape sequence");
  294. int nybble;
  295. if (c >= '0' && c <= '9')
  296. {
  297. nybble = c - '0';
  298. }
  299. else if (c >= 'a' && c <= 'f')
  300. {
  301. nybble = c - 'a' + 10;
  302. }
  303. else if (c >= 'A' && c <= 'F')
  304. {
  305. nybble = c - 'A' + 10;
  306. }
  307. else
  308. {
  309. throw reader.CreateException(string.Format(CultureInfo.InvariantCulture, "Invalid character in character escape sequence: U+{0:x4}", (int) c));
  310. }
  311. result = (result << 4) + nybble;
  312. }
  313. return (char) result;
  314. }
  315. /// <summary>
  316. /// Consumes a text-only literal, throwing an exception if the read text doesn't match it.
  317. /// It is assumed that the first letter of the literal has already been read.
  318. /// </summary>
  319. private void ConsumeLiteral(string text)
  320. {
  321. for (int i = 1; i < text.Length; i++)
  322. {
  323. char? next = reader.Read();
  324. if (next == null)
  325. {
  326. throw reader.CreateException("Unexpected end of text while reading literal token " + text);
  327. }
  328. if (next.Value != text[i])
  329. {
  330. throw reader.CreateException("Unexpected character while reading literal token " + text);
  331. }
  332. }
  333. }
  334. private double ReadNumber(char initialCharacter)
  335. {
  336. StringBuilder builder = new StringBuilder();
  337. if (initialCharacter == '-')
  338. {
  339. builder.Append("-");
  340. }
  341. else
  342. {
  343. reader.PushBack(initialCharacter);
  344. }
  345. // Each method returns the character it read that doesn't belong in that part,
  346. // so we know what to do next, including pushing the character back at the end.
  347. // null is returned for "end of text".
  348. char? next = ReadInt(builder);
  349. if (next == '.')
  350. {
  351. next = ReadFrac(builder);
  352. }
  353. if (next == 'e' || next == 'E')
  354. {
  355. next = ReadExp(builder);
  356. }
  357. // If we read a character which wasn't part of the number, push it back so we can read it again
  358. // to parse the next token.
  359. if (next != null)
  360. {
  361. reader.PushBack(next.Value);
  362. }
  363. // TODO: What exception should we throw if the value can't be represented as a double?
  364. try
  365. {
  366. return double.Parse(builder.ToString(),
  367. NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
  368. CultureInfo.InvariantCulture);
  369. }
  370. catch (OverflowException)
  371. {
  372. throw reader.CreateException("Numeric value out of range: " + builder);
  373. }
  374. }
  375. private char? ReadInt(StringBuilder builder)
  376. {
  377. char first = reader.ReadOrFail("Invalid numeric literal");
  378. if (first < '0' || first > '9')
  379. {
  380. throw reader.CreateException("Invalid numeric literal");
  381. }
  382. builder.Append(first);
  383. int digitCount;
  384. char? next = ConsumeDigits(builder, out digitCount);
  385. if (first == '0' && digitCount != 0)
  386. {
  387. throw reader.CreateException("Invalid numeric literal: leading 0 for non-zero value.");
  388. }
  389. return next;
  390. }
  391. private char? ReadFrac(StringBuilder builder)
  392. {
  393. builder.Append('.'); // Already consumed this
  394. int digitCount;
  395. char? next = ConsumeDigits(builder, out digitCount);
  396. if (digitCount == 0)
  397. {
  398. throw reader.CreateException("Invalid numeric literal: fraction with no trailing digits");
  399. }
  400. return next;
  401. }
  402. private char? ReadExp(StringBuilder builder)
  403. {
  404. builder.Append('E'); // Already consumed this (or 'e')
  405. char? next = reader.Read();
  406. if (next == null)
  407. {
  408. throw reader.CreateException("Invalid numeric literal: exponent with no trailing digits");
  409. }
  410. if (next == '-' || next == '+')
  411. {
  412. builder.Append(next.Value);
  413. }
  414. else
  415. {
  416. reader.PushBack(next.Value);
  417. }
  418. int digitCount;
  419. next = ConsumeDigits(builder, out digitCount);
  420. if (digitCount == 0)
  421. {
  422. throw reader.CreateException("Invalid numeric literal: exponent without value");
  423. }
  424. return next;
  425. }
  426. private char? ConsumeDigits(StringBuilder builder, out int count)
  427. {
  428. count = 0;
  429. while (true)
  430. {
  431. char? next = reader.Read();
  432. if (next == null || next.Value < '0' || next.Value > '9')
  433. {
  434. return next;
  435. }
  436. count++;
  437. builder.Append(next.Value);
  438. }
  439. }
  440. /// <summary>
  441. /// Validates that we're in a valid state to read a value (using the given error prefix if necessary)
  442. /// and changes the state to the appropriate one, e.g. ObjectAfterColon to ObjectAfterProperty.
  443. /// </summary>
  444. private void ValidateAndModifyStateForValue(string errorPrefix)
  445. {
  446. ValidateState(ValueStates, errorPrefix);
  447. switch (state)
  448. {
  449. case State.StartOfDocument:
  450. state = State.ExpectedEndOfDocument;
  451. return;
  452. case State.ObjectAfterColon:
  453. state = State.ObjectAfterProperty;
  454. return;
  455. case State.ArrayStart:
  456. case State.ArrayAfterComma:
  457. state = State.ArrayAfterValue;
  458. return;
  459. default:
  460. throw new InvalidOperationException("ValidateAndModifyStateForValue does not handle all value states (and should)");
  461. }
  462. }
  463. /// <summary>
  464. /// Pops the top-most container, and sets the state to the appropriate one for the end of a value
  465. /// in the parent container.
  466. /// </summary>
  467. private void PopContainer()
  468. {
  469. containerStack.Pop();
  470. var parent = containerStack.Peek();
  471. switch (parent)
  472. {
  473. case ContainerType.Object:
  474. state = State.ObjectAfterProperty;
  475. break;
  476. case ContainerType.Array:
  477. state = State.ArrayAfterValue;
  478. break;
  479. case ContainerType.Document:
  480. state = State.ExpectedEndOfDocument;
  481. break;
  482. default:
  483. throw new InvalidOperationException("Unexpected container type: " + parent);
  484. }
  485. }
  486. private enum ContainerType
  487. {
  488. Document, Object, Array
  489. }
  490. /// <summary>
  491. /// Possible states of the tokenizer.
  492. /// </summary>
  493. /// <remarks>
  494. /// <para>This is a flags enum purely so we can simply and efficiently represent a set of valid states
  495. /// for checking.</para>
  496. /// <para>
  497. /// Each is documented with an example,
  498. /// where ^ represents the current position within the text stream. The examples all use string values,
  499. /// but could be any value, including nested objects/arrays.
  500. /// The complete state of the tokenizer also includes a stack to indicate the contexts (arrays/objects).
  501. /// Any additional notional state of "AfterValue" indicates that a value has been completed, at which
  502. /// point there's an immediate transition to ExpectedEndOfDocument, ObjectAfterProperty or ArrayAfterValue.
  503. /// </para>
  504. /// <para>
  505. /// These states were derived manually by reading RFC 7159 carefully.
  506. /// </para>
  507. /// </remarks>
  508. [Flags]
  509. private enum State
  510. {
  511. /// <summary>
  512. /// ^ { "foo": "bar" }
  513. /// Before the value in a document. Next states: ObjectStart, ArrayStart, "AfterValue"
  514. /// </summary>
  515. StartOfDocument = 1 << 0,
  516. /// <summary>
  517. /// { "foo": "bar" } ^
  518. /// After the value in a document. Next states: ReaderExhausted
  519. /// </summary>
  520. ExpectedEndOfDocument = 1 << 1,
  521. /// <summary>
  522. /// { "foo": "bar" } ^ (and already read to the end of the reader)
  523. /// Terminal state.
  524. /// </summary>
  525. ReaderExhausted = 1 << 2,
  526. /// <summary>
  527. /// { ^ "foo": "bar" }
  528. /// Before the *first* property in an object.
  529. /// Next states:
  530. /// "AfterValue" (empty object)
  531. /// ObjectBeforeColon (read a name)
  532. /// </summary>
  533. ObjectStart = 1 << 3,
  534. /// <summary>
  535. /// { "foo" ^ : "bar", "x": "y" }
  536. /// Next state: ObjectAfterColon
  537. /// </summary>
  538. ObjectBeforeColon = 1 << 4,
  539. /// <summary>
  540. /// { "foo" : ^ "bar", "x": "y" }
  541. /// Before any property other than the first in an object.
  542. /// (Equivalently: after any property in an object)
  543. /// Next states:
  544. /// "AfterValue" (value is simple)
  545. /// ObjectStart (value is object)
  546. /// ArrayStart (value is array)
  547. /// </summary>
  548. ObjectAfterColon = 1 << 5,
  549. /// <summary>
  550. /// { "foo" : "bar" ^ , "x" : "y" }
  551. /// At the end of a property, so expecting either a comma or end-of-object
  552. /// Next states: ObjectAfterComma or "AfterValue"
  553. /// </summary>
  554. ObjectAfterProperty = 1 << 6,
  555. /// <summary>
  556. /// { "foo":"bar", ^ "x":"y" }
  557. /// Read the comma after the previous property, so expecting another property.
  558. /// This is like ObjectStart, but closing brace isn't valid here
  559. /// Next state: ObjectBeforeColon.
  560. /// </summary>
  561. ObjectAfterComma = 1 << 7,
  562. /// <summary>
  563. /// [ ^ "foo", "bar" ]
  564. /// Before the *first* value in an array.
  565. /// Next states:
  566. /// "AfterValue" (read a value)
  567. /// "AfterValue" (end of array; will pop stack)
  568. /// </summary>
  569. ArrayStart = 1 << 8,
  570. /// <summary>
  571. /// [ "foo" ^ , "bar" ]
  572. /// After any value in an array, so expecting either a comma or end-of-array
  573. /// Next states: ArrayAfterComma or "AfterValue"
  574. /// </summary>
  575. ArrayAfterValue = 1 << 9,
  576. /// <summary>
  577. /// [ "foo", ^ "bar" ]
  578. /// After a comma in an array, so there *must* be another value (simple or complex).
  579. /// Next states: "AfterValue" (simple value), StartObject, StartArray
  580. /// </summary>
  581. ArrayAfterComma = 1 << 10
  582. }
  583. /// <summary>
  584. /// Wrapper around a text reader allowing small amounts of buffering and location handling.
  585. /// </summary>
  586. private class PushBackReader
  587. {
  588. // TODO: Add locations for errors etc.
  589. private readonly TextReader reader;
  590. internal PushBackReader(TextReader reader)
  591. {
  592. // TODO: Wrap the reader in a BufferedReader?
  593. this.reader = reader;
  594. }
  595. /// <summary>
  596. /// The buffered next character, if we have one.
  597. /// </summary>
  598. private char? nextChar;
  599. /// <summary>
  600. /// Returns the next character in the stream, or null if we have reached the end.
  601. /// </summary>
  602. /// <returns></returns>
  603. internal char? Read()
  604. {
  605. if (nextChar != null)
  606. {
  607. char? tmp = nextChar;
  608. nextChar = null;
  609. return tmp;
  610. }
  611. int next = reader.Read();
  612. return next == -1 ? null : (char?) next;
  613. }
  614. internal char ReadOrFail(string messageOnFailure)
  615. {
  616. char? next = Read();
  617. if (next == null)
  618. {
  619. throw CreateException(messageOnFailure);
  620. }
  621. return next.Value;
  622. }
  623. internal void PushBack(char c)
  624. {
  625. if (nextChar != null)
  626. {
  627. throw new InvalidOperationException("Cannot push back when already buffering a character");
  628. }
  629. nextChar = c;
  630. }
  631. /// <summary>
  632. /// Creates a new exception appropriate for the current state of the reader.
  633. /// </summary>
  634. internal InvalidJsonException CreateException(string message)
  635. {
  636. // TODO: Keep track of and use the location.
  637. return new InvalidJsonException(message);
  638. }
  639. }
  640. }
  641. }