On Sun, 04 Sep 2011 13:51:52 -0400, Robert Jacques <sandf...@jhu.edu> wrote:

On Sun, 04 Sep 2011 00:06:47 -0400, Andrei Alexandrescu <seewebsiteforem...@erdani.org> wrote:

On 8/30/11 8:59 PM, Paul D. Anderson wrote:
Can someone clarify for me the status and/or direction of string
formatting in D?
[snip]

I agree there are major inefficiencies and composability problems caused
by a blind toString() that creates a whole new string without any
assistance. So we need to fix that.

There are suggestions to add this method to Object:

void writeTo(void delegate(const(char)[]) sink, string format = null);

Then, the suggestion goes, whether or not we deprecate toString, in the
short term it should be implemented in terms of writeTo.

There are a few questions raised by this proposal:

1. Okay, this takes care of streaming text. How about streaming in
binary format?

2. Since we have a relatively involved "output to text" routine, how
about an "input from text" routine? If writeTo is there, where is readFrom?


Andrei


I'd like to point out that parsing a format string for every object/variable is very inefficient. I'd recommend having the virtual writeTo function accept FormatSpec, like the formatValue routines, and then make the writeTo which takes a format string be final. i.e.:

void writeTo(void delegate(const(char)[]) sink, ref FormatSpec!(Char) format);

void writeTo(void delegate(const(char)[]) sink, string format = null) final {
        auto spec = FormatSpec!char(format);
        writeTo(sink, spec);
}

Hm... I haven't delved (yet) into the specifics of how std.format works, but it seems like it uses this notion.

One thing which became apparent from a reply to Timon early on in this thread. Say you have a struct like this:

struct S
{
   int x, y, z;
   void writeTo(scope Sink s, const(char)[] format = null)
   {
      formattedWrite(s, "(%d,%d,%d)", x, y, z);
   }
}

How to, say, format the output to be hexadecimal? I'd expect you'd just pass "%x" into write to, but formattedWrite would have to be split into 3 calls, unless you wanted to heap-allocate a new string. I suppose you could allocate a stack buffer to hold the whole format string, but it gets a bit tenuous.

I don't even know if FormatSpec would fix this. We may need a more capable formatting facility, which can do loops, or some new way to do the formatting. Actually, can the format string be a range? I guess not since that would require making writeTo a template. Unless that range is some sort of processor that you always use (like FormatSpec, but able to add extra functionality, like looping).

One issue with your idea is that all derived classes will have to alias in the overload.

-Steve

Reply via email to