UnescapeBytes() static private method

Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string.
static private UnescapeBytes ( string input ) : ByteString
input string
return ByteString
Esempio n. 1
0
        /// <summary>
        /// If the next token is a string, consume it, unescape it as a
        /// ByteString and return it. Otherwise, throw a FormatException.
        /// </summary>
        public ByteString ConsumeByteString()
        {
            char quote = currentToken.Length > 0 ? currentToken[0] : '\0';

            if (quote != '\"' && quote != '\'')
            {
                throw CreateFormatException("Expected string.");
            }

            if (currentToken.Length < 2 ||
                currentToken[currentToken.Length - 1] != quote)
            {
                throw CreateFormatException("String missing ending quote.");
            }

            try
            {
                string     escaped = currentToken.Substring(1, currentToken.Length - 2);
                ByteString result  = TextFormat.UnescapeBytes(escaped);
                NextToken();
                return(result);
            }
            catch (FormatException e)
            {
                throw CreateFormatException(e.Message);
            }
        }
        public void Escape()
        {
            // Escape sequences.
            Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"",
                            TextFormat.EscapeBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"")));
            Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"",
                            TextFormat.EscapeText("\0\u0001\u0007\b\f\n\r\t\v\\\'\""));
            Assert.AreEqual(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\""),
                            TextFormat.UnescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
            Assert.AreEqual("\0\u0001\u0007\b\f\n\r\t\v\\\'\"",
                            TextFormat.UnescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));

            // Unicode handling.
            Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeText("\u1234"));
            Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeBytes(Bytes(0xe1, 0x88, 0xb4)));
            Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\341\\210\\264"));
            Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\341\\210\\264"));
            Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\xe1\\x88\\xb4"));
            Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\xe1\\x88\\xb4"));

            // Errors.
            AssertFormatException(() => TextFormat.UnescapeText("\\x"));
            AssertFormatException(() => TextFormat.UnescapeText("\\z"));
            AssertFormatException(() => TextFormat.UnescapeText("\\"));
        }