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