ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Utilities

🛠️ Core utility functions for string manipulation, paths, IP parsing, and formatting More...

Topics

 Utility Functions
 🛠️ String, path, IP, UTF-8, CRC32, and formatting utilities

Files

file  time.c
 ⏱️ High-precision timing utilities implementation
file  time.h
 ⏱️ High-precision timing utilities using sokol_time.h and uthash

Data Structures

struct  timer_record
 Individual timer record for a named timing operation. More...
struct  adaptive_sleep_config_t
 Configuration for adaptive sleep behavior. More...
struct  adaptive_sleep_state_t
 Runtime state for adaptive sleep. More...

Macros

#define TIME_DURATION_BUFFER_SIZE   32
#define UTIL_TIME_TIMER_NAME_BUFFER_SIZE   256
#define UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE   280
#define TIME_ATOMIC_UINT64   atomic_t
#define TIME_ATOMIC_UINT64_INIT(val)
#define NS_PER_US   1000.0
#define NS_PER_MS   (1000.0 * NS_PER_US)
#define NS_PER_SEC   (1000.0 * NS_PER_MS)
#define NS_PER_MIN   (60.0 * NS_PER_SEC)
#define NS_PER_HOUR   (60.0 * NS_PER_MIN)
#define NS_PER_DAY   (24.0 * NS_PER_HOUR)
#define NS_PER_YEAR   (365.25 * NS_PER_DAY)
#define NS_PER_US_INT   1000ULL
#define NS_PER_MS_INT   (1000ULL * NS_PER_US_INT)
#define NS_PER_SEC_INT   (1000ULL * NS_PER_MS_INT)
#define US_PER_MS_INT   1000ULL
#define US_PER_SEC_INT   1000000ULL
#define MS_PER_SEC_INT   1000ULL
#define SEC_PER_MIN   60ULL
#define SEC_PER_HOUR   (SEC_PER_MIN * SEC_PER_MIN)
#define SEC_PER_DAY   (24ULL * SEC_PER_HOUR)
#define NS_PER_MIN_INT   (SEC_PER_MIN * NS_PER_SEC_INT)
#define NS_PER_HOUR_INT   (SEC_PER_HOUR * NS_PER_SEC_INT)
#define NS_PER_DAY_INT   (SEC_PER_DAY * NS_PER_SEC_INT)
#define START_TIMER(name_fmt, ...)
 Start a timer with formatted name.
#define START_TIMER_GLOBAL(name_fmt, ...)
 Start a timer without thread ID (for cross-thread timers).
#define STOP_TIMER_GLOBAL(name_fmt, ...)
 Stop a cross-thread timer and return elapsed time.
#define STOP_TIMER(name_fmt, ...)
 Stop a timer with formatted name and return elapsed time.
#define STOP_TIMER_AND_LOG(log_level, threshold_ns, timer_name, msg_fmt, ...)
 Stop a timer and log the result with a custom message.
#define STOP_TIMER_AND_LOG_EVERY(log_level, interval_ns, threshold_ns, timer_name, msg_fmt, ...)
 Stop a timer and log the result with rate limiting.

Typedefs

typedef struct timer_record timer_record_t
 Individual timer record for a named timing operation.

Functions

void time_sleep_ns (uint64_t ns)
 Configuration for adaptive sleep behavior.
uint64_t time_elapsed_ns (uint64_t start_ns, uint64_t end_ns)
 Calculate elapsed time with wraparound safety.
bool timer_system_init (void)
 Initialize the timing system.
void timer_system_destroy (void)
 Cleanup the timing system.
bool timer_start (const char *name)
 Start a named timer.
double timer_stop (const char *name)
 Stop a named timer and return elapsed time.
bool timer_is_initialized (void)
 Check if timing system is initialized.
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.
int time_pretty_now (int decimals, char *buffer, size_t buffer_size)
 Format current monotonic time as pretty duration.
int time_human_readable (int64_t nanoseconds, char *buffer, size_t buffer_size)
 Format nanoseconds as human-readable relative duration (moment.js style).
int time_human_readable_unsigned (uint64_t nanoseconds, char *buffer, size_t buffer_size)
 Format elapsed time as human-readable relative duration (unsigned version).
int time_human_readable_now (char *buffer, size_t buffer_size)
 Format current monotonic time as human-readable relative duration.
int format_uptime_hms (int hours, int minutes, int seconds, char *buffer, size_t buffer_size)
 Format uptime as HH:MM:SS string.
void adaptive_sleep_init (adaptive_sleep_state_t *state, const adaptive_sleep_config_t *config)
 Initialize adaptive sleep state with configuration.
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.
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.
bool time_format_is_valid_strftime (const char *format_str)
 Validate strftime format string against known safe specifiers.
int time_format_now (const char *format_str, char *buf, size_t buf_size)
 Format current time using strftime format string.
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.
uint64_t time_timespec_to_ns (const struct timespec *ts)
 Convert struct timespec to nanoseconds.

Detailed Description

🛠️ Core utility functions for string manipulation, paths, IP parsing, and formatting

String utilities, path handling, IP address parsing, UTF-8 support, CRC32, and formatting.

This module provides a simple timing API for performance measurement:

  • START_TIMER("name", ...) - Begin timing with formatted message
  • STOP_TIMER("name") - End timing, log result, return elapsed time

Features:

  • Cross-platform high-resolution timing (sokol_time.h)
  • Automatic hashtable management for named timers
  • Thread-safe operation with mutex protection
  • Formatted timer names with printf-style arguments
  • Zero overhead when timing is disabled

Example usage:

START_TIMER("process_frame_%d", frame_num);
// ... do work ...
double elapsed_ns = STOP_TIMER("process_frame_%d", frame_num);
// Use time_pretty() for human-readable formatted output
char duration_str[32];
time_pretty((uint64_t)elapsed_ns, -1, duration_str, sizeof(duration_str));
log_info("Frame took %s", duration_str);
unsigned long long uint64_t
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
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:368
#define START_TIMER(name_fmt,...)
Start a timer with formatted name.
Definition time.h:349
#define STOP_TIMER(name_fmt,...)
Stop a timer with formatted name and return elapsed time.
Definition time.h:418
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025

Macro Definition Documentation

◆ MS_PER_SEC_INT

◆ NS_PER_DAY

#define NS_PER_DAY   (24.0 * NS_PER_HOUR)

#include <include/ascii-chat/util/time.h>

Definition at line 167 of file time.h.

◆ NS_PER_DAY_INT

#define NS_PER_DAY_INT   (SEC_PER_DAY * NS_PER_SEC_INT)

#include <include/ascii-chat/util/time.h>

Definition at line 190 of file time.h.

Referenced by time_pretty().

◆ NS_PER_HOUR

#define NS_PER_HOUR   (60.0 * NS_PER_MIN)

#include <include/ascii-chat/util/time.h>

Definition at line 166 of file time.h.

◆ NS_PER_HOUR_INT

#define NS_PER_HOUR_INT   (SEC_PER_HOUR * NS_PER_SEC_INT)

#include <include/ascii-chat/util/time.h>

Definition at line 189 of file time.h.

Referenced by time_pretty().

◆ NS_PER_MIN

#define NS_PER_MIN   (60.0 * NS_PER_SEC)

#include <include/ascii-chat/util/time.h>

Definition at line 165 of file time.h.

◆ NS_PER_MIN_INT

#define NS_PER_MIN_INT   (SEC_PER_MIN * NS_PER_SEC_INT)

#include <include/ascii-chat/util/time.h>

Definition at line 188 of file time.h.

Referenced by time_pretty().

◆ NS_PER_MS

◆ NS_PER_MS_INT

◆ NS_PER_SEC

◆ NS_PER_SEC_INT

◆ NS_PER_US

#define NS_PER_US   1000.0

#include <include/ascii-chat/util/time.h>

Definition at line 162 of file time.h.

Referenced by time_pretty().

◆ NS_PER_US_INT

#define NS_PER_US_INT   1000ULL

#include <include/ascii-chat/util/time.h>

