Remove dynamic exceptions
[anna.git] / source / core / util / Millisecond.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 #include <time.h>
10 #include <sys/time.h>
11 #include <stdlib.h>
12
13 #include <anna/core/functions.hpp>
14 #include <anna/core/util/Millisecond.hpp>
15 #include <anna/core/util/Second.hpp>
16 #include <anna/core/util/Microsecond.hpp>
17
18 using namespace std;
19 using namespace anna;
20
21 #define implement_operator(op) \
22    bool Millisecond::operator op (const Second& other) const \
23       \
24    {\
25       return a_value op (other.a_value * (type_t)1000);\
26    }\
27    bool Millisecond::operator op (const Microsecond& other) const\
28       \
29    {\
30       return a_value op (other.a_value / 1000);\
31    }
32
33 Millisecond::Millisecond(const Second& other) : a_value(other.a_value) { a_value *= (type_t)1000;}
34
35 Millisecond::Millisecond(const Microsecond& other) : a_value(other.a_value / 1000) {;}
36
37 Millisecond& Millisecond::operator= (const Second & other)
38 {
39   a_value = other.a_value;
40   a_value *= (type_t)1000;
41   return *this;
42 }
43
44 Millisecond& Millisecond::operator= (const Microsecond & other)
45 {
46   a_value = (other.a_value / 1000);
47   return *this;
48 }
49
50 implement_operator( ==)
51 implement_operator( !=)
52 implement_operator( >)
53 implement_operator( <)
54
55 //static
56 Millisecond Millisecond::getTime()
57 {
58   struct timeval tv;
59   gettimeofday(&tv, NULL);
60   Millisecond result(Second(tv.tv_sec));
61   Millisecond aux(Microsecond(tv.tv_usec));
62   result.a_value += aux.a_value;
63   return result;
64 }
65
66 timeval* Millisecond::getTimeVal(timeval& tv) const
67 {
68   if(a_value < 0)
69     return NULL;
70
71   tv.tv_sec = a_value / 1000;
72   tv.tv_usec = (a_value % 1000) * (type_t)1000;
73   return &tv;
74 }
75
76 string Millisecond::asString() const
77 {
78   string result(functions::asString(a_value));
79   return result += " ms";
80 }
81
82 //static
83 Millisecond Millisecond::fromString(const std::string& value)
84 noexcept(false) {
85   if(value.find(" ms") == string::npos) {
86     string msg("String: ");
87     msg += value;
88     msg += " | Invalid expression for Millisecond";
89     throw RuntimeException(msg, ANNA_FILE_LOCATION);
90   }
91
92   return Millisecond(atoll(value.c_str()));
93 }
94