Esempio n. 1
0
        // adapted directly from minecraft's (decompiled) source
        private static string QuoteAndEscape(string input, SnbtOptions.QuoteMode mode, bool escape_newlines)
        {
            const char PLACEHOLDER_QUOTE = '\0';
            var        builder           = new StringBuilder(PLACEHOLDER_QUOTE.ToString()); // dummy value to be replaced at end
            char       preferred_quote;

            if (mode == SnbtOptions.QuoteMode.DoubleQuotes)
            {
                preferred_quote = '"';
            }
            else if (mode == SnbtOptions.QuoteMode.SingleQuotes)
            {
                preferred_quote = '\'';
            }
            else
            {
                preferred_quote = PLACEHOLDER_QUOTE; // dummy value when we're not sure which quote type to use yet
            }
            foreach (char c in input)
            {
                if (c == STRING_ESCAPE)
                {
                    builder.Append(STRING_ESCAPE);
                }
                else if (c == STRING_PRIMARY_QUOTE || c == STRING_SECONDARY_QUOTE)
                {
                    // if we find one of the quotes in the actual string text, use the other one for quoting
                    if (preferred_quote == PLACEHOLDER_QUOTE)
                    {
                        preferred_quote = (c == STRING_PRIMARY_QUOTE ? STRING_SECONDARY_QUOTE : STRING_PRIMARY_QUOTE);
                    }
                    if (c == preferred_quote)
                    {
                        builder.Append(STRING_ESCAPE);
                    }
                }
                if (escape_newlines && c == '\n')
                {
                    builder.Append(STRING_ESCAPE + "n");
                }
                else
                {
                    builder.Append(c);
                }
            }
            if (preferred_quote == PLACEHOLDER_QUOTE)
            {
                preferred_quote = STRING_PRIMARY_QUOTE;
            }
            builder[0] = preferred_quote;
            builder.Append(preferred_quote);
            return(builder.ToString());
        }
Esempio n. 2
0
 private static string QuoteIfRequested(string str, Predicate <string> should_quote, SnbtOptions.QuoteMode mode, bool escape_newlines)
 {
     if (should_quote(str))
     {
         return(QuoteAndEscape(str, mode, escape_newlines));
     }
     else
     {
         return(str);
     }
 }