comparison Implab/Formats/JSON/StringTranslator.cs @ 180:c32688129f14 ref20160224

refactoring complete, JSONParser rewritten
author cin
date Thu, 24 Mar 2016 02:30:46 +0300
parents 0c3c69fe225b
children 9428ea36838e
comparison
equal deleted inserted replaced
179:478ef706906a 180:c32688129f14
9 9
10 namespace Implab.Formats.JSON { 10 namespace Implab.Formats.JSON {
11 /// <summary> 11 /// <summary>
12 /// Класс для преобразования экранированной строки JSON 12 /// Класс для преобразования экранированной строки JSON
13 /// </summary> 13 /// </summary>
14 public class StringTranslator : TextScanner<JSONGrammar.TokenType> { 14 static class StringTranslator {
15 static readonly char[] _escMap; 15 static readonly char[] _escMap;
16 static readonly int[] _hexMap; 16 static readonly int[] _hexMap;
17 17
18 static StringTranslator() { 18 static StringTranslator() {
19 var chars = new char[] { 'b', 'f', 't', 'r', 'n', '\\', '/' }; 19 var chars = new char[] { 'b', 'f', 't', 'r', 'n', '\\', '/' };
32 for (int i = 0; i < hexs.Length; i++) 32 for (int i = 0; i < hexs.Length; i++)
33 _hexMap[hexs[i]] = ints[i]; 33 _hexMap[hexs[i]] = ints[i];
34 34
35 } 35 }
36 36
37 public StringTranslator() {
38 }
39
40 public string Translate(string data) {
41 Safe.ArgumentNotNull(data, "data");
42 return Translate(data.ToCharArray());
43 }
44
45 public string Translate(char[] data) {
46 Safe.ArgumentNotNull(data, "data");
47 return Translate(data, data.Length);
48 }
49
50 public string Translate(char[] data, int length) {
51 Safe.ArgumentNotNull(data, "data");
52 Safe.ArgumentInRange(length, 0, data.Length, "length");
53
54 var translated = new char[length];
55
56 Feed(data,length);
57
58 int pos = 0;
59
60 while (ReadTokenInternal()) {
61 switch ((JSONGrammar.TokenType)Tags[0]) {
62 case JSONGrammar.TokenType.UnescapedChar:
63 Array.Copy(m_buffer,m_tokenOffset,translated,pos,m_tokenLen);
64 pos += m_tokenLen;
65 break;
66 case JSONGrammar.TokenType.EscapedChar:
67 translated[pos] = _escMap[m_buffer[m_tokenOffset + 1]];
68 pos++;
69 break;
70 case JSONGrammar.TokenType.EscapedUnicode:
71 translated[pos] = TranslateHexUnicode(m_buffer,m_tokenOffset + 2);
72 pos++;
73 break;
74 }
75 }
76
77 return new String(translated, 0, pos);
78 }
79
80 internal static char TranslateEscapedChar(char symbol) { 37 internal static char TranslateEscapedChar(char symbol) {
81 return _escMap[symbol]; 38 return _escMap[symbol];
82 } 39 }
83 40
84 internal static char TranslateHexUnicode(char[] symbols, int offset) { 41 internal static char TranslateHexUnicode(char[] symbols, int offset) {