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