libostd/examples/format.cc

94 lines
2.4 KiB
C++
Raw Normal View History

#include <tuple>
2016-02-03 22:21:53 +01:00
#include <ostd/algorithm.hh>
#include <ostd/vector.hh>
#include <ostd/unordered_map.hh>
2016-02-03 22:21:53 +01:00
#include <ostd/range.hh>
#include <ostd/io.hh>
using namespace ostd;
using namespace ostd::string_literals;
2016-02-03 22:21:53 +01:00
struct Foo {
};
/* implementing formatting for custom objects - external function */
template<typename R>
2017-02-16 20:39:05 +01:00
void to_format(Foo const &, R &writer, format_spec const &fs) {
2016-02-03 22:21:53 +01:00
switch (fs.spec()) {
2016-08-03 17:50:06 +02:00
case 'i':
range_put_all(writer, "Foo1"_sr);
2016-08-03 17:50:06 +02:00
break;
default:
range_put_all(writer, "Foo2"_sr);
2016-08-03 17:50:06 +02:00
break;
2016-02-03 22:21:53 +01:00
}
}
struct Bar {
/* implementing formatting for custom objects - method */
template<typename R>
2017-02-16 20:39:05 +01:00
void to_format(R &writer, format_spec const &fs) const {
2016-02-03 22:21:53 +01:00
switch (fs.spec()) {
2016-08-03 17:50:06 +02:00
case 'i':
range_put_all(writer, "Bar1"_sr);
2016-08-03 17:50:06 +02:00
break;
default:
range_put_all(writer, "Bar2"_sr);
2016-08-03 17:50:06 +02:00
break;
2016-02-03 22:21:53 +01:00
}
}
};
int main() {
2017-01-25 01:44:22 +01:00
std::vector<int> x = { 5, 10, 15, 20 };
2016-02-03 22:21:53 +01:00
writefln("[%(%s|%)]", x);
writefln("%s", x);
2016-02-03 22:21:53 +01:00
int y[] = { 2, 4, 8, 16, 32 };
writefln("{ %(%s, %) }", y);
writefln("[\n%([ %(%s, %) ]%|,\n%)\n]", map(range(10), [](int v) {
return range(v + 1);
}));
std::unordered_map<std::string, int> m = {
2016-02-03 22:21:53 +01:00
{ "foo", 5 },
{ "bar", 10 },
{ "baz", 15 }
};
/* strings and chars are automatically escaped */
writefln("{ %#(%s: %d, %) }", m);
/* can override escaping with the - flag,
* # flag expands the element into multiple values
*/
writefln("{ %-#(%s: %d, %) }", m);
/* without expansion */
writefln("{ %(%s, %) }", m);
/* tuple formatting */
std::tuple<std::string, int, float> tup{"hello world", 1337, 3.14f};
writefln("the tuple contains %<%s, %d, %f%>.", tup);
2016-02-03 22:21:53 +01:00
/* tuple format test */
std::tuple<int, float, char const *> xt[] = {
std::make_tuple(5, 3.14f, "foo"),
std::make_tuple(3, 1.23f, "bar"),
std::make_tuple(9, 8.66f, "baz")
2016-02-03 22:21:53 +01:00
};
writefln("[ %#(<%d|%f|%s>%|, %) ]", xt);
/* custom format */
2016-05-25 18:12:28 +02:00
writefln("%s", Foo{});
writefln("%i", Foo{});
2016-02-03 22:21:53 +01:00
/* custom format via method */
2016-05-25 18:12:28 +02:00
writefln("%s", Bar{});
writefln("%i", Bar{});
2016-02-03 22:21:53 +01:00
/* format into string */
2017-02-18 17:25:49 +01:00
auto s = appender_range<std::string>{};
2016-02-03 22:21:53 +01:00
format(s, "hello %s", "world");
writeln(s.get());
2016-02-07 22:17:15 +01:00
}