diff options
Diffstat (limited to '')
| -rw-r--r-- | src/tools/format.cpp | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/src/tools/format.cpp b/src/tools/format.cpp new file mode 100644 index 0000000..6a2f3bd --- /dev/null +++ b/src/tools/format.cpp | |||
| @@ -0,0 +1,88 @@ | |||
| 1 | #include <bu/string.h> | ||
| 2 | #include <bu/formatter.h> | ||
| 3 | #include <bu/sio.h> | ||
| 4 | #include <bu/variant.h> | ||
| 5 | #include <bu/membuf.h> | ||
| 6 | |||
| 7 | using namespace Bu; | ||
| 8 | |||
| 9 | class Fmter | ||
| 10 | { | ||
| 11 | public: | ||
| 12 | Fmter( const Bu::String &sSrc ) : | ||
| 13 | sSrc( sSrc ) | ||
| 14 | { | ||
| 15 | } | ||
| 16 | |||
| 17 | template<typename T> | ||
| 18 | Fmter &arg( const T &x ) | ||
| 19 | { | ||
| 20 | lParm.append( Pair( x ) ); | ||
| 21 | |||
| 22 | return *this; | ||
| 23 | } | ||
| 24 | |||
| 25 | template<typename T> | ||
| 26 | Fmter &arg( const T &x, Bu::Formatter::Fmt f ) | ||
| 27 | { | ||
| 28 | lParm.append( Pair( x, f ) ); | ||
| 29 | |||
| 30 | return *this; | ||
| 31 | } | ||
| 32 | |||
| 33 | operator Bu::String() const | ||
| 34 | { | ||
| 35 | Bu::MemBuf mbOut; | ||
| 36 | Bu::Formatter f( mbOut ); | ||
| 37 | ParmList::const_iterator i = lParm.begin(); | ||
| 38 | for( Bu::String::const_iterator s = sSrc.begin(); s; s++ ) | ||
| 39 | { | ||
| 40 | if( *s == '%' ) | ||
| 41 | { | ||
| 42 | f << (*i).format << (*i).value; | ||
| 43 | i++; | ||
| 44 | } | ||
| 45 | else | ||
| 46 | { | ||
| 47 | f << *s; | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | return mbOut.getString(); | ||
| 52 | } | ||
| 53 | |||
| 54 | private: | ||
| 55 | const Bu::String &sSrc; | ||
| 56 | class Pair | ||
| 57 | { | ||
| 58 | public: | ||
| 59 | template<typename T> | ||
| 60 | Pair( const T &v ) : | ||
| 61 | value( v ) | ||
| 62 | { | ||
| 63 | } | ||
| 64 | |||
| 65 | template<typename T> | ||
| 66 | Pair( const T &v, Bu::Formatter::Fmt f ) : | ||
| 67 | value( v ), | ||
| 68 | format( f ) | ||
| 69 | { | ||
| 70 | } | ||
| 71 | |||
| 72 | Bu::Variant value; | ||
| 73 | Bu::Formatter::Fmt format; | ||
| 74 | }; | ||
| 75 | typedef Bu::List<Pair> ParmList; | ||
| 76 | ParmList lParm; | ||
| 77 | }; | ||
| 78 | |||
| 79 | Bu::Formatter &operator<<( Bu::Formatter &f, const Fmter &r ) | ||
| 80 | { | ||
| 81 | return f << (Bu::String)r; | ||
| 82 | } | ||
| 83 | |||
| 84 | int main() | ||
| 85 | { | ||
| 86 | sio << Fmter("A word is % and a number is % %.").arg("Hello").arg(75, Fmt::hex() ).arg(" - ") << sio.nl; | ||
| 87 | } | ||
| 88 | |||
