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

Andrei Alexandrescu andrei at erdani.com
Tue Apr 20 08:20:36 PDT 2010


Great. I suggest we actually put that in std.string such that run-time 
code could use it as well.

Andrei

On 04/20/2010 10:13 AM, Don Clugston wrote:
> 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`);
> }
> _______________________________________________
> phobos mailing list
> phobos at puremagic.com
> http://lists.puremagic.com/mailman/listinfo/phobos


More information about the phobos mailing list