summaryrefslogtreecommitdiffstats
path: root/xbmc/threads/SystemClock.h
blob: 92c490134a96a7a72e3e16883e968623ffc31c2d (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
/*
 *  Copyright (C) 2005-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#pragma once

#include "utils/log.h"

#include <chrono>
#include <limits>
#include <thread>

namespace XbmcThreads
{

template<typename>
struct is_chrono_duration : std::false_type
{
};

template<typename Rep, typename Period>
struct is_chrono_duration<std::chrono::duration<Rep, Period>> : std::true_type
{
};

template<typename T = std::chrono::milliseconds, bool = is_chrono_duration<T>::value>
class EndTime;

template<typename T>
class EndTime<T, true>
{
public:
  explicit EndTime(const T duration) { Set(duration); }

  EndTime() = default;
  EndTime(const EndTime& right) = delete;
  ~EndTime() = default;

  static constexpr T Max() { return m_max; }

  void Set(const T duration)
  {
    m_startTime = std::chrono::steady_clock::now();

    if (duration > m_max)
    {
      m_totalWaitTime = m_max;
      CLog::Log(LOGWARNING, "duration ({}) greater than max ({}) - duration will be truncated!",
                duration.count(), m_max.count());
    }
    else
    {
      m_totalWaitTime = duration;
    }
  }

  bool IsTimePast() const
  {
    const auto now = std::chrono::steady_clock::now();

    return ((now - m_startTime) >= m_totalWaitTime);
  }

  T GetTimeLeft() const
  {
    const auto now = std::chrono::steady_clock::now();

    const auto left = ((m_startTime + m_totalWaitTime) - now);

    if (left < T::zero())
      return T::zero();

    return std::chrono::duration_cast<T>(left);
  }

  void SetExpired() { m_totalWaitTime = T::zero(); }

  void SetInfinite() { m_totalWaitTime = m_max; }

  T GetInitialTimeoutValue() const { return m_totalWaitTime; }

  std::chrono::steady_clock::time_point GetStartTime() const { return m_startTime; }

private:
  std::chrono::steady_clock::time_point m_startTime;
  T m_totalWaitTime = T::zero();

  static constexpr T m_max =
      std::chrono::duration_cast<T>(std::chrono::steady_clock::duration::max());
};

} // namespace XbmcThreads