summaryrefslogtreecommitdiff
path: root/xsd-examples/cxx/parser/performance/time.hxx
blob: a22f67139fc5067ba2b9afd2630b3b23a68a79e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// file      : cxx/parser/performance/time.hxx
// copyright : not copyrighted - public domain

#ifndef TIME_HXX
#define TIME_HXX

#include <iosfwd> // std::ostream&

namespace os
{
  class time
  {
  public:
    class failed {};

    // Create a time object representing the current time.
    //
    time ();

    time (unsigned long long nsec)
    {
      sec_  = static_cast<unsigned long> (nsec / 1000000000ULL);
      nsec_ = static_cast<unsigned long> (nsec % 1000000000ULL);
    }

    time (unsigned long sec, unsigned long nsec)
    {
      sec_  = sec;
      nsec_ = nsec;
    }

  public:
    unsigned long
    sec () const
    {
      return sec_;
    }

    unsigned long
    nsec () const
    {
      return nsec_;
    }

  public:
    class overflow {};
    class underflow {};

    time
    operator+= (time const& b)
    {
      unsigned long long tmp = 0ULL + nsec_ + b.nsec_;

      sec_ += static_cast<unsigned long> (b.sec_ + tmp / 1000000000ULL);
      nsec_ = static_cast<unsigned long> (tmp % 1000000000ULL);

      return *this;
    }

    time
    operator-= (time const& b)
    {
      if (*this < b)
        throw underflow ();

      sec_ -= b.sec_;

      if (nsec_ < b.nsec_)
      {
        --sec_;
        nsec_ += 1000000000ULL - b.nsec_;
      }
      else
        nsec_ -= b.nsec_;

      return *this;
    }

    friend time
    operator+ (time const& a, time const& b)
    {
      time r (a);
      r += b;
      return r;
    }

    friend time
    operator- (time const& a, time const& b)
    {
      time r (a);
      r -= b;
      return r;
    }

    friend bool
    operator < (time const& a, time const& b)
    {
      return (a.sec_ < b.sec_) || (a.sec_ == b.sec_ && a.nsec_ < b.nsec_);
    }

  private:
    unsigned long sec_;
    unsigned long nsec_;
  };

  std::ostream&
  operator<< (std::ostream&, time const&);
}

#endif // TIME_HXX