Skip to content

Instantly share code, notes, and snippets.

@PetarKirov
Created October 8, 2021 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PetarKirov/dc7b5d386bf3a853a9b4a4ea85304095 to your computer and use it in GitHub Desktop.
Save PetarKirov/dc7b5d386bf3a853a9b4a4ea85304095 to your computer and use it in GitHub Desktop.
Generic basic toString example in D
void genericToString(T, Writer)(scope ref const T obj, scope ref Writer writer)
{
import std.format : formattedWrite;
writer.formattedWrite("Transaction {\n");
writer.formattedWrite!" from: 0x%s\n"(obj.from.chars);
writer.formattedWrite!" to: 0x%s\n"(obj.to.chars);
writer.formattedWrite("}");
}
struct Address { char[40] chars; }
struct Transaction
{
Address from;
Address to;
void toString(Writer)(scope ref Writer writer)
{
this.genericToString(writer);
}
}
unittest
{
import std.array : appender;
auto t = Transaction(
Address("DcE029Dc77087DE89ED1B9DAe8b6007272fbFc2A"),
Address("2bc71FD2010fD525885491ff0Db7C530F1a207E4")
);
auto a = appender!string;
t.toString(a);
import std.stdio;
a[].writeln;
auto s = "
Transaction {
from: 0xDcE029Dc77087DE89ED1B9DAe8b6007272fbFc2A
to: 0x2bc71FD2010fD525885491ff0Db7C530F1a207E4
}".outdent;
s.writefln!"---\n%s\n---";
}
/++
Removes leading whitespace indentation from each line in the range.
Params:
range = range of characters on which to operate
levelsOfIndentation = number of repetition of indent; 1 level by default
indent = whitespace used for indentation; 4 spaces by default
Returns:
The resulting range with each line stripped from `levelsOfIndentation` number of occurances of `indent`.
++/
auto outdent(Range)(auto ref Range range, uint levelsOfIndentation = 1, string indent = " ")
{
import std.array : array;
import std.algorithm : map, joiner;
import std.range : repeat;
import std.string : lineSplitter, skipPrefix = chompPrefix;
import std.typecons : Yes;
auto leadingIndent = indent;//.repeat(levelsOfIndentation).joiner.array;
return range
.skipPrefix("\n")
.lineSplitter!(Yes.keepTerminator)
.map!(line => line.skipPrefix(leadingIndent))
.joiner;
}
pure @safe
unittest
{
import std.array : array;
import std.string : splitLines;
auto s = "
Transaction {
from: 0xDcE029Dc77087DE89ED1B9DAe8b6007272fbFc2A
to: 0x2bc71FD2010fD525885491ff0Db7C530F1a207E4
}".outdent;
assert(s.array.splitLines == [
"Transaction {"d,
" from: 0xDcE029Dc77087DE89ED1B9DAe8b6007272fbFc2A",
" to: 0x2bc71FD2010fD525885491ff0Db7C530F1a207E4",
"}"
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment