[phobos] enquote() -- a small function for std.metastrings

Don Clugston dclugston at googlemail.com
Tue Apr 20 08:13:52 PDT 2010


I've found that the function below is invaluable for CTFE programming;
it gets rid of a huge fraction of the ugliness.
I think this function, or something like it, should be in std.metastrings.

==================

/** Escape any quotes and backslashes inside the given string,
 * prefixing them with the given escape sequence. Use `\` to escape
 * once, `\\\` to escape twice.
 */
string enquote(string instr, string escape = `\`)
{
    // This function is critical for compilation speed.
    // Need to minimise the number of allocations.
    // It's worth using copy-on-write even for CTFE.

    for(int i = 0; i < instr.length; ++i)
    {
        if (instr[i] == '"' || instr[i] == '\\')
        {
            string str = instr[0..i] ~ escape;
            int m = i;
            foreach(int k, char c; instr[i+1..$])
            {
                if (c=='"' || c=='\\')
                {
                    str ~= instr[m..i+1+k] ~ escape;
                    m = i+k+1;
                }
            }
            return str ~ instr[m..$];
        }
    }
    return instr;
}

unittest {
    assert(enquote(`"a\"`)==`\"a\\\"`);
    assert(enquote(`abc`)==`abc`);
}


More information about the phobos mailing list