ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
time.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define UTIL_TIME_TEMP_BUFFER_SIZE 64
9
12
13#undef SOKOL_TIME_INCLUDED
14#define SOKOL_TIME_IMPL
15#include <ascii-chat-deps/sokol/sokol_time.h>
17#include <ascii-chat/common.h>
18#include <ctype.h>
19#include <libplatform/atomic.h>
20#include <libplatform/compiler.h>
21#include <libplatform/lifecycle.h>
22#include <libplatform/rwlock.h>
23#include <libplatform/system.h>
24#include <libplatform/terminal.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <time.h>
29
30// ============================================================================
31// Global State
32// ============================================================================
33
37static struct {
39 rwlock_t rwlock;
41 lifecycle_t
43} g_timer_manager = {
44 .timers = NULL,
45 .lifecycle = LIFECYCLE_INIT,
46};
47
48// ============================================================================
49// Human-Readable Time Formatting Helper
50// ============================================================================
51
72static int format_human_readable_time_ago(double total_seconds, int minutes,
73 int hours, int days, int months,
74 int years, const char *suffix,
75 char *buffer, size_t buffer_size) {
76 int written = 0;
77
78 if (total_seconds < 3) {
79 written = safe_snprintf(buffer, buffer_size, "a moment %s", suffix);
80 } else if (total_seconds < 10) {
81 written = safe_snprintf(buffer, buffer_size, "a few seconds %s", suffix);
82 } else if (total_seconds < 45) {
83 written = safe_snprintf(buffer, buffer_size, "%d seconds %s",
84 (int)total_seconds, suffix);
85 } else if (total_seconds < 90) {
86 written = safe_snprintf(buffer, buffer_size, "a minute %s", suffix);
87 } else if (minutes < 45) {
88 written =
89 safe_snprintf(buffer, buffer_size, "%d minutes %s", minutes, suffix);
90 } else if (minutes < 90) {
91 written = safe_snprintf(buffer, buffer_size, "an hour %s", suffix);
92 } else if (hours < 22) {
93 written = safe_snprintf(buffer, buffer_size, "%d hours %s", hours, suffix);
94 } else if (hours < 36) {
95 written = safe_snprintf(buffer, buffer_size, "a day %s", suffix);
96 } else if (days < 25) {
97 written = safe_snprintf(buffer, buffer_size, "%d days %s", days, suffix);
98 } else if (days < 45) {
99 written = safe_snprintf(buffer, buffer_size, "a month %s", suffix);
100 } else if (months < 11) {
101 written =
102 safe_snprintf(buffer, buffer_size, "%d months %s", months, suffix);
103 } else if (months < 18) {
104 written = safe_snprintf(buffer, buffer_size, "a year %s", suffix);
105 } else {
106 written = safe_snprintf(buffer, buffer_size, "%d years %s", years, suffix);
107 }
108
109 return written;
110}
111
112// ============================================================================
113// Core Monotonic Timing Implementation
114// ============================================================================
115
117 // Use platform abstraction for cross-platform sleep
118 // Convert nanoseconds to microseconds (1 us = 1000 ns)
119 unsigned int usec = (unsigned int)(ns / 1000);
120 if (usec == 0 && ns > 0) {
121 usec = 1; // Minimum 1 microsecond
122 }
123 platform_sleep_us(usec);
124}
125
127 // Handle wraparound (defensive - uint64_t won't wrap in practice at
128 // nanosecond resolution) but this is safe and handles any theoretical edge
129 // cases
130 if (end_ns >= start_ns) {
131 return end_ns - start_ns;
132 }
133 // Wraparound case (extremely unlikely)
134 return (UINT64_MAX - start_ns) + end_ns + 1;
135}
136
137// ============================================================================
138// Conversion Functions (moved from inline in header to avoid circular deps)
139// ============================================================================
140
141uint64_t time_timespec_to_ns(const struct timespec *ts) {
142 if (!ts) {
143 SET_ERRNO(ERROR_INVALID_PARAM, "null ts");
144 return 0;
145 }
146 // Check before multiplying so this also works with MSVC, which has no
147 // GNU __uint128_t extension.
148 if (ts->tv_sec < 0 || (uintmax_t)ts->tv_sec > UINT64_MAX / NS_PER_SEC_INT) {
149 SET_ERRNO(ERROR_INVALID_PARAM, "timespec value would overflow");
150 return UINT64_MAX;
151 }
152 uint64_t result = (uint64_t)ts->tv_sec * NS_PER_SEC_INT;
153 if ((uint64_t)ts->tv_nsec > UINT64_MAX - result) {
154 SET_ERRNO(ERROR_INVALID_PARAM, "timespec value would overflow");
155 return UINT64_MAX;
156 }
157 return result + (uint64_t)ts->tv_nsec;
158}
159
160// ============================================================================
161// Timer System Implementation
162// ============================================================================
163
165 if (lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
166 return true;
167 }
168
169 // Initialize sokol_time
170 stm_setup();
171
172 // Initialize rwlock and lifecycle together
173 g_timer_manager.lifecycle.sync_type = LIFECYCLE_SYNC_RWLOCK;
174 g_timer_manager.lifecycle.sync.rwlock = &g_timer_manager.rwlock;
175 if (!lifecycle_init(&g_timer_manager.lifecycle, "timer_manager")) {
176 SET_ERRNO(ERROR_PLATFORM_INIT, "Failed to initialize timer system (already "
177 "initialized by another thread)");
178 return true; // Another thread already initialized it
179 }
180
181 g_timer_manager.timers = NULL;
182
183 log_dev("Timer system initialized");
184 return true;
185}
186
188 if (!lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
189 return;
190 }
191
192 rwlock_wrlock(&g_timer_manager.rwlock);
193
194 // Free all timer records
195 int timer_count = 0;
196 timer_record_t *current, *tmp;
197 HASH_ITER(hh, g_timer_manager.timers, current, tmp) {
198 HASH_DEL(g_timer_manager.timers, current);
199 SAFE_FREE(current->name);
200 SAFE_FREE(current);
201 timer_count++;
202 }
203
204 g_timer_manager.timers = NULL;
205
206 rwlock_wrunlock(&g_timer_manager.rwlock);
207
208 /* Shutdown lifecycle and destroy rwlock together */
209 lifecycle_shutdown(&g_timer_manager.lifecycle);
210
211 log_debug("Timer system cleaned up (freed %d timers)", timer_count);
212}
213
214bool timer_start(const char *name) {
215 if (!lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
216 SET_ERRNO(ERROR_INVALID_STATE, "Timer system not initialized");
217 return false;
218 }
219
220 if (!name) {
221 SET_ERRNO(ERROR_INVALID_PARAM, "Timer name is NULL");
222 return false;
223 }
224
225 rwlock_wrlock(&g_timer_manager.rwlock);
226
227 // Check if timer already exists - this is an error, timers must be unique
228 timer_record_t *existing = NULL;
229 HASH_FIND_STR(g_timer_manager.timers, name, existing);
230
231 if (existing) {
232 rwlock_wrunlock(&g_timer_manager.rwlock);
234 "Timer '%s' already exists - timers must have unique names",
235 name);
236 return false;
237 }
238
239 // Create new timer record
241 if (!timer) {
242 rwlock_wrunlock(&g_timer_manager.rwlock);
243 SET_ERRNO(ERROR_MEMORY, "Failed to allocate timer record");
244 return false;
245 }
246
247 // Use platform-safe string duplication
248 size_t name_len = strlen(name) + 1;
249 timer->name = SAFE_MALLOC(name_len, char *);
250 if (!timer->name) {
251 SAFE_FREE(timer);
252 rwlock_wrunlock(&g_timer_manager.rwlock);
253 SET_ERRNO(ERROR_MEMORY, "Failed to allocate timer name");
254 return false;
255 }
256 SAFE_STRNCPY(timer->name, name, name_len);
257
258 timer->start_ticks = stm_now();
259
260 // Add to hashtable
261 HASH_ADD_KEYPTR(hh, g_timer_manager.timers, timer->name, strlen(timer->name),
262 timer);
263
264 rwlock_wrunlock(&g_timer_manager.rwlock);
265 return true;
266}
267
268double timer_stop(const char *name) {
269 if (!lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
270 SET_ERRNO(ERROR_INVALID_STATE, "Timer system not initialized");
271 return -1.0;
272 }
273
274 if (!name) {
275 SET_ERRNO(ERROR_INVALID_PARAM, "Timer name is NULL");
276 return -1.0;
277 }
278
279 rwlock_wrlock(&g_timer_manager.rwlock);
280
281 // Find timer
282 timer_record_t *timer = NULL;
283 HASH_FIND_STR(g_timer_manager.timers, name, timer);
284
285 if (!timer) {
286 rwlock_wrunlock(&g_timer_manager.rwlock);
287 log_dev("Timer '%s' not found (may have already been stopped)", name);
288 return -1.0;
289 }
290
291 // Calculate elapsed time in nanoseconds for maximum precision
292 uint64_t end_ticks = stm_now();
293 uint64_t elapsed_ticks = stm_diff(end_ticks, timer->start_ticks);
294 double elapsed_ns = stm_ns(elapsed_ticks);
295
296 // Format duration for human-readable logging
297 char duration_str[TIME_DURATION_BUFFER_SIZE];
298 time_pretty((uint64_t)elapsed_ns, -1, duration_str, sizeof(duration_str));
299
300 // Log the result (dev level - only shown with --verbose)
301 log_dev("Timer '%s': %s", name, duration_str);
302
303 // Save pointers to free BEFORE removing from hashtable
304 char *timer_name = timer->name;
305
306 // Remove from hashtable (HASH_DEL only removes from hash, doesn't free
307 // memory)
308 HASH_DEL(g_timer_manager.timers, timer);
309
310 // Free timer->name first (this was allocated separately)
311 SAFE_FREE(timer_name);
312
313 // Nullify the timer->name field so debug_free doesn't try to access it
314 // when freeing the timer structure itself
315 timer->name = NULL;
316
317 // Free the timer record itself
318 SAFE_FREE(timer);
319
320 rwlock_wrunlock(&g_timer_manager.rwlock);
321 return elapsed_ns; // Return nanoseconds
322}
323
324double timer_stop_formatted(const char *name_fmt, ...) {
326 return -1.0;
329 va_list args;
330 va_start(args, name_fmt);
331 vsnprintf(name, sizeof(name), name_fmt, args);
332 va_end(args);
333 snprintf(with_tid, sizeof(with_tid), "%s_tid%llu", name,
334 (unsigned long long)thread_current_id());
335 return timer_stop(with_tid);
336}
337
339 return lifecycle_is_initialized(&g_timer_manager.lifecycle);
340}
341
342// ============================================================================
343// Time Formatting Implementation
344// ============================================================================
345
346int format_uptime_hms(int hours, int minutes, int seconds, char *buffer,
347 size_t buffer_size) {
348 if (!buffer || buffer_size == 0) {
349 return -1;
350 }
351
352 // Validate components
353 if (hours < 0 || minutes < 0 || minutes >= 60 || seconds < 0 ||
354 seconds >= 60) {
355 return -1;
356 }
357
358 // Format as HH:MM:SS with zero-padding
359 int written = safe_snprintf(buffer, buffer_size, "%02d:%02d:%02d", hours,
360 minutes, seconds);
361
362 if (written < 0 || (size_t)written >= buffer_size) {
363 return -1;
364 }
365
366 return written;
367}
368
369// ============================================================================
370// Pretty Time Formatting with Spaces and Configurable Precision
371// ============================================================================
372
379static int strip_trailing_zeros(char *str) {
380 if (!str || !*str)
381 return 0;
382
383 int len = (int)strlen(str);
384 if (len <= 0)
385 return len;
386
387 // Find decimal point
388 char *decimal = strchr(str, '.');
389 if (!decimal)
390 return len; // No decimal point
391
392 // Keep the unit suffix while removing zeros from the fractional digits.
393 char *suffix = decimal + 1;
394 while (*suffix >= '0' && *suffix <= '9')
395 ++suffix;
396 char *end = suffix;
397 while (end > decimal + 1 && end[-1] == '0')
398 --end;
399 if (end == decimal + 1)
400 end = decimal;
401 memmove(end, suffix, strlen(suffix) + 1);
402
403 return (int)strlen(str);
404}
405
406int time_pretty(uint64_t nanoseconds, int decimals, char *buffer,
407 size_t buffer_size) {
408 if (!buffer || buffer_size == 0) {
409 return -1;
410 }
411
412 // Handle zero
413 if (nanoseconds == 0) {
414 int written = safe_snprintf(buffer, buffer_size, "0ns");
415 return (written < 0 || (size_t)written >= buffer_size) ? -1 : written;
416 }
417
418 // Determine decimals for this range if not explicitly set
419 int actual_decimals = decimals;
420 if (decimals == -1) {
421 if (nanoseconds < NS_PER_MIN_INT) {
422 actual_decimals =
423 (nanoseconds < NS_PER_SEC_INT) ? 3 : 2; // ns/µs/ms or seconds
424 } else {
425 actual_decimals = 0; // colon notation uses whole seconds
426 }
427 }
428
429 // Clamp decimals to valid range
430 if (actual_decimals < 0)
431 actual_decimals = 0;
432 if (actual_decimals > 9)
433 actual_decimals = 9;
434
435 int written = 0;
436
437 // Nanoseconds (< 1µs)
438 if (nanoseconds < NS_PER_US_INT) {
439 written = safe_snprintf(buffer, buffer_size, "%lluns",
440 (unsigned long long)nanoseconds);
441 }
442 // Microseconds (< 1ms)
443 else if (nanoseconds < NS_PER_MS_INT) {
444 double us = (double)nanoseconds / NS_PER_US;
445 char temp_buf[UTIL_TIME_TEMP_BUFFER_SIZE];
446 // Use a direct snprintf with large enough buffer first
447 snprintf(temp_buf, sizeof(temp_buf), "%.*fµs", actual_decimals, us);
448 strip_trailing_zeros(temp_buf);
449 written = (int)strlen(temp_buf);
450 if (written > 0 && written < (int)buffer_size) {
451 SAFE_STRNCPY(buffer, temp_buf, buffer_size);
452 } else {
453 written = -1;
454 }
455 }
456 // Milliseconds (< 1s)
457 else if (nanoseconds < NS_PER_SEC_INT) {
458 double ms = (double)nanoseconds / NS_PER_MS;
459 char temp_buf[UTIL_TIME_TEMP_BUFFER_SIZE];
460 snprintf(temp_buf, sizeof(temp_buf), "%.*fms", actual_decimals, ms);
461 strip_trailing_zeros(temp_buf);
462 written = (int)strlen(temp_buf);
463 if (written > 0 && written < (int)buffer_size) {
464 SAFE_STRNCPY(buffer, temp_buf, buffer_size);
465 } else {
466 written = -1;
467 }
468 }
469 // Seconds (< 1 minute)
470 else if (nanoseconds < NS_PER_MIN_INT) {
471 double s = (double)nanoseconds / NS_PER_SEC;
472 char temp_buf[UTIL_TIME_TEMP_BUFFER_SIZE];
473 snprintf(temp_buf, sizeof(temp_buf), "%.*fs", actual_decimals, s);
474 strip_trailing_zeros(temp_buf);
475 written = (int)strlen(temp_buf);
476 if (written > 0 && written < (int)buffer_size) {
477 SAFE_STRNCPY(buffer, temp_buf, buffer_size);
478 } else {
479 written = -1;
480 }
481 }
482 // Minutes omit fractions; days omit seconds.
483 else if (nanoseconds < NS_PER_HOUR_INT) {
484 uint64_t total_seconds = nanoseconds / NS_PER_SEC_INT;
485 written = safe_snprintf(buffer, buffer_size, "%llu:%02llu",
486 (unsigned long long)(total_seconds / 60),
487 (unsigned long long)(total_seconds % 60));
488 } else if (nanoseconds >= NS_PER_DAY_INT) {
489 uint64_t total_minutes = nanoseconds / NS_PER_MIN_INT;
490 written = safe_snprintf(buffer, buffer_size, "%llud %llu:%02llu",
491 (unsigned long long)(total_minutes / (24 * 60)),
492 (unsigned long long)((total_minutes / 60) % 24),
493 (unsigned long long)(total_minutes % 60));
494 }
495 // Hours use H:MM:SS.
496 else {
497 uint64_t total_seconds = nanoseconds / NS_PER_SEC_INT;
498 uint64_t hours = total_seconds / 3600;
499 uint64_t remaining = total_seconds % 3600;
500 uint64_t minutes = remaining / 60;
501 uint64_t seconds = remaining % 60;
502
503 written = safe_snprintf(
504 buffer, buffer_size, "%llu:%02llu:%02llu", (unsigned long long)hours,
505 (unsigned long long)minutes, (unsigned long long)seconds);
506 }
507
508 if (written < 0 || (size_t)written >= buffer_size) {
509 return -1;
510 }
511
512 return written;
513}
514
515int time_pretty_now(int decimals, char *buffer, size_t buffer_size) {
516 uint64_t ns = time_get_ns();
517 return time_pretty(ns, decimals, buffer, buffer_size);
518}
519
520// ============================================================================
521// Human-Readable Time Formatting (moment.js style)
522// ============================================================================
523
524int time_human_readable_unsigned(uint64_t nanoseconds, char *buffer,
525 size_t buffer_size) {
526 if (!buffer || buffer_size == 0) {
527 return -1;
528 }
529
530 // Convert nanoseconds to seconds for threshold checking
531 double total_seconds = (double)nanoseconds / NS_PER_SEC;
532 int minutes = (int)(total_seconds / 60);
533 int hours = minutes / 60;
534 int days = hours / 24;
535 int months = days / 30; // Approximate
536 int years = months / 12;
537
538 int written =
539 format_human_readable_time_ago(total_seconds, minutes, hours, days,
540 months, years, "ago", buffer, buffer_size);
541
542 if (written < 0 || (size_t)written >= buffer_size) {
543 return -1;
544 }
545
546 return written;
547}
548
549int time_human_readable(int64_t nanoseconds, char *buffer, size_t buffer_size) {
550 if (!buffer || buffer_size == 0) {
551 return -1;
552 }
553
554 // Determine direction (past vs future)
555 bool is_future = nanoseconds < 0;
556 uint64_t abs_ns =
557 is_future ? (uint64_t)(-nanoseconds) : (uint64_t)nanoseconds;
558
559 // Convert nanoseconds to seconds for threshold checking
560 double total_seconds = (double)abs_ns / NS_PER_SEC;
561 int minutes = (int)(total_seconds / 60);
562 int hours = minutes / 60;
563 int days = hours / 24;
564 int months = days / 30; // Approximate
565 int years = months / 12;
566
567 const char *suffix = is_future ? "from now" : "ago";
568 int written = format_human_readable_time_ago(total_seconds, minutes, hours,
569 days, months, years, suffix,
570 buffer, buffer_size);
571
572 if (written < 0 || (size_t)written >= buffer_size) {
573 return -1;
574 }
575
576 return written;
577}
578
579int time_human_readable_now(char *buffer, size_t buffer_size) {
580 int64_t ns = (int64_t)time_get_ns();
581 return time_human_readable(ns, buffer, buffer_size);
582}
583
584// ============================================================================
585// Adaptive Sleep Implementation
586// ============================================================================
587
589 const adaptive_sleep_config_t *config) {
590 if (!state || !config) {
591 return;
592 }
593
594 // Copy configuration
595 state->config = *config;
596
597 // A multiplier of 1.0 preserves the configured interval. Clamp it for
598 // configurations whose allowed range does not include the baseline.
599 state->current_speed_multiplier = 1.0;
600 if (state->current_speed_multiplier < config->min_speed_multiplier) {
602 }
603 if (state->current_speed_multiplier > config->max_speed_multiplier) {
605 }
606
607 state->last_sleep_ns =
609}
610
612 size_t queue_depth, size_t target_depth) {
613 if (!state) {
614 return 0;
615 }
616
617 const adaptive_sleep_config_t *cfg = &state->config;
618
619 // Determine if we need to speed up or slow down
620 double desired_multiplier;
621
622 if (queue_depth > target_depth) {
623 // Queue is building up - speed up processing
624 // The more items in queue, the faster we should process
625 size_t backlog = queue_depth - target_depth;
626
627 // Calculate desired speed based on backlog
628 // Each item above target increases speed proportionally
629 // This ensures we drain the queue faster the more backed up we are
630 double backlog_factor =
631 1.0 + ((double)backlog / (double)(target_depth + 1));
632 desired_multiplier = cfg->min_speed_multiplier * backlog_factor;
633
634 // Clamp to max speed
635 if (desired_multiplier > cfg->max_speed_multiplier) {
636 desired_multiplier = cfg->max_speed_multiplier;
637 }
638
639 // Ramp up gradually based on speedup_rate
640 double delta = desired_multiplier - state->current_speed_multiplier;
641 state->current_speed_multiplier += delta * cfg->speedup_rate;
642
643 } else {
644 // Queue is at or below target - slow down to baseline
645 desired_multiplier = 1.0;
646 if (desired_multiplier < cfg->min_speed_multiplier) {
647 desired_multiplier = cfg->min_speed_multiplier;
648 }
649 if (desired_multiplier > cfg->max_speed_multiplier) {
650 desired_multiplier = cfg->max_speed_multiplier;
651 }
652
653 // Ramp down gradually based on slowdown_rate
654 double delta = desired_multiplier - state->current_speed_multiplier;
655 state->current_speed_multiplier += delta * cfg->slowdown_rate;
656 }
657
658 // Ensure we stay within configured bounds
661 }
664 }
665
666 // Calculate actual sleep time: baseline / speed_multiplier
667 // Higher multiplier = shorter sleep = faster processing
668 uint64_t sleep_ns =
670
671 // Store for debugging
672 state->last_sleep_ns = sleep_ns;
673
674 return sleep_ns;
675}
676
677void adaptive_sleep_do(adaptive_sleep_state_t *state, size_t queue_depth,
678 size_t target_depth) {
679 uint64_t sleep_ns =
680 adaptive_sleep_calculate(state, queue_depth, target_depth);
681
682 if (sleep_ns > 0) {
683 platform_sleep_ns(sleep_ns);
684 }
685}
686
687/* ============================================================================
688 * Time Format Validation and Formatting Implementation
689 * ============================================================================
690 */
691
696static const char SUPPORTED_SPECIFIERS[] = "YmmdHMSaAbBjwuIpZzcxXFTsGgV";
697
698bool time_format_is_valid_strftime(const char *format_str) {
699 if (!format_str) {
700 return false;
701 }
702
703 for (const char *p = format_str; *p; p++) {
704 if (*p == '%') {
705 p++;
706 if (!*p) {
707 /* Unterminated % at end of string */
708 log_error("Invalid time format: unterminated %% at end");
709 return false;
710 }
711
712 if (*p == '%') {
713 /* Escaped %% - this is valid, just skip it */
714 continue;
715 }
716
717 /* Optional: flag characters (-, 0, +, space) */
718 if (*p == '-' || *p == '0' || *p == '+' || *p == ' ') {
719 p++;
720 if (!*p) {
721 log_error("Invalid time format: flag character without specifier");
722 return false;
723 }
724 }
725
726 /* Optional: width specifier (digits or *) */
727 if (*p == '*' || isdigit((unsigned char)*p)) {
728 while (*p && (isdigit((unsigned char)*p) || *p == '*')) {
729 p++;
730 }
731 if (!*p) {
732 log_error("Invalid time format: width specifier without specifier "
733 "character");
734 return false;
735 }
736 }
737
738 /* Optional: precision specifier (.digits or .*) */
739 if (*p == '.') {
740 p++;
741 if (!*p) {
742 log_error("Invalid time format: precision specifier incomplete");
743 return false;
744 }
745 while (*p && (isdigit((unsigned char)*p) || *p == '*')) {
746 p++;
747 }
748 if (!*p) {
749 log_error("Invalid time format: precision specifier without "
750 "specifier character");
751 return false;
752 }
753 }
754
755 /* Optional: modifier characters (E for %Ex, O for %Ox) */
756 if (*p == 'E' || *p == 'O') {
757 p++;
758 if (!*p) {
759 log_error(
760 "Invalid time format: modifier character without specifier");
761 return false;
762 }
763 }
764
765 /* Validate that the final character is a supported specifier */
766 if (!strchr(SUPPORTED_SPECIFIERS, *p)) {
767 log_error(
768 "Invalid time format: unsupported specifier %%%c (at position %ld)",
769 *p, (p - format_str));
770 return false;
771 }
772 }
773 }
774
775 return true;
776}
777
778int time_format_now(const char *format_str, char *buf, size_t buf_size) {
779 if (!format_str || !buf || buf_size < 2) {
781 "invalid arguments - format_str=%p, buf=%p, buf_size=%zu",
782 format_str, buf, buf_size);
783 return 0;
784 }
785
786 /* Get current wall-clock time in nanoseconds */
787 uint64_t ts_ns = time_get_realtime_ns();
788
789 /* Extract seconds and nanoseconds */
790 time_t seconds = (time_t)(ts_ns / NS_PER_SEC_INT);
791
792 /* Convert seconds to struct tm */
793 struct tm tm_info;
794 platform_localtime(&seconds, &tm_info);
795
796 /* Format using strftime */
797 size_t (*formatter)(char *, size_t, const char *, const struct tm *) =
798 strftime;
799 size_t len = formatter(buf, buf_size, format_str, &tm_info);
800
801 /* Check for strftime errors or buffer overflow */
802 if (len == 0) {
803 /* strftime returned 0 - either error or exact buffer fill */
804 log_debug("strftime returned 0 for format: %s", format_str);
805 return 0;
806 }
807
808 if (len >= buf_size - 1) {
809 /* Buffer would overflow - strftime filled entire buffer or hit exact size
810 */
811 log_error("buffer too small (need %zu, have %zu)", len + 1, buf_size);
812 return 0;
813 }
814
815 return (int)len;
816}
817
818asciichat_error_t time_format_safe(const char *format_str, char *buf,
819 size_t buf_size) {
820 /* Check NULL pointers */
821 if (!format_str) {
822 return SET_ERRNO(ERROR_INVALID_STATE, "format_str is NULL");
823 }
824
825 if (!buf) {
826 return SET_ERRNO(ERROR_INVALID_STATE, "buf is NULL");
827 }
828
829 /* Check minimum buffer size */
830 if (buf_size < 64) {
832 "buffer too small (minimum 64 bytes, got %zu)", buf_size);
833 }
834
835 /* Validate format string */
836 if (!time_format_is_valid_strftime(format_str)) {
837 return SET_ERRNO(ERROR_INVALID_STATE, "invalid time format: %s",
838 format_str);
839 }
840
841 /* Format the time */
842 int result = time_format_now(format_str, buf, buf_size);
843 if (result <= 0) {
844 return SET_ERRNO(ERROR_INVALID_STATE, "strftime formatting failed");
845 }
846
847 return ASCIICHAT_OK;
848}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
Error and exit codes - unified status values (0-255).
int buffer_size
Size of circular buffer.
Definition grep.c:69
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
double timer_stop_formatted(const char *name_fmt,...)
Definition time.c:324
double timer_stop(const char *name)
Stop a named timer and return elapsed time.
Definition time.c:268
int time_pretty_now(int decimals, char *buffer, size_t buffer_size)
Format current monotonic time as pretty duration.
Definition time.c:515
bool timer_start(const char *name)
Start a named timer.
Definition time.c:214
bool time_format_is_valid_strftime(const char *format_str)
Validate strftime format string against known safe specifiers.
Definition time.c:698
#define NS_PER_MIN_INT
Definition time.h:188
#define NS_PER_SEC_INT
Definition time.h:173
uint64_t adaptive_sleep_calculate(adaptive_sleep_state_t *state, size_t queue_depth, size_t target_depth)
Calculate adaptive sleep time based on queue depth.
Definition time.c:611
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
int time_format_now(const char *format_str, char *buf, size_t buf_size)
Format current time using strftime format string.
Definition time.c:778
uint64_t time_timespec_to_ns(const struct timespec *ts)
Convert struct timespec to nanoseconds.
Definition time.c:141
#define NS_PER_HOUR_INT
Definition time.h:189
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
void timer_system_destroy(void)
Cleanup the timing system.
Definition time.c:187
#define NS_PER_MS_INT
Definition time.h:172
int time_human_readable_unsigned(uint64_t nanoseconds, char *buffer, size_t buffer_size)
Format elapsed time as human-readable relative duration (unsigned version).
Definition time.c:524
#define NS_PER_MS
Definition time.h:163
void adaptive_sleep_init(adaptive_sleep_state_t *state, const adaptive_sleep_config_t *config)
Initialize adaptive sleep state with configuration.
Definition time.c:588
int time_human_readable(int64_t nanoseconds, char *buffer, size_t buffer_size)
Format nanoseconds as human-readable relative duration (moment.js style).
Definition time.c:549
#define UTIL_TIME_TIMER_NAME_BUFFER_SIZE
Definition time.h:43
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
#define NS_PER_US_INT
Definition time.h:171
int format_uptime_hms(int hours, int minutes, int seconds, char *buffer, size_t buffer_size)
Format uptime as HH:MM:SS string.
Definition time.c:346
void time_sleep_ns(uint64_t ns)
Configuration for adaptive sleep behavior.
Definition time.c:116
bool timer_is_initialized(void)
Check if timing system is initialized.
Definition time.c:338
bool timer_system_init(void)
Initialize the timing system.
Definition time.c:164
void adaptive_sleep_do(adaptive_sleep_state_t *state, size_t queue_depth, size_t target_depth)
Calculate sleep time and immediately sleep for that duration.
Definition time.c:677
#define NS_PER_US
Definition time.h:162
struct timer_record timer_record_t
Individual timer record for a named timing operation.
#define UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE
Definition time.h:44
#define NS_PER_DAY_INT
Definition time.h:190
asciichat_error_t time_format_safe(const char *format_str, char *buf, size_t buf_size)
Safe wrapper for time formatting with validation and error codes.
Definition time.c:818
int time_human_readable_now(char *buffer, size_t buffer_size)
Format current monotonic time as human-readable relative duration.
Definition time.c:579
#define NS_PER_SEC
Definition time.h:164
⚙️ Common definitions, error codes, macros, and types shared throughout the application
action_args_t args
🔤 String Manipulation and Shell Escaping Utilities
Configuration for adaptive sleep behavior.
Definition time.h:683
double min_speed_multiplier
Minimum speed (max sleep) - usually 1.0 (baseline speed).
Definition time.h:685
double max_speed_multiplier
Maximum speed (min sleep) - e.g., 4.0 = process 4x faster.
Definition time.h:686
uint64_t baseline_sleep_ns
Normal sleep time in nanoseconds (when queue is at target).
Definition time.h:684
double speedup_rate
Ramp-up rate when queue builds (0.0-1.0, higher = faster ramp).
Definition time.h:687
double slowdown_rate
Ramp-down rate when queue empties (0.0-1.0, higher = faster ramp).
Definition time.h:688
Runtime state for adaptive sleep.
Definition time.h:699
double current_speed_multiplier
Current speed state (1.0 = baseline, >1.0 = faster).
Definition time.h:701
uint64_t last_sleep_ns
Last calculated sleep time (for debugging).
Definition time.h:702
adaptive_sleep_config_t config
Configuration (copied, not referenced).
Definition time.h:700
uint64_t start_ticks
Start time in sokol ticks.
Definition time.h:266
char * name
Timer name (heap-allocated, unique key).
Definition time.h:265
rwlock_t rwlock
Definition time.c:39
lifecycle_t lifecycle
Lifecycle state machine for init/shutdown synchronization.
Definition time.c:42
timer_record_t * timers
Hash table of active timers (uthash head pointer).
Definition time.c:38
#define UTIL_TIME_TEMP_BUFFER_SIZE
Definition time.c:8
⏱️ High-precision timing utilities using sokol_time.h and uthash
int platform_localtime(const time_t *timer, struct tm *result)
Definition util.c:57