Definition at line 171 of file time.h.

Referenced by audio_processor_default_config(), and time_pretty().

◆ NS_PER_YEAR

#define NS_PER_YEAR   (365.25 * NS_PER_DAY)

#include <include/ascii-chat/util/time.h>

Definition at line 168 of file time.h.

◆ SEC_PER_DAY

#define SEC_PER_DAY   (24ULL * SEC_PER_HOUR)

#include <include/ascii-chat/util/time.h>

Definition at line 185 of file time.h.

Referenced by update_check_startup().

◆ SEC_PER_HOUR

#define SEC_PER_HOUR   (SEC_PER_MIN * SEC_PER_MIN)

◆ SEC_PER_MIN

#define SEC_PER_MIN   60ULL

#include <include/ascii-chat/util/time.h>

Definition at line 183 of file time.h.

Referenced by parse_timestamp(), and ui_status_render_header().

◆ START_TIMER

#define START_TIMER ( name_fmt,
... )

#include <include/ascii-chat/util/time.h>

Value:
do { \
char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
char _timer_name_with_tid[UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE]; \
snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
snprintf(_timer_name_with_tid, sizeof(_timer_name_with_tid), "%s_tid%llu", _timer_name_buf, (unsigned long long)thread_current_id()); \
(void)timer_start(_timer_name_with_tid); \
} \
} while (0)
bool timer_start(const char *name)
Start a named timer.
Definition time.c:198
#define UTIL_TIME_TIMER_NAME_BUFFER_SIZE
Definition time.h:43
bool timer_is_initialized(void)
Check if timing system is initialized.
Definition time.c:304
#define UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE
Definition time.h:44

Start a timer with formatted name.

The timer name is created by formatting the name_fmt string with the provided arguments. This complete formatted string becomes the unique key in the hashtable.

IMPORTANT: Timer names must be unique. If a timer with the same formatted name already exists, timer_start() will return false and log an error.

Usage: START_TIMER("lock_%p", lock_ptr); // Unique per lock address START_TIMER("process_frame_%d", frame_id); // Unique per frame START_TIMER("client_%u_decode", client_id); // Unique per client

Parameters
name_fmtPrintf-style format string for timer name
...Format arguments to create unique key

Definition at line 349 of file time.h.

349#define START_TIMER(name_fmt, ...) \
350 do { \
351 if (timer_is_initialized()) { \
352 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
353 char _timer_name_with_tid[UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE]; \
354 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
355 snprintf(_timer_name_with_tid, sizeof(_timer_name_with_tid), "%s_tid%llu", _timer_name_buf, (unsigned long long)thread_current_id()); \
356 (void)timer_start(_timer_name_with_tid); \
357 } \
358 } while (0)

◆ START_TIMER_GLOBAL

#define START_TIMER_GLOBAL ( name_fmt,
... )

#include <include/ascii-chat/util/time.h>

Value:
do { \
char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
(void)timer_start(_timer_name_buf); \
} \
} while (0)

Start a timer without thread ID (for cross-thread timers).

Use this variant when a timer may be stopped on a different thread than it was started. The timer name will NOT include thread ID, so it must be globally unique through other means (e.g., including a unique identifier in the format string).

Parameters
name_fmtPrintf-style format string for timer name
...Format arguments to create unique key

Definition at line 372 of file time.h.

372#define START_TIMER_GLOBAL(name_fmt, ...) \
373 do { \
374 if (timer_is_initialized()) { \
375 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
376 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
377 (void)timer_start(_timer_name_buf); \
378 } \
379 } while (0)

◆ STOP_TIMER

#define STOP_TIMER ( name_fmt,
... )

#include <include/ascii-chat/util/time.h>

Value:
({ \
double _elapsed = -1.0; \
char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
char _timer_name_with_tid[UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE]; \
snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
snprintf(_timer_name_with_tid, sizeof(_timer_name_with_tid), "%s_tid%llu", _timer_name_buf, (unsigned long long)thread_current_id()); \
_elapsed = timer_stop(_timer_name_with_tid); \
} \
_elapsed; \
})
double timer_stop(const char *name)
Stop a named timer and return elapsed time.
Definition time.c:249

Stop a timer with formatted name and return elapsed time.

The timer name must match exactly (including all format arguments) with the name used in START_TIMER(). The formatted string is used as the hashtable key lookup.

Usage: double ns = STOP_TIMER("lock_%p", lock_ptr); double ns = STOP_TIMER("process_frame_%d", frame_id);

Parameters
name_fmtPrintf-style format string for timer name (must match START_TIMER)
...Format arguments (must match START_TIMER to create same key)
Returns
Elapsed time in nanoseconds, or -1.0 if timer not found

Definition at line 418 of file time.h.

418#define STOP_TIMER(name_fmt, ...) \
419 ({ \
420 double _elapsed = -1.0; \
421 if (timer_is_initialized()) { \
422 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
423 char _timer_name_with_tid[UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE]; \
424 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
425 snprintf(_timer_name_with_tid, sizeof(_timer_name_with_tid), "%s_tid%llu", _timer_name_buf, (unsigned long long)thread_current_id()); \
426 _elapsed = timer_stop(_timer_name_with_tid); \
427 } \
428 _elapsed; \
429 })

◆ STOP_TIMER_AND_LOG

#define STOP_TIMER_AND_LOG ( log_level,
threshold_ns,
timer_name,
msg_fmt,
... )

#include <include/ascii-chat/util/time.h>

