datetime.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //
  2. // Copyright (c) 2019-2023 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BHO_MYSQL_DATETIME_HPP
  8. #define BHO_MYSQL_DATETIME_HPP
  9. #include <asio2/bho/mysql/days.hpp>
  10. #include <asio2/bho/mysql/detail/config.hpp>
  11. #include <asio2/bho/mysql/detail/datetime.hpp>
  12. #include <asio2/bho/assert.hpp>
  13. #include <asio2/bho/config.hpp>
  14. #include <asio2/bho/throw_exception.hpp>
  15. #include <chrono>
  16. #include <cstdint>
  17. #include <iosfwd>
  18. #include <ratio>
  19. #include <stdexcept>
  20. namespace bho {
  21. namespace mysql {
  22. /**
  23. * \brief Type representing MySQL `DATETIME` and `TIMESTAMP` data types.
  24. * \details Represents a broken datetime by its year, month, day, hour, minute, second and
  25. * microsecond components. This type is close to the protocol and should not be used as a vocabulary
  26. * type. Instead, cast it to a `std::chrono::time_point` by calling \ref as_time_point or \ref
  27. * get_time_point.
  28. * \n
  29. * As opposed to `time_point`, this type allows representing invalid and zero datetimes.
  30. */
  31. class datetime
  32. {
  33. public:
  34. /**
  35. * \brief A `std::chrono::time_point` that can represent any valid datetime.
  36. * \details Represents microseconds since the UNIX epoch, with the same precision for all architectures.
  37. */
  38. using time_point = std::chrono::
  39. time_point<std::chrono::system_clock, std::chrono::duration<std::int64_t, std::micro>>;
  40. /**
  41. * \brief Constructs a zero datetime.
  42. * \details Results in a datetime with all of its components set to zero.
  43. * \par Exception safety
  44. * No-throw guarantee.
  45. */
  46. constexpr datetime() noexcept = default;
  47. /**
  48. * \brief Constructs a datetime from its individual components.
  49. * \par Exception safety
  50. * No-throw guarantee.
  51. */
  52. constexpr datetime(
  53. std::uint16_t year,
  54. std::uint8_t month,
  55. std::uint8_t day,
  56. std::uint8_t hour = 0,
  57. std::uint8_t minute = 0,
  58. std::uint8_t second = 0,
  59. std::uint32_t microsecond = 0
  60. ) noexcept
  61. : year_(year),
  62. month_(month),
  63. day_(day),
  64. hour_(hour),
  65. minute_(minute),
  66. second_(second),
  67. microsecond_(microsecond)
  68. {
  69. }
  70. /**
  71. * \brief Constructs a datetime from a `time_point`.
  72. * \par Exception safety
  73. * Strong guarantee. Throws on invalid input.
  74. * \throws std::out_of_range If the resulting `datetime` object would be
  75. * out of the [\ref min_datetime, \ref max_datetime] range.
  76. */
  77. BHO_CXX14_CONSTEXPR inline explicit datetime(time_point tp);
  78. /**
  79. * \brief Retrieves the year component.
  80. * \par Exception safety
  81. * No-throw guarantee.
  82. */
  83. constexpr std::uint16_t year() const noexcept { return year_; }
  84. /**
  85. * \brief Retrieves the month component.
  86. * \par Exception safety
  87. * No-throw guarantee.
  88. */
  89. constexpr std::uint8_t month() const noexcept { return month_; }
  90. /**
  91. * \brief Retrieves the day component.
  92. * \par Exception safety
  93. * No-throw guarantee.
  94. */
  95. constexpr std::uint8_t day() const noexcept { return day_; }
  96. /**
  97. * \brief Retrieves the hour component.
  98. * \par Exception safety
  99. * No-throw guarantee.
  100. */
  101. constexpr std::uint8_t hour() const noexcept { return hour_; }
  102. /**
  103. * \brief Retrieves the minute component.
  104. * \par Exception safety
  105. * No-throw guarantee.
  106. */
  107. constexpr std::uint8_t minute() const noexcept { return minute_; }
  108. /**
  109. * \brief Retrieves the second component.
  110. * \par Exception safety
  111. * No-throw guarantee.
  112. */
  113. constexpr std::uint8_t second() const noexcept { return second_; }
  114. /**
  115. * \brief Retrieves the microsecond component.
  116. * \par Exception safety
  117. * No-throw guarantee.
  118. */
  119. constexpr std::uint32_t microsecond() const noexcept { return microsecond_; }
  120. /**
  121. * \brief Returns `true` if `*this` represents a valid `time_point`.
  122. * \details If any of the individual components is out of range, the datetime
  123. * doesn't represent an actual `time_point` (e.g. `datetime(2020, 2, 30)`) or
  124. * the datetime is not in the [\ref min_date, \ref max_date] validity range,
  125. * returns `false`. Otherwise, returns `true`.
  126. *
  127. * \par Exception safety
  128. * No-throw guarantee.
  129. */
  130. constexpr bool valid() const noexcept
  131. {
  132. return detail::is_valid(year_, month_, day_) && hour_ <= detail::max_hour &&
  133. minute_ <= detail::max_min && second_ <= detail::max_sec && microsecond_ <= detail::max_micro;
  134. }
  135. /**
  136. * \brief Converts `*this` into a `time_point` (unchecked access).
  137. * \par Preconditions
  138. * `this->valid() == true` (if violated, results in undefined behavior).
  139. *
  140. * \par Exception safety
  141. * No-throw guarantee.
  142. */
  143. BHO_CXX14_CONSTEXPR time_point get_time_point() const noexcept
  144. {
  145. BHO_ASSERT(valid());
  146. return unch_get_time_point();
  147. }
  148. /**
  149. * \brief Converts `*this` into a `time_point` (checked access).
  150. * \par Exception safety
  151. * Strong guarantee.
  152. * \throws std::invalid_argument If `!this->valid()`.
  153. */
  154. BHO_CXX14_CONSTEXPR inline time_point as_time_point() const
  155. {
  156. if (!valid())
  157. BHO_THROW_EXCEPTION(std::invalid_argument("datetime::as_time_point: invalid datetime"));
  158. return unch_get_time_point();
  159. }
  160. /**
  161. * \brief Tests for equality.
  162. * \details Two datetimes are considered equal if all of its individual components
  163. * are equal. This function works for invalid datetimes, too.
  164. *
  165. * \par Exception safety
  166. * No-throw guarantee.
  167. */
  168. constexpr bool operator==(const datetime& rhs) const noexcept
  169. {
  170. return year_ == rhs.year_ && month_ == rhs.month_ && day_ == rhs.day_ && hour_ == rhs.hour_ &&
  171. minute_ == rhs.minute_ && second_ == rhs.second_ && microsecond_ == rhs.microsecond_;
  172. }
  173. /**
  174. * \brief Tests for inequality.
  175. * \par Exception safety
  176. * No-throw guarantee.
  177. */
  178. constexpr bool operator!=(const datetime& rhs) const noexcept { return !(*this == rhs); }
  179. /**
  180. * \brief Returns the current system time as a datetime object.
  181. * \par Exception safety
  182. * Strong guarantee. Only throws if obtaining the current time throws.
  183. */
  184. static datetime now()
  185. {
  186. auto now = time_point::clock::now();
  187. return datetime(std::chrono::time_point_cast<time_point::duration>(now));
  188. }
  189. private:
  190. std::uint16_t year_{};
  191. std::uint8_t month_{};
  192. std::uint8_t day_{};
  193. std::uint8_t hour_{};
  194. std::uint8_t minute_{};
  195. std::uint8_t second_{};
  196. std::uint32_t microsecond_{};
  197. BHO_CXX14_CONSTEXPR inline time_point unch_get_time_point() const noexcept
  198. {
  199. // Doing time of day independently to prevent overflow
  200. days d(detail::ymd_to_days(year_, month_, day_));
  201. auto time_of_day = std::chrono::hours(hour_) + std::chrono::minutes(minute_) +
  202. std::chrono::seconds(second_) + std::chrono::microseconds(microsecond_);
  203. return time_point(d) + time_of_day;
  204. }
  205. };
  206. /**
  207. * \relates datetime
  208. * \brief Streams a datetime.
  209. * \details This function works for invalid datetimes, too.
  210. */
  211. BHO_MYSQL_DECL
  212. std::ostream& operator<<(std::ostream& os, const datetime& v);
  213. /// The minimum allowed value for \ref datetime.
  214. constexpr datetime min_datetime(0u, 1u, 1u);
  215. /// The maximum allowed value for \ref datetime.
  216. constexpr datetime max_datetime(9999u, 12u, 31u, 23u, 59u, 59u, 999999u);
  217. } // namespace mysql
  218. } // namespace bho
  219. // Implementations
  220. BHO_CXX14_CONSTEXPR bho::mysql::datetime::datetime(time_point tp)
  221. {
  222. using std::chrono::duration_cast;
  223. using std::chrono::hours;
  224. using std::chrono::microseconds;
  225. using std::chrono::minutes;
  226. using std::chrono::seconds;
  227. // Avoiding using -= for durations as it's not constexpr until C++17
  228. auto input_dur = tp.time_since_epoch();
  229. auto rem = input_dur % days(1);
  230. auto num_days = duration_cast<days>(input_dur);
  231. if (rem.count() < 0)
  232. {
  233. rem = rem + days(1);
  234. num_days = num_days - days(1);
  235. }
  236. auto num_hours = duration_cast<hours>(rem);
  237. rem = rem - num_hours;
  238. auto num_minutes = duration_cast<minutes>(rem);
  239. rem = rem - num_minutes;
  240. auto num_seconds = duration_cast<seconds>(rem);
  241. rem = rem - num_seconds;
  242. auto num_microseconds = duration_cast<microseconds>(rem);
  243. BHO_ASSERT(num_hours.count() >= 0 && num_hours.count() <= detail::max_hour);
  244. BHO_ASSERT(num_minutes.count() >= 0 && num_minutes.count() <= detail::max_min);
  245. BHO_ASSERT(num_seconds.count() >= 0 && num_seconds.count() <= detail::max_sec);
  246. BHO_ASSERT(num_microseconds.count() >= 0 && num_microseconds.count() <= detail::max_micro);
  247. bool ok = detail::days_to_ymd(num_days.count(), year_, month_, day_);
  248. if (!ok)
  249. BHO_THROW_EXCEPTION(std::out_of_range("datetime::datetime: time_point was out of range"));
  250. microsecond_ = static_cast<std::uint32_t>(num_microseconds.count());
  251. second_ = static_cast<std::uint8_t>(num_seconds.count());
  252. minute_ = static_cast<std::uint8_t>(num_minutes.count());
  253. hour_ = static_cast<std::uint8_t>(num_hours.count());
  254. }
  255. #ifdef BHO_MYSQL_HEADER_ONLY
  256. #include <asio2/bho/mysql/impl/datetime.ipp>
  257. #endif
  258. #endif