]> git.tdb.fi Git - libs/core.git/blob - source/time/timedelta.cpp
Assimilate exceptions and RefPtr from mspmisc
[libs/core.git] / source / time / timedelta.cpp
1 /*
2 This file is part of libmspcore
3 Copyright © 2006  Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
5 */
6 #include <sstream>
7 #include <iomanip>
8 #include "timedelta.h"
9 #include "units.h"
10
11 using namespace std;
12
13 namespace {
14
15 void print_part(ostream &out, int64_t &value, int64_t unit, char sep, bool &first)
16 {
17         if(value<unit && first)
18                 return;
19         
20         if(!first)
21                 out<<sep<<setw(2);
22         
23         out<<value/unit;
24         value%=unit;
25         first=false;
26 }
27
28 }
29
30 namespace Msp {
31 namespace Time {
32
33 ostream &operator<<(ostream &out, const TimeDelta &td)
34 {
35         ostringstream ss;
36         ss.fill('0');
37
38         int64_t value=td.raw();
39
40         if(value<0)
41         {
42                 ss<<'-';
43                 value=-value;
44         }
45
46         if(value==0)
47                 ss<<'0';
48         else if(value<1000)
49                 ss<<value<<"µs";
50         else if(value<1000000)
51         {
52                 ss<<value/1000;
53                 value%=1000;
54                 if(value)
55                         ss<<'.'<<setw(3)<<value;
56                 ss<<"ms";
57         }
58         else
59         {
60                 bool first=true;
61                 print_part(ss, value, 86400000000LL,  0,  first);
62                 print_part(ss, value, 3600000000LL,  '-', first);
63                 print_part(ss, value, 60000000LL,    ':', first);
64                 print_part(ss, value, 1000000LL,     ':', first);
65
66                 if(value)
67                 {
68                         ss<<'.';
69                         if(value%1000)
70                                 ss<<setw(6)<<value;
71                         else
72                                 ss<<setw(3)<<value/1000;
73                 }
74                 ss<<"s";
75         }
76
77         out<<ss.str();
78
79         return out;
80 }
81
82 } // namespace Time
83 } // namespace Msp