Value:
do { \
double _elapsed_ns = STOP_TIMER(timer_name, ##__VA_ARGS__); \
if (_elapsed_ns >= 0.0 && (threshold_ns == 0 || _elapsed_ns >= (double)(threshold_ns))) { \
char _duration_str[TIME_DURATION_BUFFER_SIZE]; \
time_pretty((uint64_t)_elapsed_ns, -1, _duration_str, sizeof(_duration_str)); \
log_##log_level(msg_fmt " in %s", ##__VA_ARGS__, _duration_str); \
} \
} while (0)
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40

Stop a timer and log the result with a custom message.

Combines STOP_TIMER() with logging. The timer is stopped, elapsed time is retrieved, and a log message is generated with the elapsed time appended in human-readable format. Optionally filters based on a minimum elapsed time threshold.

Usage: STOP_TIMER_AND_LOG(info, 0, "client_handshake", "Crypto handshake completed successfully"); STOP_TIMER_AND_LOG(debug, 5000000, "process_frame_%d", "Frame %d processed", frame_id, frame_id); STOP_TIMER_AND_LOG(dev, NS_PER_MS_INT, "render", "Rendering complete");

The macro will append " in X.XXms" (or appropriate unit) to your message automatically. Supported log levels: dev, debug, info, warn, error, fatal

Parameters
log_levelLog level name (dev, debug, info, warn, error, fatal - without log_ prefix)
threshold_nsMinimum elapsed time in nanoseconds to trigger log (0 = always log)
timer_nameTimer name (must match START_TIMER call)
msg_fmtPrintf-style format string for the message
...Format arguments for both timer name and message

Definition at line 628 of file time.h.

628#define STOP_TIMER_AND_LOG(log_level, threshold_ns, timer_name, msg_fmt, ...) \
629 do { \
630 double _elapsed_ns = STOP_TIMER(timer_name, ##__VA_ARGS__); \
631 if (_elapsed_ns >= 0.0 && (threshold_ns == 0 || _elapsed_ns >= (double)(threshold_ns))) { \
632 char _duration_str[TIME_DURATION_BUFFER_SIZE]; \
633 time_pretty((uint64_t)_elapsed_ns, -1, _duration_str, sizeof(_duration_str)); \
634 log_##log_level(msg_fmt " in %s", ##__VA_ARGS__, _duration_str); \
635 } \
636 } while (0)

Referenced by client_video_render_thread().

◆ STOP_TIMER_AND_LOG_EVERY

#define STOP_TIMER_AND_LOG_EVERY ( log_level,
interval_ns,
threshold_ns,
timer_name,
msg_fmt,
... )

#include <include/ascii-chat/util/time.h>

Value:
do { \
double _elapsed_ns = STOP_TIMER(timer_name, ##__VA_ARGS__); \
if (_elapsed_ns >= 0.0 && (threshold_ns == 0 || _elapsed_ns >= (double)(threshold_ns))) { \
static atomic_t _log_every_last_time = {0}; \
uint64_t _log_every_now = time_get_ns(); \
uint64_t _log_every_last = atomic_load_u64(&_log_every_last_time); \
if (_log_every_now - _log_every_last >= (uint64_t)(interval_ns)) { \
if (atomic_cas_u64(&_log_every_last_time, &_log_every_last, _log_every_now)) { \
char _duration_str[TIME_DURATION_BUFFER_SIZE]; \
time_pretty((uint64_t)_elapsed_ns, -1, _duration_str, sizeof(_duration_str)); \
log_##log_level(msg_fmt " in %s", ##__VA_ARGS__, _duration_str); \
} \
} \
} \
} while (0)
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76

Stop a timer and log the result with rate limiting.

Combines STOP_TIMER() with rate-limited logging. The timer is stopped, elapsed time is retrieved, and a log message is generated only if:

  1. The elapsed time exceeds the threshold (if non-zero), AND
  2. The specified time interval has passed since the last logged occurrence

This prevents log spam from frequent operations while also filtering out fast operations.

Usage: STOP_TIMER_AND_LOG_EVERY(dev, 1000000000, 0, "opus_encode", "Opus encode completed"); STOP_TIMER_AND_LOG_EVERY(info, 5000000000, NS_PER_MS_INT, "process_frame_%d", "Frame %d processed", frame_id);

The macro will append " in X.XXms" (or appropriate unit) to your message automatically. Supported log levels: dev, debug, info, warn, error, fatal

Parameters
log_levelLog level name (dev, debug, info, warn, error, fatal - without log_ prefix)
interval_nsTime interval in nanoseconds between log emissions (rate limiting)
threshold_nsMinimum elapsed time in nanoseconds to trigger log (0 = no threshold)
timer_nameTimer name (must match START_TIMER call)
msg_fmtPrintf-style format string for the message
...Format arguments for both timer name and message

Definition at line 663 of file time.h.

663#define STOP_TIMER_AND_LOG_EVERY(log_level, interval_ns, threshold_ns, timer_name, msg_fmt, ...) \
664 do { \
665 double _elapsed_ns = STOP_TIMER(timer_name, ##__VA_ARGS__); \
666 if (_elapsed_ns >= 0.0 && (threshold_ns == 0 || _elapsed_ns >= (double)(threshold_ns))) { \
667 static atomic_t _log_every_last_time = {0}; \
668 uint64_t _log_every_now = time_get_ns(); \
669 uint64_t _log_every_last = atomic_load_u64(&_log_every_last_time); \
670 if (_log_every_now - _log_every_last >= (uint64_t)(interval_ns)) { \
671 if (atomic_cas_u64(&_log_every_last_time, &_log_every_last, _log_every_now)) { \
672 char _duration_str[TIME_DURATION_BUFFER_SIZE]; \
673 time_pretty((uint64_t)_elapsed_ns, -1, _duration_str, sizeof(_duration_str)); \
674 log_##log_level(msg_fmt " in %s", ##__VA_ARGS__, _duration_str); \
675 } \
676 } \
677 } \
678 } while (0)

◆ STOP_TIMER_GLOBAL

#define STOP_TIMER_GLOBAL ( name_fmt,
... )

#include <include/ascii-chat/util/time.h>

Value:
({ \
double _elapsed = -1.0; \
char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
_elapsed = timer_stop(_timer_name_buf); \
} \
_elapsed; \
})

Stop a cross-thread timer and return elapsed time.

Use this variant when stopping a timer started with START_TIMER_GLOBAL. The timer name must match exactly (without thread ID appended).

Parameters
name_fmtPrintf-style format string for timer name (must match START_TIMER_GLOBAL)
...Format arguments (must match START_TIMER_GLOBAL to create same key)
Returns
Elapsed time in nanoseconds, or -1.0 if timer not found

Definition at line 392 of file time.h.

392#define STOP_TIMER_GLOBAL(name_fmt, ...) \
393 ({ \
394 double _elapsed = -1.0; \
395 if (timer_is_initialized()) { \
396 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
397 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
398 _elapsed = timer_stop(_timer_name_buf); \
399 } \
400 _elapsed; \
401 })

◆ TIME_ATOMIC_UINT64

#define TIME_ATOMIC_UINT64   atomic_t

#include <include/ascii-chat/util/time.h>

Definition at line 63 of file time.h.

◆ TIME_ATOMIC_UINT64_INIT

#define TIME_ATOMIC_UINT64_INIT ( val)

#include <include/ascii-chat/util/time.h>

Value:
{0}

Definition at line 64 of file time.h.

◆ TIME_DURATION_BUFFER_SIZE

◆ US_PER_MS_INT

◆ US_PER_SEC_INT

◆ UTIL_TIME_TIMER_NAME_BUFFER_SIZE

#define UTIL_TIME_TIMER_NAME_BUFFER_SIZE   256

#include <include/ascii-chat/util/time.h>

Definition at line 43 of file time.h.

◆ UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE

#define UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE   280

#include <include/ascii-chat/util/time.h>

Definition at line 44 of file time.h.

Typedef Documentation

◆ timer_record_t

typedef struct timer_record timer_record_t

#include <include/ascii-chat/util/time.h>

Individual timer record for a named timing operation.

Function Documentation

◆ adaptive_sleep_calculate()

uint64_t adaptive_sleep_calculate ( adaptive_sleep_state_t * state,
size_t queue_depth,
size_t target_depth )

#include <include/ascii-chat/util/time.h>

Calculate adaptive sleep time based on queue depth.

Evaluates current queue depth against target and adjusts the speed multiplier:

  • If queue_depth > target_depth: speed up (reduce sleep, drain queue faster)
  • If queue_depth < target_depth: slow down (increase sleep back to baseline)
  • Speed multiplier changes gradually based on speedup_rate/slowdown_rate

The actual sleep time is calculated as: baseline_sleep_ns / current_speed_multiplier

Example usage:

.baseline_sleep_ns = 16666667, // ~60 FPS (16.67ms)
.min_speed_multiplier = 1.0, // Never slower than baseline
.max_speed_multiplier = 4.0, // Can process up to 4x faster (240 FPS)
.speedup_rate = 0.1, // Ramp up 10% per frame
.slowdown_rate = 0.05 // Ramp down 5% per frame
};
adaptive_sleep_init(&sleep_state, &config);
while (running) {
// Process one frame/packet/unit of work
process_data();
// Sleep adaptively based on queue depth
size_t queue_depth = get_queue_size();
uint64_t sleep_ns = adaptive_sleep_calculate(&sleep_state, queue_depth, 10);
platform_sleep_us(sleep_ns / 1000);
}
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:556
void adaptive_sleep_init(adaptive_sleep_state_t *state, const adaptive_sleep_config_t *config)
Initialize adaptive sleep state with configuration.
Definition time.c:535
Configuration for adaptive sleep behavior.
Definition time.h:693
Runtime state for adaptive sleep.
Definition time.h:709
Parameters
statePointer to adaptive sleep state (will be updated)
queue_depthCurrent number of items in queue/buffer
target_depthDesired queue depth (0 = empty queue target)
Returns
Sleep time in nanoseconds

Definition at line 556 of file time.c.

