]> git.tdb.fi Git - libs/core.git/blob - source/time/timedelta.cpp
Use format instead of stringstream in TimeDelta
[libs/core.git] / source / time / timedelta.cpp
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2006  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <msp/strings/format.h>
9 #include "timedelta.h"
10 #include "units.h"
11
12 using namespace std;
13
14 namespace {
15
16 using Msp::Time::RawTime;
17
18 string format_part(RawTime &value, RawTime unit, char sep, bool &first)
19 {
20         if(value<unit && first)
21                 return string();
22
23         RawTime v = value/unit;
24         value %= unit;
25         if(first)
26         {
27                 first = false;
28                 return Msp::format("%d", v);
29         }
30         else
31                 return Msp::format("%c%02d", sep, v);
32 }
33
34 }
35
36 namespace Msp {
37 namespace Time {
38
39 void operator<<(LexicalConverter &conv, const TimeDelta &td)
40 {
41         string result;
42
43         RawTime value = td.raw();
44
45         if(value<0)
46         {
47                 result += '-';
48                 value = -value;
49         }
50
51         if(value==0)
52                 result += '0';
53         else if(value<1000)
54                 result += format("%dµs", value);
55         else if(value<1000000)
56         {
57                 result += format("%d", value/1000);
58                 value %= 1000;
59                 if(value)
60                         result += format(".%03d", value);
61                 result += "ms";
62         }
63         else
64         {
65                 bool first = true;
66                 bool unit = value<60000000LL;
67                 result += format_part(value, 86400000000LL,  0,  first);
68                 result += format_part(value, 3600000000LL,  '-', first);
69                 result += format_part(value, 60000000LL,    ':', first);
70                 result += format_part(value, 1000000LL,     ':', first);
71
72                 if(value)
73                 {
74                         if(value%1000)
75                                 result += format(".%06d", value);
76                         else
77                                 result += format(".%03d", value/1000);
78                 }
79                 if(unit)
80                         result += 's';
81         }
82
83         conv.result(result);
84 }
85
86 } // namespace Time
87 } // namespace Msp