/// <summary> /// Returns true if it quoted. /// </summary> public static bool QuoteValue(string str, StringBuilder sb, bool force = false) { int ich = sb.Length; bool f = QuoteValueCore(str, sb, force); #if DEBUG // Verify the result. string v = sb.ToString(ich, sb.Length - ich); var curs = new CharCursor(v); Contracts.Assert(f == (force || curs.ChCur == '{')); var lex = new CmdLexer(curs); var res = new StringBuilder(); // If it was quoted, gathering curly contents should get us the original. Otherwise, // the result should be equivalent to the original and should be a single token. if (f) { Contracts.Assert(v.StartsWith("{") && v.EndsWith("}")); lex.GatherCurlyContents(res); } else { lex.GetToken(res); } Contracts.Assert(!lex.Error); Contracts.Assert(curs.Eof); Contracts.Assert(str == res.ToString()); #endif return(f); }
public static bool NeedsQuoting(StringBuilder sb, int ich) { Contracts.AssertValue(sb); Contracts.Assert(0 <= ich && ich <= sb.Length); if (ich >= sb.Length) { return(true); } if (sb[ich] == '{') { return(true); } // See if we need to quote. If lexing produces a single token with the exact // same value, then we don't need to. int ichLim = sb.Length; int cch = ichLim - ich; var curs = new CharCursor(sb.ToString(ich, cch)); var lex = new CmdLexer(curs); lex.GetToken(sb); Contracts.Assert(curs.IchCur > 0 || lex.Error); try { if (!lex.Error && curs.Eof && sb.Length == ichLim + cch) { // See if the characters match. for (int ichSrc = ich; ; ichSrc++) { if (ichSrc >= ichLim) { return(false); } if (sb[ichSrc] != sb[ichSrc + cch]) { break; } } } return(true); } finally { sb.Length = ich + cch; } }
// Determines whether str needs quoting. If not, appends the string to sb and returns try. // If so, sb's contents are preserved and returns false. private static bool TryNoQuoting(string str, StringBuilder sb) { Contracts.AssertNonEmpty(str); if (str[0] == '{') { return(false); } int ichDst = sb.Length; // See if we need to quote. If lexing produces a single token with the exact // same value, then we don't need to. var curs = new CharCursor(str); var lex = new CmdLexer(curs); lex.GetToken(sb); Contracts.Assert(curs.IchCur > 0 || lex.Error); if (!lex.Error && curs.Eof && sb.Length == ichDst + str.Length) { // See if the characters match. for (int ichSrc = 0; ; ichSrc++) { if (ichSrc >= str.Length) { return(true); } if (sb[ichDst + ichSrc] != str[ichSrc]) { break; } } } // Reset the string builder. sb.Length = ichDst; return(false); }