556 {
557 if (!state) {
558 return 0;
559 }
560
561 const adaptive_sleep_config_t *cfg = &state->config;
562
563 // Determine if we need to speed up or slow down
564 double desired_multiplier;
565
566 if (queue_depth > target_depth) {
567 // Queue is building up - speed up processing
568 // The more items in queue, the faster we should process
569 size_t backlog = queue_depth - target_depth;
570
571 // Calculate desired speed based on backlog
572 // Each item above target increases speed proportionally
573 // This ensures we drain the queue faster the more backed up we are
574 double backlog_factor = 1.0 + ((double)backlog / (double)(target_depth + 1));
575 desired_multiplier = cfg->min_speed_multiplier * backlog_factor;
576
577 // Clamp to max speed
578 if (desired_multiplier > cfg->max_speed_multiplier) {
579 desired_multiplier = cfg->max_speed_multiplier;
580 }
581
582 // Ramp up gradually based on speedup_rate
583 double delta = desired_multiplier - state->current_speed_multiplier;
584 state->current_speed_multiplier += delta * cfg->speedup_rate;
585
586 } else {
587 // Queue is at or below target - slow down to baseline
588 desired_multiplier = 1.0;
589 if (desired_multiplier < cfg->min_speed_multiplier) {
590 desired_multiplier = cfg->min_speed_multiplier;
591 }
592 if (desired_multiplier > cfg->max_speed_multiplier) {
593 desired_multiplier = cfg->max_speed_multiplier;
594 }
595
596 // Ramp down gradually based on slowdown_rate
597 double delta = desired_multiplier - state->current_speed_multiplier;
598 state->current_speed_multiplier += delta * cfg->slowdown_rate;
599 }
600
601 // Ensure we stay within configured bounds
604 }
607 }
608
609 // Calculate actual sleep time: baseline / speed_multiplier
610 // Higher multiplier = shorter sleep = faster processing
612
613 // Store for debugging
614 state->last_sleep_ns = sleep_ns;
615
616 return sleep_ns;
617}
double min_speed_multiplier
Minimum speed (max sleep) - usually 1.0 (baseline speed).
Definition time.h:695
double max_speed_multiplier
Maximum speed (min sleep) - e.g., 4.0 = process 4x faster.
Definition time.h:696
uint64_t baseline_sleep_ns
Normal sleep time in nanoseconds (when queue is at target).
Definition time.h:694
double speedup_rate
Ramp-up rate when queue builds (0.0-1.0, higher = faster ramp).
Definition time.h:697
double slowdown_rate
Ramp-down rate when queue empties (0.0-1.0, higher = faster ramp).
Definition time.h:698
double current_speed_multiplier
Current speed state (1.0 = baseline, >1.0 = faster).
Definition time.h:711
uint64_t last_sleep_ns
Last calculated sleep time (for debugging).
Definition time.h:712
adaptive_sleep_config_t config
Configuration (copied, not referenced).
Definition time.h:710

References adaptive_sleep_config_t::baseline_sleep_ns, adaptive_sleep_state_t::config, adaptive_sleep_state_t::current_speed_multiplier, adaptive_sleep_state_t::last_sleep_ns, adaptive_sleep_config_t::max_speed_multiplier, adaptive_sleep_config_t::min_speed_multiplier, adaptive_sleep_config_t::slowdown_rate, and adaptive_sleep_config_t::speedup_rate.

Referenced by adaptive_sleep_do().

◆ adaptive_sleep_do()

void adaptive_sleep_do ( adaptive_sleep_state_t * state,
size_t queue_depth,
size_t target_depth )

#include <include/ascii-chat/util/time.h>

Calculate sleep time and immediately sleep for that duration.

Convenience wrapper that combines adaptive_sleep_calculate() with platform_sleep_us(). Useful for simple loops that don't need to inspect the calculated sleep time.

Parameters
statePointer to adaptive sleep state (will be updated)
queue_depthCurrent number of items in queue/buffer
target_depthDesired queue depth (0 = empty queue target)

Definition at line 619 of file time.c.

619 {
620 uint64_t sleep_ns = adaptive_sleep_calculate(state, queue_depth, target_depth);
621
622 if (sleep_ns > 0) {
623 platform_sleep_ns(sleep_ns);
624 }
625}

References adaptive_sleep_calculate().

◆ adaptive_sleep_init()

void adaptive_sleep_init ( adaptive_sleep_state_t * state,
const adaptive_sleep_config_t * config )

#include <include/ascii-chat/util/time.h>

Initialize adaptive sleep state with configuration.

Sets up an adaptive sleep state structure with the provided configuration. The configuration is copied internally, so the caller doesn't need to keep the config structure alive.

Parameters
statePointer to adaptive sleep state to initialize
configPointer to configuration (will be copied)

Definition at line 535 of file time.c.

535 {
536 if (!state || !config) {
537 return;
538 }
539
540 // Copy configuration
541 state->config = *config;
542
543 // A multiplier of 1.0 preserves the configured interval. Clamp it for
544 // configurations whose allowed range does not include the baseline.
545 state->current_speed_multiplier = 1.0;
546 if (state->current_speed_multiplier < config->min_speed_multiplier) {
548 }
549 if (state->current_speed_multiplier > config->max_speed_multiplier) {
551 }
552
554}

References adaptive_sleep_config_t::baseline_sleep_ns, adaptive_sleep_state_t::config, adaptive_sleep_state_t::current_speed_multiplier, adaptive_sleep_state_t::last_sleep_ns, adaptive_sleep_config_t::max_speed_multiplier, and adaptive_sleep_config_t::min_speed_multiplier.

◆ format_uptime_hms()

