[libc-commits] [libc] [libc] create TimeReader to look at a struct tm (PR #126138)
Michael Jones via libc-commits
libc-commits at lists.llvm.org
Tue Feb 11 10:27:16 PST 2025
================
@@ -94,6 +101,255 @@ LIBC_INLINE struct tm *localtime(const time_t *t_ptr) {
return time_utils::gmtime_internal(t_ptr, &result);
}
+// Returns number of years from (1, year).
+LIBC_INLINE constexpr int64_t get_num_of_leap_years_before(int64_t year) {
+ return (year / 4) - (year / 100) + (year / 400);
+}
+
+// Returns True if year is a leap year.
+LIBC_INLINE constexpr bool is_leap_year(const int64_t year) {
+ return (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0));
+}
+
+LIBC_INLINE constexpr int get_days_in_year(const int year) {
+ return is_leap_year(year) ? time_constants::DAYS_PER_LEAP_YEAR
+ : time_constants::DAYS_PER_NON_LEAP_YEAR;
+}
+
+// This is a helper class that takes a struct tm and lets you inspect its
+// values. Where relevant, results are bounds checked and returned as optionals.
+// This class does not, however, do data normalization except where necessary.
+// It will faithfully return a date of 9999-99-99, even though that makes no
+// sense.
+class TMReader final {
+ const tm *timeptr;
+
+public:
+ LIBC_INLINE constexpr TMReader(const tm *tmptr) : timeptr(tmptr) { ; }
+
+ // Strings
+ LIBC_INLINE constexpr cpp::optional<cpp::string_view>
----------------
michaelrj-google wrote:
The way this is used in the followup can be seen here: https://github.com/llvm/llvm-project/pull/122556/files#diff-32cc25b66a2431d22a10654223546500152fb9ba20daf51053d1c36238e25cefR22-R30
Basically: It returns the string if it has one, or a '?' if it gets nullopt. I could check the size for that as well, and either works, but I prefer this way since it prevents the user from accidentally passing along the empty `string_view` thinking it's valid. If you have successfully gotten a `string_view` it can be passed to the user. It also makes a type-system distinction between functions like `get_weekday_XXXX_name` which can fail and ones like `get_am_pm` which cannot.
https://github.com/llvm/llvm-project/pull/126138
More information about the libc-commits
mailing list