diff options
author | Timothy Flynn <trflynn89@pm.me> | 2022-01-10 22:38:48 -0500 |
---|---|---|
committer | Linus Groh <mail@linusgroh.de> | 2022-01-11 23:56:35 +0100 |
commit | 548643bcc9d196c2b10a29e7ced4e9b5044d88b0 (patch) | |
tree | 2ad96891796315c3792c82bc9a797080af9f0f12 /AK/Time.h | |
parent | c7e021c1f19b1b7572e3bcc46c9230c8b7660262 (diff) | |
download | serenity-548643bcc9d196c2b10a29e7ced4e9b5044d88b0.zip |
AK: Redeclare a few AK::Time helpers as constexpr
This is to allow using these methods within an upcoming constexpr
factory method.
Diffstat (limited to 'AK/Time.h')
-rw-r--r-- | AK/Time.h | 30 |
1 files changed, 21 insertions, 9 deletions
@@ -6,6 +6,7 @@ #pragma once +#include <AK/Array.h> #include <AK/Assertions.h> #include <AK/Platform.h> #include <AK/Types.h> @@ -25,6 +26,11 @@ concept TimeSpecType = requires(T t) t.tv_nsec; }; +constexpr bool is_leap_year(int year) +{ + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); +} + // Month and day start at 1. Month must be >= 1 and <= 12. // The return value is 0-indexed, that is 0 is Sunday, 1 is Monday, etc. // Day may be negative or larger than the number of days @@ -36,22 +42,28 @@ unsigned day_of_week(int year, unsigned month, int day); // Day may be negative or larger than the number of days // in the given month. If day is negative enough, the result // can be negative. -int day_of_year(int year, unsigned month, int day); +constexpr int day_of_year(int year, unsigned month, int day) +{ + VERIFY(month >= 1 && month <= 12); -// Month starts at 1. Month must be >= 1 and <= 12. -int days_in_month(int year, unsigned month); + constexpr Array seek_table = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; + int day_of_year = seek_table[month - 1] + day - 1; -inline bool is_leap_year(int year) -{ - return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + if (is_leap_year(year) && month >= 3) + day_of_year++; + + return day_of_year; } -inline int days_in_year(int year) +// Month starts at 1. Month must be >= 1 and <= 12. +int days_in_month(int year, unsigned month); + +constexpr int days_in_year(int year) { return 365 + (is_leap_year(year) ? 1 : 0); } -inline int years_to_days_since_epoch(int year) +constexpr int years_to_days_since_epoch(int year) { int days = 0; for (int current_year = 1970; current_year < year; ++current_year) @@ -61,7 +73,7 @@ inline int years_to_days_since_epoch(int year) return days; } -inline int days_since_epoch(int year, int month, int day) +constexpr int days_since_epoch(int year, int month, int day) { return years_to_days_since_epoch(year) + day_of_year(year, month, day); } |