int format_uptime_hms ( int hours,
int minutes,
int seconds,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/util/time.h>

Format uptime as HH:MM:SS string.

Parameters
hoursHours component (0-999)
minutesMinutes component (0-59)
secondsSeconds component (0-59)
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Formats an uptime duration as a fixed "HH:MM:SS" string with zero-padding. Useful for status displays where consistent formatting is preferred over adaptive human-readable formats.

Examples:

  • format_uptime_hms(0, 0, 5, buf, size) -> "00:00:05"
  • format_uptime_hms(1, 30, 45, buf, size) -> "01:30:45"
  • format_uptime_hms(123, 45, 6, buf, size) -> "123:45:06"
Note
Buffer should be at least 12 bytes (HH:MM:SS + null terminator)
Thread-safe (no global state)
Hours component can exceed 99 (e.g., "123:45:06" for 123 hours)

Definition at line 312 of file time.c.

312 {
313 if (!buffer || buffer_size == 0) {
314 return -1;
315 }
316
317 // Validate components
318 if (hours < 0 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60) {
319 return -1;
320 }
321
322 // Format as HH:MM:SS with zero-padding
323 int written = safe_snprintf(buffer, buffer_size, "%02d:%02d:%02d", hours, minutes, seconds);
324
325 if (written < 0 || (size_t)written >= buffer_size) {
326 return -1;
327 }
328
329 return written;
330}
int buffer_size
Size of circular buffer.
Definition grep.c:68

References buffer_size.

Referenced by ui_status_render_header().

◆ time_elapsed_ns()

uint64_t time_elapsed_ns ( uint64_t start_ns,
uint64_t end_ns )

#include <include/ascii-chat/util/time.h>

Calculate elapsed time with wraparound safety.

Computes the difference between two time values, handling potential wraparound of uint64_t (which won't happen in practice - uint64_t wraps after ~584 years at nanosecond resolution, but this is defensive).

Parameters
start_nsStart time in nanoseconds
end_nsEnd time in nanoseconds
Returns
Elapsed time in nanoseconds (end - start)

Usage:

uint64_t start = time_get_ns();
// ... do work ...
uint64_t elapsed = time_elapsed_ns(start, time_get_ns());
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117

Definition at line 117 of file time.c.

117 {
118 // Handle wraparound (defensive - uint64_t won't wrap in practice at nanosecond resolution)
119 // but this is safe and handles any theoretical edge cases
120 if (end_ns >= start_ns) {
121 return end_ns - start_ns;
122 }
123 // Wraparound case (extremely unlikely)
124 return (UINT64_MAX - start_ns) + end_ns + 1;
125}

Referenced by ascii_convert_with_buffers_stabilized(), asciichat_instr_log_line(), audio_analysis_print_report(), fps_frame_ns(), media_source_read_video(), media_source_seek(), mixer_process_excluding_source(), session_capture_get_current_fps(), session_render_loop(), and webrtc_peer_manager_check_gathering_timeouts().

◆ time_format_is_valid_strftime()

bool time_format_is_valid_strftime ( const char * format_str)

#include <include/ascii-chat/util/time.h>

Validate strftime format string against known safe specifiers.

Parameters
format_strFormat string to validate (e.g., "%H:%M:%S")
Returns
true if valid, false if contains invalid specifiers or syntax

Validates format string by checking each % specifier against a whitelist of known safe POSIX strftime specifiers. Returns false if:

  • Contains unterminated % sequences
  • Contains invalid/unsupported specifiers
  • Contains malformed width/precision
  • Contains unsupported locale-dependent specifiers

Supported specifiers:

  • Date: Y (4-digit year), m (month), d (day), j (day of year)
  • Date (ISO): F (full date), G (ISO year), g (ISO year short), V (ISO week)
  • Time: H (24-hour), M (minute), S (second), I (12-hour), p (AM/PM)
  • Time (combined): T (full time HH:MM:SS), s (seconds since epoch)
  • Locale: a (abbrev weekday), A (full weekday), b (abbrev month), B (full month)
  • Locale: c (locale date/time), x (locale date), X (locale time)
  • Timezone: z (offset), Z (name)
  • Weekday: w (0-6), u (1-7)

Definition at line 637 of file time.c.

637 {
638 if (!format_str) {
639 return false;
640 }
641
642 for (const char *p = format_str; *p; p++) {
643 if (*p == '%') {
644 p++;
645 if (!*p) {
646 /* Unterminated % at end of string */
647 log_error("Invalid time format: unterminated %% at end");
648 return false;
649 }
650
651 if (*p == '%') {
652 /* Escaped %% - this is valid, just skip it */
653 continue;
654 }
655
656 /* Optional: flag characters (-, 0, +, space) */
657 if (*p == '-' || *p == '0' || *p == '+' || *p == ' ') {
658 p++;
659 if (!*p) {
660 log_error("Invalid time format: flag character without specifier");
661 return false;
662 }
663 }
664
665 /* Optional: width specifier (digits or *) */
666 if (*p == '*' || isdigit((unsigned char)*p)) {
667 while (*p && (isdigit((unsigned char)*p) || *p == '*')) {
668 p++;
669 }
670 if (!*p) {
671 log_error("Invalid time format: width specifier without specifier character");
672 return false;
673 }
674 }
675
676 /* Optional: precision specifier (.digits or .*) */
677 if (*p == '.') {
678 p++;
679 if (!*p) {
680 log_error("Invalid time format: precision specifier incomplete");
681 return false;
682 }
683 while (*p && (isdigit((unsigned char)*p) || *p == '*')) {
684 p++;
685 }
686 if (!*p) {
687 log_error("Invalid time format: precision specifier without specifier character");
688 return false;
689 }
690 }
691
692 /* Optional: modifier characters (E for %Ex, O for %Ox) */
693 if (*p == 'E' || *p == 'O') {
694 p++;
695 if (!*p) {
696 log_error("Invalid time format: modifier character without specifier");
697 return false;
698 }
699 }
700
701 /* Validate that the final character is a supported specifier */
702 if (!strchr(SUPPORTED_SPECIFIERS, *p)) {
703 log_error("Invalid time format: unsupported specifier %%%c (at position %ld)", *p, (p - format_str));
704 return false;
705 }
706 }
707 }
708
709 return true;
710}
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628

References log_error.

Referenced by time_format_safe().

◆ time_format_now()

int time_format_now ( const char * format_str,
char * buf,
size_t buf_size )

#include <include/ascii-chat/util/time.h>

Format current time using strftime format string.

Parameters
format_strstrftime format string (should be validated with time_format_is_valid_strftime)
bufOutput buffer
buf_sizeOutput buffer size
Returns
Number of characters written (excluding null terminator), or 0 on error

Formats current wall-clock time (CLOCK_REALTIME) using the provided strftime format. Handles nanosecond precision separately: if format contains S and buffer has room, appends ".NNNNNN" for microseconds (rounded from nanoseconds).

Example outputs:

  • Format "%H:%M:%S" → "14:30:45.123456"
  • Format "%Y-%m-%d" → "2026-02-16"
  • Format "%F %T" → "2026-02-16 14:30:45.123456"

Notes:

  • Buffer size should be at least 64 bytes
  • Automatic microsecond appending occurs only when S is in format
  • Output is locale-aware (UTF-8 safe from strftime)
  • Returns 0 on error (strftime failure or buffer overflow)

Definition at line 712 of file time.c.

712 {
713 if (!format_str || !buf || buf_size < 2) {
714 SET_ERRNO(ERROR_INVALID_PARAM, "invalid arguments - format_str=%p, buf=%p, buf_size=%zu", format_str, buf, buf_size);
715 return 0;
716 }
717
718 /* Get current wall-clock time in nanoseconds */
719 uint64_t ts_ns = time_get_realtime_ns();
720
721 /* Extract seconds and nanoseconds */
722 time_t seconds = (time_t)(ts_ns / NS_PER_SEC_INT);
723
724 /* Convert seconds to struct tm */
725 struct tm tm_info;
726 platform_localtime(&seconds, &tm_info);
727
728 /* Format using strftime */
729 size_t len = strftime(buf, buf_size, format_str, &tm_info);
730
731 /* Check for strftime errors or buffer overflow */
732 if (len == 0) {
733 /* strftime returned 0 - either error or exact buffer fill */
734 log_debug("strftime returned 0 for format: %s", format_str);
735 return 0;
736 }
737
738 if (len >= buf_size - 1) {
739 /* Buffer would overflow - strftime filled entire buffer or hit exact size */
740 log_error("buffer too small (need %zu, have %zu)", len + 1, buf_size);
741 return 0;
742 }
743
744 return (int)len;
745}
#define SET_ERRNO(code,...)
@ ERROR_INVALID_PARAM
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
int platform_localtime(const time_t *timer, struct tm *result)
Definition util.c:57

References ERROR_INVALID_PARAM, log_debug, log_error, NS_PER_SEC_INT, platform_localtime(), and SET_ERRNO.

Referenced by log_template_apply(), and time_format_safe().

◆ time_format_safe()

asciichat_error_t time_format_safe ( const char * format_str,
char * buf,
size_t buf_size )

#include <include/ascii-chat/util/time.h>

Safe wrapper for time formatting with validation and error codes.

Parameters
format_strFormat string to use
bufOutput buffer
buf_sizeOutput buffer size
Returns
ASCIICHAT_OK on success, error code on failure (includes error context)

Validates format string first, then formats time. Returns detailed error if:

  • format_str is NULL
  • buf is NULL
  • buf_size < 64 (minimum safe size)
  • format_str contains invalid specifiers
  • strftime fails

All errors include context message via SET_ERRNO for debugging.

Example:

char timebuf[64];
asciichat_error_t err = time_format_safe("%H:%M:%S", timebuf, sizeof(timebuf));
if (err != ASCIICHAT_OK) {
log_error("Failed to format time");
return err;
}
log_info("Current time: %s", timebuf);
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
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:747

Definition at line 747 of file time.c.

747 {
748 /* Check NULL pointers */
749 if (!format_str) {
750 return SET_ERRNO(ERROR_INVALID_STATE, "format_str is NULL");
751 }
752
753 if (!buf) {
754 return SET_ERRNO(ERROR_INVALID_STATE, "buf is NULL");
755 }
756
757 /* Check minimum buffer size */
758 if (buf_size < 64) {
759 return SET_ERRNO(ERROR_INVALID_STATE, "buffer too small (minimum 64 bytes, got %zu)", buf_size);
760 }
761
762 /* Validate format string */
763 if (!time_format_is_valid_strftime(format_str)) {
764 return SET_ERRNO(ERROR_INVALID_STATE, "invalid time format: %s", format_str);
765 }
766
767 /* Format the time */
768 int result = time_format_now(format_str, buf, buf_size);
769 if (result <= 0) {
770 return SET_ERRNO(ERROR_INVALID_STATE, "strftime formatting failed");
771 }
772
773 return ASCIICHAT_OK;
774}
@ ERROR_INVALID_STATE
bool time_format_is_valid_strftime(const char *format_str)
Validate strftime format string against known safe specifiers.
Definition time.c:637
int time_format_now(const char *format_str, char *buf, size_t buf_size)
Format current time using strftime format string.
Definition time.c:712

References ASCIICHAT_OK, ERROR_INVALID_STATE, SET_ERRNO, time_format_is_valid_strftime(), and time_format_now().

◆ time_human_readable()

int time_human_readable ( int64_t nanoseconds,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/util/time.h>

Format nanoseconds as human-readable relative duration (moment.js style).

Parameters
nanosecondsDuration in nanoseconds
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Formats a duration using moment.js-compatible thresholds to produce natural language relative time strings like "a few seconds ago", "3 minutes ago", "2 hours ago", etc.

Threshold table (moment.js compatible):

  • < 45 s → "a few seconds ago"
  • < 90 s → "a minute ago"
  • < 45 min → "%d minutes ago"
  • < 90 min → "an hour ago"
  • < 22 h → "%d hours ago"
  • < 36 h → "a day ago"
  • < 25 d → "%d days ago"
  • < 45 d → "a month ago"
  • < 11 months → "%d months ago"
  • < 18 months → "a year ago"
  • ≥ 18 months → "%d years ago"
Note
Buffer should be at least 32 bytes for all possible outputs
Thread-safe (no global state)

Format elapsed time as human-readable relative duration with past/future support

Parameters
nanosecondsSigned elapsed nanoseconds (negative for future times)
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Formats a duration as a human-readable string with moment.js-compatible thresholds. Supports both past times ("3 hours ago") and future times ("in 5 minutes").

Examples:

  • Positive: 3600000000000 ns → "an hour ago"
  • Negative: -300000000000 ns → "in 5 minutes"
Note
Use positive values for elapsed time (past), negative for countdown (future)
Buffer should be at least 32 bytes for all possible outputs
Thread-safe (no global state)

Definition at line 499 of file time.c.

499 {
500 if (!buffer || buffer_size == 0) {
501 return -1;
502 }
503
504 // Determine direction (past vs future)
505 bool is_future = nanoseconds < 0;
506 uint64_t abs_ns = is_future ? (uint64_t)(-nanoseconds) : (uint64_t)nanoseconds;
507
508 // Convert nanoseconds to seconds for threshold checking
509 double total_seconds = (double)abs_ns / NS_PER_SEC;
510 int minutes = (int)(total_seconds / 60);
511 int hours = minutes / 60;
512 int days = hours / 24;
513 int months = days / 30; // Approximate
514 int years = months / 12;
515
516 const char *suffix = is_future ? "from now" : "ago";
517 int written = format_human_readable_time_ago(total_seconds, minutes, hours, days, months, years, suffix, buffer, buffer_size);
518
519 if (written < 0 || (size_t)written >= buffer_size) {
520 return -1;
521 }
522
523 return written;
524}
#define NS_PER_SEC
Definition time.h:164

References buffer_size, and NS_PER_SEC.

Referenced by time_human_readable_now().

◆ time_human_readable_now()

int time_human_readable_now ( char * buffer,
size_t buffer_size )

#include <include/ascii-chat/util/time.h>

Format current monotonic time as human-readable relative duration.

Parameters
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Convenience wrapper that calls time_get_ns() and delegates to time_human_readable(). Useful for measuring time since program start in a single call.

Note
Buffer should be at least 32 bytes for all possible outputs
Thread-safe (no global state)

Definition at line 526 of file time.c.

526 {
527 int64_t ns = (int64_t)time_get_ns();
528 return time_human_readable(ns, buffer, buffer_size);
529}
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:499

References buffer_size, and time_human_readable().

◆ time_human_readable_unsigned()

int time_human_readable_unsigned ( uint64_t nanoseconds,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/util/time.h>

Format elapsed time as human-readable relative duration (unsigned version).

Parameters
nanosecondsUnsigned elapsed nanoseconds (always past times)
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Formats unsigned nanosecond durations as human-readable past-time strings. Uses moment.js-compatible thresholds. All values are interpreted as elapsed time and formatted with "ago" suffix.

Examples:

  • 3600000000000 ns → "an hour ago"
  • 300000000000 ns → "5 minutes ago"
Note
Use this for values from time_get_ns() or other unsigned sources
Buffer should be at least 32 bytes for all possible outputs
Thread-safe (no global state)

Definition at line 477 of file time.c.

477 {
478 if (!buffer || buffer_size == 0) {
479 return -1;
480 }
481
482 // Convert nanoseconds to seconds for threshold checking
483 double total_seconds = (double)nanoseconds / NS_PER_SEC;
484 int minutes = (int)(total_seconds / 60);
485 int hours = minutes / 60;
486 int days = hours / 24;
487 int months = days / 30; // Approximate
488 int years = months / 12;
489
490 int written = format_human_readable_time_ago(total_seconds, minutes, hours, days, months, years, "ago", buffer, buffer_size);
491
492 if (written < 0 || (size_t)written >= buffer_size) {
493 return -1;
494 }
495
496 return written;
497}

References buffer_size, and NS_PER_SEC.

◆ time_pretty()

int time_pretty ( uint64_t nanoseconds,
int decimals,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/util/time.h>

Format nanoseconds as a compact duration with configurable sub-minute precision.

Parameters
nanosecondsDuration in nanoseconds
decimalsNumber of decimal places (0-9), or -1 for sensible defaults per range
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Formats sub-minute durations without spaces between the number and unit. Strips trailing fractional zeros. Minutes and hours omit fractions; days omit seconds.

Examples (with decimals=-1):

  • 100 ns → "100ns"
  • 3500 ns → "3.5µs"
  • 255000000 ns → "255ms"
  • 2500000000 ns → "2.5s"
  • 83456000000 ns → "1:23" (minutes range, M:SS)
  • 7530000000000 ns → "2:05:30" (hours range, H:MM:SS)
  • 3207240000000000 ns → "37d 2:54" (days range, Dd H:MM)

Unit selection logic:

  • [0, 1k) ns → "NNNns"
  • [1k, 1M) ns → "N.Nµs" (up to 3 decimals)
  • [1M, 1G) ns → "N.NNNms" (up to 3 decimals)
  • [1G, 60G) ns → "N.NNs" (up to 2 decimals)
  • [60G, 3.6T) ns → "M:SS"
  • [3.6T, 86.4T) ns → "H:MM:SS"
  • [86.4T+) ns → "Dd H:MM"
Note
Buffer should be at least 32 bytes for all possible outputs
Thread-safe (no global state)
decimals=-1 uses appropriate defaults (3 for µs/ms, 2 for s)
decimals applies only below one minute; larger durations truncate omitted fields
decimals=0 produces no decimal point

Definition at line 368 of file time.c.

368 {
369 if (!buffer || buffer_size == 0) {
370 return -1;
371 }
372
373 // Handle zero
374 if (nanoseconds == 0) {
375 int written = safe_snprintf(buffer, buffer_size, "0ns");
376 return (written < 0 || (size_t)written >= buffer_size) ? -1 : written;
377 }
378
379 // Determine decimals for this range if not explicitly set
380 int actual_decimals = decimals;
381 if (decimals == -1) {
382 if (nanoseconds < NS_PER_MIN_INT) {
383 actual_decimals = (nanoseconds < NS_PER_SEC_INT) ? 3 : 2; // ns/µs/ms or seconds
384 } else {
385 actual_decimals = 0; // colon notation uses whole seconds
386 }
387 }
388
389 // Clamp decimals to valid range
390 if (actual_decimals < 0)
391 actual_decimals = 0;
392 if (actual_decimals > 9)
393 actual_decimals = 9;
394
395 int written = 0;
396
397 // Nanoseconds (< 1µs)
398 if (nanoseconds < NS_PER_US_INT) {
399 written = safe_snprintf(buffer, buffer_size, "%lluns", (unsigned long long)nanoseconds);
400 }
401 // Microseconds (< 1ms)
402 else if (nanoseconds < NS_PER_MS_INT) {
403 double us = (double)nanoseconds / NS_PER_US;
404 char temp_buf[UTIL_TIME_TEMP_BUFFER_SIZE];
405 // Use a direct snprintf with large enough buffer first
406 snprintf(temp_buf, sizeof(temp_buf), "%.*fµs", actual_decimals, us);
407 strip_trailing_zeros(temp_buf);
408 written = (int)strlen(temp_buf);
409 if (written > 0 && written < (int)buffer_size) {
410 SAFE_STRNCPY(buffer, temp_buf, buffer_size);
411 } else {
412 written = -1;
413 }
414 }
415 // Milliseconds (< 1s)
416 else if (nanoseconds < NS_PER_SEC_INT) {
417 double ms = (double)nanoseconds / NS_PER_MS;
418 char temp_buf[UTIL_TIME_TEMP_BUFFER_SIZE];
419 snprintf(temp_buf, sizeof(temp_buf), "%.*fms", actual_decimals, ms);
420 strip_trailing_zeros(temp_buf);
421 written = (int)strlen(temp_buf);
422 if (written > 0 && written < (int)buffer_size) {
423 SAFE_STRNCPY(buffer, temp_buf, buffer_size);
424 } else {
425 written = -1;
426 }
427 }
428 // Seconds (< 1 minute)
429 else if (nanoseconds < NS_PER_MIN_INT) {
430 double s = (double)nanoseconds / NS_PER_SEC;
431 char temp_buf[UTIL_TIME_TEMP_BUFFER_SIZE];
432 snprintf(temp_buf, sizeof(temp_buf), "%.*fs", actual_decimals, s);
433 strip_trailing_zeros(temp_buf);
434 written = (int)strlen(temp_buf);
435 if (written > 0 && written < (int)buffer_size) {
436 SAFE_STRNCPY(buffer, temp_buf, buffer_size);
437 } else {
438 written = -1;
439 }
440 }
441 // Minutes omit fractions; days omit seconds.
442 else if (nanoseconds < NS_PER_HOUR_INT) {
443 uint64_t total_seconds = nanoseconds / NS_PER_SEC_INT;
444 written = safe_snprintf(buffer, buffer_size, "%llu:%02llu", (unsigned long long)(total_seconds / 60), (unsigned long long)(total_seconds % 60));
445 } else if (nanoseconds >= NS_PER_DAY_INT) {
446 uint64_t total_minutes = nanoseconds / NS_PER_MIN_INT;
447 written = safe_snprintf(buffer, buffer_size, "%llud %llu:%02llu", (unsigned long long)(total_minutes / (24 * 60)), (unsigned long long)((total_minutes / 60) % 24),
448 (unsigned long long)(total_minutes % 60));
449 }
450 // Hours use H:MM:SS.
451 else {
452 uint64_t total_seconds = nanoseconds / NS_PER_SEC_INT;
453 uint64_t hours = total_seconds / 3600;
454 uint64_t remaining = total_seconds % 3600;
455 uint64_t minutes = remaining / 60;
456 uint64_t seconds = remaining % 60;
457
458 written = safe_snprintf(buffer, buffer_size, "%llu:%02llu:%02llu", (unsigned long long)hours, (unsigned long long)minutes, (unsigned long long)seconds);
459 }
460
461 if (written < 0 || (size_t)written >= buffer_size) {
462 return -1;
463 }
464
465 return written;
466}
#define SAFE_STRNCPY(dst, src, size)
#define NS_PER_MIN_INT
Definition time.h:188
#define NS_PER_HOUR_INT
Definition time.h:189
#define NS_PER_MS_INT
Definition time.h:172
#define NS_PER_MS
Definition time.h:163
#define NS_PER_US_INT
Definition time.h:171
#define NS_PER_US
Definition time.h:162
#define NS_PER_DAY_INT
Definition time.h:190
#define UTIL_TIME_TEMP_BUFFER_SIZE
Definition time.c:8

References buffer_size, NS_PER_DAY_INT, NS_PER_HOUR_INT, NS_PER_MIN_INT, NS_PER_MS, NS_PER_MS_INT, NS_PER_SEC, NS_PER_SEC_INT, NS_PER_US, NS_PER_US_INT, SAFE_STRNCPY, and UTIL_TIME_TEMP_BUFFER_SIZE.

Referenced by acip_server_receive_and_dispatch(), asciichat_instr_log_line(), client_video_render_thread(), create_mixed_ascii_frame_for_client(), crypto_init(), crypto_rekey_init(), media_source_seek(), mixer_process_excluding_source(), session_display_write_ascii_frame(), session_render_loop(), time_pretty_now(), timer_stop(), and ui_sync_render().

◆ time_pretty_now()

int time_pretty_now ( int decimals,
char * buffer,
size_t buffer_size )

#include <include/ascii-chat/util/time.h>

Format current monotonic time as pretty duration.

Parameters
decimalsNumber of decimal places (0-9), or -1 for sensible defaults per range
bufferOutput buffer for formatted string
buffer_sizeSize of output buffer
Returns
Number of characters written (excluding null terminator), or -1 on error

Convenience wrapper that calls time_get_ns() and delegates to time_pretty(). Useful for measuring elapsed time since program start in a single call.

Note
Buffer should be at least 32 bytes for all possible outputs
Thread-safe (no global state)

Definition at line 468 of file time.c.

468 {
469 uint64_t ns = time_get_ns();
470 return time_pretty(ns, decimals, buffer, buffer_size);
471}

References buffer_size, and time_pretty().

◆ time_sleep_ns()

void time_sleep_ns ( uint64_t ns)

#include <include/ascii-chat/util/time.h>

Configuration for adaptive sleep behavior.

Runtime state for adaptive sleep

Individual timer record for a named timing operation

Get current monotonic time in nanoseconds

Returns high-precision monotonic time that never goes backwards. Suitable for measuring elapsed time, FPS tracking, and performance metrics.

Returns
Current time in nanoseconds (monotonic, never decreases)

Usage:

uint64_t start = time_get_ns();
// ... do work ...
uint64_t elapsed_ns = time_elapsed_ns(start, time_get_ns());

Get current wall-clock (real) time in nanoseconds

Returns high-precision wall-clock time that can jump forwards or backwards when system time is adjusted. Use this for timestamps, database records, and user-facing time displays.

Returns
Current wall-clock time in nanoseconds (CLOCK_REALTIME)

Note: This time can jump backward if system clock is adjusted. For measuring elapsed time, use time_get_ns() instead.

Sleep for specified nanoseconds

Sleeps the current thread for at least the specified number of nanoseconds. On some systems, actual sleep time may be slightly longer due to scheduler granularity.

Parameters
nsNumber of nanoseconds to sleep

Definition at line 107 of file time.c.

107 {
108 // Use platform abstraction for cross-platform sleep
109 // Convert nanoseconds to microseconds (1 us = 1000 ns)
110 unsigned int usec = (unsigned int)(ns / 1000);
111 if (usec == 0 && ns > 0) {
112 usec = 1; // Minimum 1 microsecond
113 }
114 platform_sleep_us(usec);
115}

◆ time_timespec_to_ns()

uint64_t time_timespec_to_ns ( const struct timespec * ts)

#include <include/ascii-chat/util/time.h>

Convert struct timespec to nanoseconds.

Parameters
tsPointer to timespec structure
Returns
Time in nanoseconds

Useful for converting CLOCK_MONOTONIC or CLOCK_REALTIME readings to nanoseconds.

Definition at line 131 of file time.c.

131 {
132 if (!ts) {
133 SET_ERRNO(ERROR_INVALID_PARAM, "null ts");
134 return 0;
135 }
136 // Use __uint128_t to prevent overflow during multiplication of large time values
137 __uint128_t result = (__uint128_t)ts->tv_sec * NS_PER_SEC_INT;
138 if (result > UINT64_MAX) {
139 SET_ERRNO(ERROR_INVALID_PARAM, "timespec value would overflow");
140 return UINT64_MAX;
141 }
142 return (uint64_t)result + (uint64_t)ts->tv_nsec;
143}

References ERROR_INVALID_PARAM, NS_PER_SEC_INT, and SET_ERRNO.

◆ timer_is_initialized()

bool timer_is_initialized ( void )

#include <include/ascii-chat/util/time.h>

Check if timing system is initialized.

Returns
true if initialized, false otherwise

Definition at line 304 of file time.c.

304 {
305 return lifecycle_is_initialized(&g_timer_manager.lifecycle);
306}

◆ timer_start()

bool timer_start ( const char * name)

#include <include/ascii-chat/util/time.h>

Start a named timer.

Creates a new timer record and stores the start time. If a timer with the same name exists, it will be overwritten.

Parameters
nameTimer name (must be unique, will be copied)
Returns
true on success, false on failure

Definition at line 198 of file time.c.

198 {
199 if (!lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
200 SET_ERRNO(ERROR_INVALID_STATE, "Timer system not initialized");
201 return false;
202 }
203
204 if (!name) {
205 SET_ERRNO(ERROR_INVALID_PARAM, "Timer name is NULL");
206 return false;
207 }
208
209 rwlock_wrlock(&g_timer_manager.rwlock);
210
211 // Check if timer already exists - this is an error, timers must be unique
212 timer_record_t *existing = NULL;
213 HASH_FIND_STR(g_timer_manager.timers, name, existing);
214
215 if (existing) {
216 rwlock_wrunlock(&g_timer_manager.rwlock);
217 SET_ERRNO(ERROR_INVALID_STATE, "Timer '%s' already exists - timers must have unique names", name);
218 return false;
219 }
220
221 // Create new timer record
223 if (!timer) {
224 rwlock_wrunlock(&g_timer_manager.rwlock);
225 SET_ERRNO(ERROR_MEMORY, "Failed to allocate timer record");
226 return false;
227 }
228
229 // Use platform-safe string duplication
230 size_t name_len = strlen(name) + 1;
231 timer->name = SAFE_MALLOC(name_len, char *);
232 if (!timer->name) {
233 SAFE_FREE(timer);
234 rwlock_wrunlock(&g_timer_manager.rwlock);
235 SET_ERRNO(ERROR_MEMORY, "Failed to allocate timer name");
236 return false;
237 }
238 SAFE_STRNCPY(timer->name, name, name_len);
239
240 timer->start_ticks = stm_now();
241
242 // Add to hashtable
243 HASH_ADD_KEYPTR(hh, g_timer_manager.timers, timer->name, strlen(timer->name), timer);
244
245 rwlock_wrunlock(&g_timer_manager.rwlock);
246 return true;
247}
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
@ ERROR_MEMORY
Definition error_codes.h:55
struct timer_record timer_record_t
Individual timer record for a named timing operation.
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

References ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, timer_record::name, SAFE_FREE, SAFE_MALLOC, SAFE_STRNCPY, SET_ERRNO, and timer_record::start_ticks.

◆ timer_stop()

double timer_stop ( const char * name)

#include <include/ascii-chat/util/time.h>

Stop a named timer and return elapsed time.

Looks up the timer by name, calculates elapsed time, logs it, and removes the timer from the hashtable.

Parameters
nameTimer name to stop
Returns
Elapsed time in nanoseconds, or -1.0 if timer not found

Definition at line 249 of file time.c.

249 {
250 if (!lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
251 SET_ERRNO(ERROR_INVALID_STATE, "Timer system not initialized");
252 return -1.0;
253 }
254
255 if (!name) {
256 SET_ERRNO(ERROR_INVALID_PARAM, "Timer name is NULL");
257 return -1.0;
258 }
259
260 rwlock_wrlock(&g_timer_manager.rwlock);
261
262 // Find timer
263 timer_record_t *timer = NULL;
264 HASH_FIND_STR(g_timer_manager.timers, name, timer);
265
266 if (!timer) {
267 rwlock_wrunlock(&g_timer_manager.rwlock);
268 log_dev("Timer '%s' not found (may have already been stopped)", name);
269 return -1.0;
270 }
271
272 // Calculate elapsed time in nanoseconds for maximum precision
273 uint64_t end_ticks = stm_now();
274 uint64_t elapsed_ticks = stm_diff(end_ticks, timer->start_ticks);
275 double elapsed_ns = stm_ns(elapsed_ticks);
276
277 // Format duration for human-readable logging
278 char duration_str[TIME_DURATION_BUFFER_SIZE];
279 time_pretty((uint64_t)elapsed_ns, -1, duration_str, sizeof(duration_str));
280
281 // Log the result (dev level - only shown with --verbose)
282 log_dev("Timer '%s': %s", name, duration_str);
283
284 // Save pointers to free BEFORE removing from hashtable
285 char *timer_name = timer->name;
286
287 // Remove from hashtable (HASH_DEL only removes from hash, doesn't free memory)
288 HASH_DEL(g_timer_manager.timers, timer);
289
290 // Free timer->name first (this was allocated separately)
291 SAFE_FREE(timer_name);
292
293 // Nullify the timer->name field so debug_free doesn't try to access it
294 // when freeing the timer structure itself
295 timer->name = NULL;
296
297 // Free the timer record itself
298 SAFE_FREE(timer);
299
300 rwlock_wrunlock(&g_timer_manager.rwlock);
301 return elapsed_ns; // Return nanoseconds
302}
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575

References ERROR_INVALID_PARAM, ERROR_INVALID_STATE, log_dev, timer_record::name, SAFE_FREE, SET_ERRNO, timer_record::start_ticks, TIME_DURATION_BUFFER_SIZE, and time_pretty().

◆ timer_system_destroy()

void timer_system_destroy ( void )

#include <include/ascii-chat/util/time.h>

Cleanup the timing system.

Frees all timer records and destroys mutex. Should be called at program exit.

Definition at line 171 of file time.c.

171 {
172 if (!lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
173 return;
174 }
175
176 rwlock_wrlock(&g_timer_manager.rwlock);
177
178 // Free all timer records
179 int timer_count = 0;
180 timer_record_t *current, *tmp;
181 HASH_ITER(hh, g_timer_manager.timers, current, tmp) {
182 HASH_DEL(g_timer_manager.timers, current);
183 SAFE_FREE(current->name);
184 SAFE_FREE(current);
185 timer_count++;
186 }
187
188 g_timer_manager.timers = NULL;
189
190 rwlock_wrunlock(&g_timer_manager.rwlock);
191
192 /* Shutdown lifecycle and destroy rwlock together */
193 lifecycle_shutdown(&g_timer_manager.lifecycle);
194
195 log_debug("Timer system cleaned up (freed %d timers)", timer_count);
196}

References log_debug, timer_record::name, and SAFE_FREE.

Referenced by asciichat_shared_destroy().

◆ timer_system_init()

bool timer_system_init ( void )

#include <include/ascii-chat/util/time.h>

Initialize the timing system.

Must be called before using any timer functions. Automatically calls stm_setup() for sokol_time initialization.

Returns
true on success, false on failure

Definition at line 149 of file time.c.

149 {
150 if (lifecycle_is_initialized(&g_timer_manager.lifecycle)) {
151 return true;
152 }
153
154 // Initialize sokol_time
155 stm_setup();
156
157 // Initialize rwlock and lifecycle together
158 g_timer_manager.lifecycle.sync_type = LIFECYCLE_SYNC_RWLOCK;
159 g_timer_manager.lifecycle.sync.rwlock = &g_timer_manager.rwlock;
160 if (!lifecycle_init(&g_timer_manager.lifecycle, "timer_manager")) {
161 SET_ERRNO(ERROR_PLATFORM_INIT, "Failed to initialize timer system (already initialized by another thread)");
162 return true; // Another thread already initialized it
163 }
164
165 g_timer_manager.timers = NULL;
166
167 log_dev("Timer system initialized");
168 return true;
169}
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59

References ERROR_PLATFORM_INIT, log_dev, and SET_ERRNO.

Referenced by asciichat_shared_init().