Update wscript.
[libsub.git] / src / metric_time.cc
1 /*
2     Copyright (C) 2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "metric_time.h"
21 #include "compose.hpp"
22 #include <iostream>
23 #include <cmath>
24
25 using std::ostream;
26 using std::string;
27 using std::cout;
28 using namespace sub;
29
30 MetricTime::MetricTime (int h, int m, int s, int ms)
31         /* cast up to int64_t to force a 64-bit calculation */
32         : _ms ((int64_t (h) * 3600 + m * 60 + s) * 1000 + ms)
33 {
34
35 }
36
37 void
38 MetricTime::split (int& h, int &m, int& s, int& ms) const
39 {
40         int64_t w = _ms;
41         h = floor (w / (3600 * 1000));
42         /* this multiply could overflow 32 bits so cast to make sure it is done as 64-bit */
43         w -= int64_t (h) * (3600 * 1000);
44         m = floor (w / (60 * 1000));
45         w -= m * (60 * 1000);
46         s = floor (w / 1000);
47         w -= s * 1000;
48         ms = w;
49 }
50
51 int
52 MetricTime::hours () const
53 {
54         int h, m, s, ms;
55         split (h, m, s, ms);
56         return h;
57 }
58
59 int
60 MetricTime::minutes () const
61 {
62         int h, m, s, ms;
63         split (h, m, s, ms);
64         return m;
65 }
66
67 int
68 MetricTime::seconds () const
69 {
70         int h, m, s, ms;
71         split (h, m, s, ms);
72         return s;
73 }
74
75 int
76 MetricTime::milliseconds () const
77 {
78         int h, m, s, ms;
79         split (h, m, s, ms);
80         return ms;
81 }
82
83 bool
84 sub::operator== (MetricTime const & a, MetricTime const & b)
85 {
86         return a._ms == b._ms;
87 }
88
89 bool
90 sub::operator> (MetricTime const & a, MetricTime const & b)
91 {
92         return a._ms > b._ms;
93 }
94
95 bool
96 sub::operator< (MetricTime const & a, MetricTime const & b)
97 {
98         return a._ms < b._ms;
99 }
100
101 ostream&
102 sub::operator<< (ostream& st, MetricTime const & t)
103 {
104         int h, m, s, ms;
105         t.split (h, m, s, ms);
106         st << h << ":" << m << ":" << s << ":" << ms;
107         return st;
108 }