From 548643bcc9d196c2b10a29e7ced4e9b5044d88b0 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Mon, 10 Jan 2022 22:38:48 -0500 Subject: [PATCH] AK: Redeclare a few AK::Time helpers as constexpr This is to allow using these methods within an upcoming constexpr factory method. --- AK/Time.cpp | 14 -------------- AK/Time.h | 30 +++++++++++++++++++++--------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/AK/Time.cpp b/AK/Time.cpp index 5d601deefa..83fe3f7d96 100644 --- a/AK/Time.cpp +++ b/AK/Time.cpp @@ -4,7 +4,6 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#include #include #include @@ -19,19 +18,6 @@ namespace AK { -int day_of_year(int year, unsigned month, int day) -{ - VERIFY(month >= 1 && month <= 12); - - 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; - - if (is_leap_year(year) && month >= 3) - day_of_year++; - - return day_of_year; -} - int days_in_month(int year, unsigned month) { VERIFY(month >= 1 && month <= 12); diff --git a/AK/Time.h b/AK/Time.h index 7365240462..df4f5b3045 100644 --- a/AK/Time.h +++ b/AK/Time.h @@ -6,6 +6,7 @@ #pragma once +#include #include #include #include @@ -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); + + 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; + + if (is_leap_year(year) && month >= 3) + day_of_year++; + + return day_of_year; +} // Month starts at 1. Month must be >= 1 and <= 12. int days_in_month(int year, unsigned month); -inline bool is_leap_year(int year) -{ - return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); -} - -inline int days_in_year(int year) +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); }