示例#1
0
        public static string ParseString(this TextReader reader, ref int c)
        {
            if (!c.IsQuoteChar())
            {
                return(null);
            }

            int q  = c;
            var sb = new StringBuilder();

            while (true)
            {
                c = reader.Read();
                if (c < 0)
                {
                    return(null);
                }
                if (c == q)
                {
                    c = reader.Read();
                    break;
                }

                if (c == '\\')
                {
                    c = reader.Read();
                    if (c == 'u')
                    {
                        int h = 0;
                        for (int i = 0; i < 4; ++i)
                        {
                            c = reader.Read();
                            if (c < 0)
                            {
                                throw new FormatException("Unexpected end of stream");
                            }
                            if (!c.IsHexDigit())
                            {
                                throw new FormatException(
                                          string.Format("Bad unicode symbol. '{0}' is not hex digit.", (char)c));
                            }
                            h += Hex.ToDecimal(c);
                        }
                        sb.Append((char)h);
                    }
                    else if (c == 'x')
                    {
                        int h = 0;
                        int n = 0;
                        while (true)
                        {
                            c = reader.Read();
                            if (c < 0)
                            {
                                throw new FormatException("Unexpected end of stream");
                            }
                            if (!c.IsHexDigit())
                            {
                                break;
                            }
                            ++n;
                            h += Hex.ToDecimal(c);
                        }
                        if (n == 0)
                        {
                            sb.Append("\\x");
                        }
                        else
                        {
                            sb.Append((char)h);
                        }
                    }
                    else if (Escaper.UnescapeChar(ref c))
                    {
                        sb.Append((char)c);
                    }
                    else
                    {
                        sb.Append('\\');
                        sb.Append((char)c);
                    }
                }
                else
                {
                    sb.Append((char)c);
                }
            }

            return(sb.ToString());
        }