[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 13:04:10 PST 2025
================
@@ -89,11 +96,254 @@ LIBC_INLINE struct tm *gmtime_internal(const time_t *timer, struct tm *result) {
// TODO: localtime is not yet implemented and a temporary solution is to
// use gmtime, https://github.com/llvm/llvm-project/issues/107597
-LIBC_INLINE struct tm *localtime(const time_t *t_ptr) {
- static struct tm result;
+LIBC_INLINE tm *localtime(const time_t *t_ptr) {
+ static tm result;
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;
+
+ template <size_t N>
+ LIBC_INLINE constexpr cpp::optional<cpp::string_view>
+ bounds_check(const cpp::array<cpp::string_view, N> &arr, int index) const {
----------------
michaelrj-google wrote:
This doesn't work with our current `span` implementation due to issues with accepting a `const array`. I'll leave it as-is for now, but I'm not opposed to moving this to be `span` in future.
https://github.com/llvm/llvm-project/pull/126138
More information about the libc-commits
mailing list