]> git.tdb.fi Git - libs/core.git/blob - source/time/timedelta.cpp
Merge branch 'strings-master'
[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 <sstream>
9 #include <iomanip>
10 #include "timedelta.h"
11 #include "units.h"
12
13 using namespace std;
14
15 namespace {
16
17 using Msp::Time::RawTime;
18
19 void print_part(ostream &out, RawTime &value, RawTime unit, char sep, bool &first)
20 {
21         if(value<unit && first)
22                 return;
23         
24         if(!first)
25                 out<<sep<<setw(2);
26         
27         out<<value/unit;
28         value %= unit;
29         first = false;
30 }
31
32 }
33
34 namespace Msp {
35 namespace Time {
36
37 ostream &operator<<(ostream &out, const TimeDelta &td)
38 {
39         ostringstream ss;
40         ss.fill('0');
41
42         RawTime value = td.raw();
43
44         if(value<0)
45         {
46                 ss<<'-';
47                 value = -value;
48         }
49
50         if(value==0)
51                 ss<<'0';
52         else if(value<1000)
53                 ss<<value<<"µs";
54         else if(value<1000000)
55         {
56                 ss<<value/1000;
57                 value %= 1000;
58                 if(value)
59                         ss<<'.'<<setw(3)<<value;
60                 ss<<"ms";
61         }
62         else
63         {
64                 bool first = true;
65                 print_part(ss, value, 86400000000LL,  0,  first);
66                 print_part(ss, value, 3600000000LL,  '-', first);
67                 print_part(ss, value, 60000000LL,    ':', first);
68                 print_part(ss, value, 1000000LL,     ':', first);
69
70                 if(value)
71                 {
72                         ss<<'.';
73                         if(value%1000)
74                                 ss<<setw(6)<<value;
75                         else
76                                 ss<<setw(3)<<value/1000;
77                 }
78                 ss<<"s";
79         }
80
81         out<<ss.str();
82
83         return out;
84 }
85
86 } // namespace Time
87 } // namespace Msp