aboutsummaryrefslogtreecommitdiff
path: root/src/tools/format.cpp
blob: 6a2f3bd245d79be8c59b56fa657dc3f73ff822be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <bu/string.h>
#include <bu/formatter.h>
#include <bu/sio.h>
#include <bu/variant.h>
#include <bu/membuf.h>

using namespace Bu;

class Fmter
{
public:
	Fmter( const Bu::String &sSrc ) :
		sSrc( sSrc )
	{
	}

	template<typename T>
	Fmter &arg( const T &x )
	{
		lParm.append( Pair( x ) );

		return *this;
	}

	template<typename T>
	Fmter &arg( const T &x, Bu::Formatter::Fmt f )
	{
		lParm.append( Pair( x, f ) );

		return *this;
	}

	operator Bu::String() const
	{
		Bu::MemBuf mbOut;
		Bu::Formatter f( mbOut );
		ParmList::const_iterator i = lParm.begin();
		for( Bu::String::const_iterator s = sSrc.begin(); s; s++ )
		{
			if( *s == '%' )
			{
				f << (*i).format << (*i).value;
				i++;
			}
			else
			{
				f << *s;
			}
		}

		return mbOut.getString();
	}

private:
	const Bu::String &sSrc;
	class Pair
	{
	public:
		template<typename T>
		Pair( const T &v ) :
			value( v )
		{
		}

		template<typename T>
		Pair( const T &v, Bu::Formatter::Fmt f ) :
			value( v ),
			format( f )
		{
		}

		Bu::Variant value;
		Bu::Formatter::Fmt format;
	};
	typedef Bu::List<Pair> ParmList;
	ParmList lParm;
};

Bu::Formatter &operator<<( Bu::Formatter &f, const Fmter &r )
{
	return f << (Bu::String)r;
}

int main()
{
	sio << Fmter("A word is % and a number is % %.").arg("Hello").arg(75, Fmt::hex() ).arg(" - ") << sio.nl;
}