API: string formatting / memory management

Johannes Pfau via Digitalmars-d digitalmars-d at puremagic.com
Fri Jul 11 08:18:54 PDT 2014


Am Fri, 11 Jul 2014 14:36:30 +0000
schrieb "Dicebot" <public at dicebot.lv>:

> Round of a formal review before proceeding to voting. Subject for 
> Phobos inclusion : http://wiki.dlang.org/Review/std.logger 
> authored by Robert Schadek.
> 
> Code:
>      https://github.com/D-Programming-Language/phobos/pull/1500

https://github.com/D-Programming-Language/phobos/pull/1500/files#diff-165d04f1fd1a1db2c37af18580f41fb4R421
The 'frontend' log methods call format and the pass the formatted string
to the Logger implementations.

I still wonder if we can do better, and if we need to
modify the API for that.

I've got three ideas:

* Using some sort of static buffer in the log* functions. I don't like
  this that much cause it will limit the msg string length
* Use malloc: This way no GC allocations, but still dynamic memory
  allocation which might not be necessary if you log e.g. to the
  console or a file.

These two options have the benefit that the API can remain unchanged
and they could be implemented after the review.



The third option requires changes to the API. We overload
------------------
writeLogMsg(ref LoggerPayload payload);
with
writeLogHeader(ref LoggerPayload header);
------------------

And add another function:
------------------
void put(/*scope*/ const(char)[] msg);
------------------

writeLogHeader would receive all data as usual, except for the message
string. Then after calling writeLogHeader, the (formatted) message
string will be passed in any number of calls to put.

I used put here to make this output-range compatible. This way it plugs
directly into formattedWrite.


An logger can still receive the complete string by appending the chunks
received in put but we might need some 'finish' function to signal the
end of the message. I guess not all loggers can fit into this
interface, so we should try to make this optional. But simple loggers
(file, console) which write the header first and the message last could
work without any dynamic memory allocation. (formattedWrite probably
uses an fixed-size buffer on the stack, but that's fine)


More information about the Digitalmars-d mailing list