utils.c
Overview
The utils.c file provides a collection of utility functions primarily for time measurement, colored console output initialization, JSON test data handling, and JSON comparison in a testing context. It facilitates precise time retrieval and formatting, reading JSON content from files, and comparing JSON strings while ignoring whitespace differences. The file also manages terminal color codes for console output, adapting to different operating systems (Windows and POSIX). These utilities are designed to support test execution and reporting.
Functions and Details
void utils_initialize(void)
Initializes console color codes for output formatting. On Windows, it enables virtual terminal processing to support ANSI escape codes. On other platforms, it simply assigns ANSI color codes.
Parameters: None
Returns: None
Usage: Called once before printing colored output to set the global color code strings
GREEN,RED, andRESET.Platform Specifics: Uses Windows API functions
GetStdHandle,GetConsoleMode, andSetConsoleModefor Windows; assigns ANSI codes directly on other platforms.
long long utils_get_time(void)
Retrieves the current monotonic time in nanoseconds. This provides a high-resolution time useful for performance measurement.
Parameters: None
Returns:
long longrepresenting current time in nanoseconds.Usage: Used to capture start and end timestamps for timing operations.
Platform Specifics: Uses
QueryPerformanceCounterandQueryPerformanceFrequencyon Windows; usesclock_gettimewithCLOCK_MONOTONICon POSIX systems.
void utils_print_time_diff(long long start_ns, long long end_ns)
Prints the difference between two timestamps in a formatted string representing hours, minutes, seconds, and milliseconds.
Parameters:
start_ns: Start time in nanoseconds.end_ns: End time in nanoseconds.
Returns: None
Usage: To display elapsed time in human-readable format after measuring execution duration.
Implementation Details: Converts nanoseconds into hours, minutes, seconds, and milliseconds by successive division and modulo based on predefined time unit constants.
char *utils_get_test_json_data(const char *filename)
Reads the contents of a JSON file and returns it as a null-terminated string.
Parameters:
filename: Path to the JSON file to read.
Returns: Pointer to dynamically allocated string containing file contents, or
NULLif file cannot be opened or read.Usage: Used to load JSON test data for comparisons or parsing.
Implementation Details: Opens the file, determines its size, allocates memory, reads the file content, null-terminates the string, and closes the file.
bool utils_test_json_equal(const char *a, const char *b)
Compares two JSON strings for equality ignoring whitespace differences.
Parameters:
a: First JSON string.b: Second JSON string.
Returns:
trueif JSON strings are equal ignoring whitespace; otherwisefalse.Usage: To assert JSON equality in tests where formatting may differ.
Implementation Details:
Iterates through both strings simultaneously.
Skips whitespace using the macro/function
NEXT_TOKEN(assumed to advance pointer past whitespace).Reports the first byte offset difference and prints a snippet of differing context around that offset.
Error Handling: Returns
falseif either input isNULL.Note: Relies on
isspacefor whitespace detection and uses stderr for mismatch reporting.
void utils_output(const char *s)
Prints a string s enclosed in delimiter lines for clear separation in console output.
Parameters:
s: The string to output.
Returns: None
Usage: For visually distinct sections in test logs or console output.
Important Implementation Details and Algorithms
Time Measurement Constants: Defined for conversions between nanoseconds, milliseconds, seconds, minutes, and hours. These constants ensure accurate time unit conversions.
Platform Abstraction: Uses preprocessor directives (
#ifdef _WIN32) to handle differences between Windows and POSIX APIs for timing and console behavior.Whitespace-Insensitive JSON Comparison: The
utils_test_json_equalfunction performs a character-by-character comparison ignoring whitespace, useful for comparing JSON test outputs that may differ in formatting but are semantically equal.Memory Management:
utils_get_test_json_dataallocates memory withcalloc; caller must free the returned pointer after use to avoid memory leaks.
Interaction with Other Parts of the System
Includes
"../test/utils.h"header, indicating it provides implementations for declared utility functions used primarily in test code.Functions like
utils_get_test_json_dataandutils_test_json_equalare designed to support JSON-based test scenarios, likely interacting with test frameworks or JSON parsing components.Time-related functions are used to measure and report execution durations during tests or benchmarks.
Color initialization supports enhanced console output formatting for test results or logs.
utils_outputis a generic output helper for formatted console prints, useful across multiple testing or logging contexts.
Visual Diagram of Function Relationships
flowchart TD
A[utils_initialize] -->|sets| B[GREEN, RED, RESET]
C[utils_get_time] --> D[Returns nanoseconds timestamp]
E[utils_print_time_diff] --> C
E --> F[Formats time difference]
G[utils_get_test_json_data] --> H[Reads JSON file content]
I[utils_test_json_equal] --> J[Compares JSON ignoring whitespace]
I -->|on mismatch| K[Prints context]
L[utils_output] --> M[Prints string with delimiters]
This diagram illustrates the main functions in utils.c and their primary functionality or flow relationships, providing a clear overview of the utility operations within this file.