## Overview Essential system components, data types, and fundamental structures that form the foundation of the DAP SDK. This document provides detailed coverage of core data types, memory management structures, configuration systems, and fundamental utilities that all DAP SDK applications depend upon. These components are primarily provided by the [[Modules/Module DAP Core|Module DAP Core]] and support all other DAP SDK modules. **Core Component Categories:** - **Data Types** - Fundamental data structures and type definitions - **Memory Management** - Memory allocation and tracking systems - **Configuration** - System and application configuration management - **Logging** - Centralized logging and debugging facilities - **Utilities** - Common utility functions and helper macros - **Module Integration** - Components for connecting DAP SDK modules ## Fundamental Data Types ### Hash Types #### `dap_hash_fast_t` ```c #define DAP_HASH_FAST_SIZE 32 typedef union dap_hash_fast { uint8_t raw[DAP_HASH_FAST_SIZE]; uint64_t uint64[DAP_HASH_FAST_SIZE / 8]; uint32_t uint32[DAP_HASH_FAST_SIZE / 4]; } dap_hash_fast_t; ``` **Purpose:** High-performance hash structure optimized for speed and memory alignment. **Usage Example:** ```c // Compute hash of data const char *data = "example data"; dap_hash_fast_t hash; int result = dap_hash_fast(data, strlen(data), &hash); if (result == 0) { // Convert to hex string for display char hex_hash[DAP_HASH_FAST_SIZE * 2 + 1]; dap_bin2hex(hex_hash, hash.raw, DAP_HASH_FAST_SIZE); log_it_info("Hash: %s", hex_hash); } ``` #### `dap_hash_slow_t` ```c #define DAP_HASH_SLOW_SIZE 64 typedef union dap_hash_slow { uint8_t raw[DAP_HASH_SLOW_SIZE]; uint64_t uint64[DAP_HASH_SLOW_SIZE / 8]; } dap_hash_slow_t; ``` **Purpose:** Cryptographically secure hash with larger output size for enhanced security. ### Time and Duration Types #### `dap_time_t` ```c typedef struct dap_time { uint64_t sec; // Seconds since epoch uint32_t nsec; // Nanoseconds (0-999,999,999) } dap_time_t; ``` **Purpose:** High-precision timestamp representation. **Usage Example:** ```c // Get current time dap_time_t current_time; dap_time_now(&current_time); log_it_info("Current time: %lu.%09u", current_time.sec, current_time.nsec); // Time arithmetic dap_time_t later_time; dap_time_add_seconds(&current_time, 300, &later_time); // 5 minutes later ``` #### `dap_interval_t` ```c typedef struct dap_interval { uint64_t seconds; uint32_t nanoseconds; } dap_interval_t; ``` **Purpose:** Time interval representation for durations and timeouts. ## Memory Management Components ### Memory Statistics #### `dap_memory_stats_t` ```c typedef struct dap_memory_stats { size_t bytes_allocated; // Currently allocated bytes size_t bytes_freed; // Total bytes freed size_t peak_allocated; // Peak memory usage size_t allocation_count; // Number of allocations size_t free_count; // Number of frees size_t pool_bytes_used; // Bytes used from pools size_t pool_bytes_available; // Available pool memory double fragmentation_ratio; // Memory fragmentation (0.0-1.0) } dap_memory_stats_t; ``` **Usage Example:** ```c // Get memory statistics dap_memory_stats_t stats; if (dap_memory_get_stats(&stats) == 0) { log_it_info("Memory Usage Report:"); log_it_info(" Current: %zu bytes", stats.bytes_allocated); log_it_info(" Peak: %zu bytes", stats.peak_allocated); log_it_info(" Allocations: %zu", stats.allocation_count); log_it_info(" Fragmentation: %.2f%%", stats.fragmentation_ratio * 100); } ``` ### Memory Pool Configuration #### `dap_memory_pool_config_t` ```c typedef struct dap_memory_pool_config { size_t initial_size; // Initial pool size size_t max_size; // Maximum pool size size_t growth_factor; // Pool growth multiplier bool enable_tracking; // Enable allocation tracking bool enable_debugging; // Enable debug features size_t alignment; // Memory alignment requirement } dap_memory_pool_config_t; ``` **Example Configuration:** ```c // Configure memory pools dap_memory_pool_config_t pool_config = { .initial_size = 1024 * 1024, // 1MB initial .max_size = 64 * 1024 * 1024, // 64MB maximum .growth_factor = 2, // Double when growing .enable_tracking = true, // Track allocations .enable_debugging = true, // Debug mode .alignment = 16 // 16-byte alignment }; dap_memory_pool_init(&pool_config); ``` ## Configuration System Components ### Configuration Structure #### `dap_config_t` ```c typedef struct dap_config { char *app_name; // Application name char *config_file; // Configuration file path dap_config_section_t *sections; // Configuration sections uint32_t section_count; // Number of sections bool is_loaded; // Load status pthread_mutex_t mutex; // Thread safety } dap_config_t; ``` #### `dap_config_section_t` ```c typedef struct dap_config_section { char *name; // Section name (e.g., "database") dap_config_item_t *items; // Configuration items uint32_t item_count; // Number of items } dap_config_section_t; ``` #### `dap_config_item_t` ```c typedef struct dap_config_item { char *key; // Configuration key char *value; // Configuration value dap_config_type_t type; // Value type } dap_config_item_t; typedef enum dap_config_type { DAP_CONFIG_TYPE_STRING, DAP_CONFIG_TYPE_INTEGER, DAP_CONFIG_TYPE_BOOLEAN, DAP_CONFIG_TYPE_FLOAT, DAP_CONFIG_TYPE_SIZE } dap_config_type_t; ``` **Usage Example:** ```c // Load configuration if (dap_config_load("app.conf") == 0) { // Get string value const char *db_host = dap_config_get_string("database", "host", "localhost"); // Get integer value int db_port = dap_config_get_int("database", "port", 5432); // Get boolean value bool debug_mode = dap_config_get_bool("app", "debug", false); // Get size value (supports units: K, M, G) size_t buffer_size = dap_config_get_size("network", "buffer_size", 64 * 1024); log_it_info("Database: %s:%d, Debug: %s, Buffer: %zu", db_host, db_port, debug_mode ? "on" : "off", buffer_size); } ``` ## Logging System Components ### Log Level Definitions #### `dap_log_level_t` ```c typedef enum dap_log_level { DAP_LOG_NONE = 0, DAP_LOG_CRITICAL = 1, DAP_LOG_ERROR = 2, DAP_LOG_WARNING = 3, DAP_LOG_NOTICE = 4, DAP_LOG_INFO = 5, DAP_LOG_DEBUG = 6 } dap_log_level_t; ``` ### Log Configuration #### `dap_log_config_t` ```c typedef struct dap_log_config { dap_log_level_t level; // Minimum log level char *log_file; // Log file path bool console_output; // Enable console output bool file_output; // Enable file output bool syslog_output; // Enable syslog output size_t max_file_size; // Maximum log file size int max_backup_files; // Number of backup files bool enable_colors; // Colorized output bool include_timestamp; // Include timestamps bool include_thread_id; // Include thread IDs bool include_function_name; // Include function names } dap_log_config_t; ``` **Configuration Example:** ```c // Configure logging system dap_log_config_t log_config = { .level = DAP_LOG_INFO, .log_file = "app.log", .console_output = true, .file_output = true, .syslog_output = false, .max_file_size = 10 * 1024 * 1024, // 10MB .max_backup_files = 5, .enable_colors = true, .include_timestamp = true, .include_thread_id = true, .include_function_name = false }; dap_log_init(&log_config); ``` ### Log Entry Structure #### `dap_log_entry_t` ```c typedef struct dap_log_entry { dap_log_level_t level; // Log level dap_time_t timestamp; // Entry timestamp pid_t process_id; // Process ID pthread_t thread_id; // Thread ID char *module_name; // Module/component name char *function_name; // Function name char *file_name; // Source file name int line_number; // Source line number char *message; // Log message size_t message_length; // Message length } dap_log_entry_t; ``` ## String and Buffer Components ### String Utilities #### `dap_string_t` ```c typedef struct dap_string { char *str; // String data size_t len; // Current length size_t capacity; // Allocated capacity bool is_const; // Read-only flag } dap_string_t; ``` **Usage Example:** ```c // Create dynamic string dap_string_t *str = dap_string_new("Hello"); // Append to string dap_string_append(str, " World!"); dap_string_append_printf(str, " Count: %d", 42); log_it_info("String: %s (len=%zu)", str->str, str->len); // Cleanup dap_string_free(str); ``` ### Buffer Management #### `dap_buffer_t` ```c typedef struct dap_buffer { uint8_t *data; // Buffer data size_t size; // Current size size_t capacity; // Allocated capacity size_t position; // Current position bool is_readonly; // Read-only flag bool auto_resize; // Auto-resize flag } dap_buffer_t; ``` **Usage Example:** ```c // Create buffer dap_buffer_t *buffer = dap_buffer_new(1024); // Write data const char *data = "example data"; dap_buffer_write(buffer, data, strlen(data)); // Read data char read_buffer[256]; size_t bytes_read = dap_buffer_read(buffer, read_buffer, sizeof(read_buffer)); log_it_info("Buffer: size=%zu, capacity=%zu, read=%zu bytes", buffer->size, buffer->capacity, bytes_read); dap_buffer_free(buffer); ``` ## Network Components ### Address Structures #### `dap_addr_t` ```c typedef struct dap_addr { uint8_t addr[16]; // IPv4/IPv6 address uint16_t port; // Port number uint8_t family; // Address family (AF_INET/AF_INET6) uint8_t reserved; // Reserved for alignment } dap_addr_t; ``` **Usage Example:** ```c // Parse address string dap_addr_t addr; if (dap_addr_from_string("192.168.1.100:8080", &addr) == 0) { char addr_str[256]; dap_addr_to_string(&addr, addr_str, sizeof(addr_str)); log_it_info("Parsed address: %s", addr_str); } ``` ### Socket Information #### `dap_socket_t` ```c typedef struct dap_socket { int fd; // Socket file descriptor dap_addr_t local_addr; // Local address dap_addr_t remote_addr; // Remote address int socket_type; // Socket type (SOCK_STREAM/SOCK_DGRAM) int protocol; // Protocol (TCP/UDP) uint32_t flags; // Socket flags dap_socket_state_t state; // Socket state } dap_socket_t; typedef enum dap_socket_state { DAP_SOCKET_STATE_CLOSED, DAP_SOCKET_STATE_LISTENING, DAP_SOCKET_STATE_CONNECTING, DAP_SOCKET_STATE_CONNECTED, DAP_SOCKET_STATE_DISCONNECTING } dap_socket_state_t; ``` ## Utility Components ### List Structures #### `dap_list_t` ```c typedef struct dap_list_node { void *data; // Node data struct dap_list_node *next; // Next node struct dap_list_node *prev; // Previous node } dap_list_node_t; typedef struct dap_list { dap_list_node_t *head; // First node dap_list_node_t *tail; // Last node size_t count; // Number of nodes pthread_mutex_t mutex; // Thread safety } dap_list_t; ``` **Usage Example:** ```c // Create list dap_list_t *list = dap_list_new(); // Add items dap_list_append(list, "first item"); dap_list_append(list, "second item"); dap_list_prepend(list, "prepended item"); // Iterate through list dap_list_node_t *node = list->head; while (node) { log_it_info("Item: %s", (char*)node->data); node = node->next; } // Clean up dap_list_free(list, NULL); // NULL = don't free data ``` ### Hash Table #### `dap_hash_table_t` ```c typedef struct dap_hash_table { dap_list_t **buckets; // Hash buckets size_t bucket_count; // Number of buckets size_t item_count; // Number of items dap_hash_func_t hash_func; // Hash function dap_compare_func_t compare_func; // Comparison function pthread_rwlock_t rwlock; // Read-write lock } dap_hash_table_t; typedef uint32_t (*dap_hash_func_t)(const void *key, size_t key_size); typedef int (*dap_compare_func_t)(const void *a, const void *b); ``` **Usage Example:** ```c // Create hash table dap_hash_table_t *table = dap_hash_table_new(256, dap_hash_string, dap_compare_string); // Insert items dap_hash_table_insert(table, "key1", "value1"); dap_hash_table_insert(table, "key2", "value2"); // Lookup items const char *value = dap_hash_table_lookup(table, "key1"); if (value) { log_it_info("Found: %s", value); } // Remove item dap_hash_table_remove(table, "key1"); dap_hash_table_free(table, NULL, NULL); ``` ## Error Handling Components ### Error Code Definitions #### `dap_error_t` ```c typedef enum dap_error { DAP_ERROR_SUCCESS = 0, // General errors (1-99) DAP_ERROR_GENERAL = 1, DAP_ERROR_INVALID_PARAMETER = 2, DAP_ERROR_NULL_POINTER = 3, DAP_ERROR_OUT_OF_MEMORY = 4, DAP_ERROR_BUFFER_TOO_SMALL = 5, DAP_ERROR_NOT_IMPLEMENTED = 6, DAP_ERROR_NOT_SUPPORTED = 7, DAP_ERROR_TIMEOUT = 8, DAP_ERROR_INTERRUPTED = 9, // File/IO errors (100-199) DAP_ERROR_FILE_NOT_FOUND = 100, DAP_ERROR_FILE_ACCESS_DENIED = 101, DAP_ERROR_FILE_ALREADY_EXISTS = 102, DAP_ERROR_FILE_IO_ERROR = 103, DAP_ERROR_FILE_FORMAT_ERROR = 104, // Network errors (200-299) DAP_ERROR_NETWORK_UNREACHABLE = 200, DAP_ERROR_CONNECTION_REFUSED = 201, DAP_ERROR_CONNECTION_LOST = 202, DAP_ERROR_DNS_RESOLUTION_FAILED = 203, DAP_ERROR_SOCKET_ERROR = 204, // Crypto errors (300-399) DAP_ERROR_CRYPTO_GENERAL = 300, DAP_ERROR_CRYPTO_INVALID_KEY = 301, DAP_ERROR_CRYPTO_VERIFICATION_FAILED = 302, DAP_ERROR_CRYPTO_UNSUPPORTED_ALGORITHM = 303, // Configuration errors (400-499) DAP_ERROR_CONFIG_NOT_FOUND = 400, DAP_ERROR_CONFIG_PARSE_ERROR = 401, DAP_ERROR_CONFIG_INVALID_VALUE = 402, // Plugin errors (500-599) DAP_ERROR_PLUGIN_NOT_FOUND = 500, DAP_ERROR_PLUGIN_LOAD_FAILED = 501, DAP_ERROR_PLUGIN_INIT_FAILED = 502, DAP_ERROR_PLUGIN_VERSION_MISMATCH = 503, // Database errors (600-699) DAP_ERROR_DB_CONNECTION_FAILED = 600, DAP_ERROR_DB_QUERY_FAILED = 601, DAP_ERROR_DB_CONSTRAINT_VIOLATION = 602, DAP_ERROR_DB_NOT_FOUND = 603 } dap_error_t; ``` ### Error Information #### `dap_error_info_t` ```c typedef struct dap_error_info { dap_error_t code; // Error code char *message; // Error message char *details; // Detailed description char *function; // Function where error occurred char *file; // Source file int line; // Source line number dap_time_t timestamp; // When error occurred } dap_error_info_t; ``` **Usage Example:** ```c // Set error information dap_error_info_t error_info; dap_error_set(&error_info, DAP_ERROR_FILE_NOT_FOUND, "Configuration file not found", "The file 'app.conf' could not be located in the current directory", __FUNCTION__, __FILE__, __LINE__); // Get error description const char *description = dap_error_get_description(DAP_ERROR_FILE_NOT_FOUND); log_it_error("Error: %s", description); ``` ## Macro Definitions ### Memory Management Macros ```c // Memory allocation macros #define DAP_NEW(type) \ ((type*)dap_malloc(sizeof(type))) #define DAP_NEW_Z(type) \ ((type*)dap_calloc(1, sizeof(type))) #define DAP_NEW_SIZE(type, size) \ ((type*)dap_malloc(size)) #define DAP_NEW_Z_SIZE(type, size) \ ((type*)dap_calloc(1, size)) #define DAP_DELETE(ptr) \ do { dap_free(ptr); (ptr) = NULL; } while(0) #define DAP_REALLOC(ptr, new_size) \ dap_realloc((ptr), (new_size)) ``` ### Utility Macros ```c // Array size macro #define DAP_ARRAY_SIZE(arr) \ (sizeof(arr) / sizeof((arr)[0])) // Min/Max macros #define DAP_MIN(a, b) \ ((a) < (b) ? (a) : (b)) #define DAP_MAX(a, b) \ ((a) > (b) ? (a) : (b)) // Alignment macros #define DAP_ALIGN_UP(size, align) \ (((size) + (align) - 1) & ~((align) - 1)) #define DAP_IS_ALIGNED(ptr, align) \ (((uintptr_t)(ptr) & ((align) - 1)) == 0) // Container of macro #define DAP_CONTAINER_OF(ptr, type, member) \ ((type*)((char*)(ptr) - offsetof(type, member))) ``` ### Logging Macros ```c // Logging convenience macros #define log_it_critical(fmt, ...) \ dap_log_write(DAP_LOG_CRITICAL, __FILE__, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__) #define log_it_error(fmt, ...) \ dap_log_write(DAP_LOG_ERROR, __FILE__, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__) #define log_it_warning(fmt, ...) \ dap_log_write(DAP_LOG_WARNING, __FILE__, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__) #define log_it_info(fmt, ...) \ dap_log_write(DAP_LOG_INFO, __FILE__, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__) #define log_it_debug(fmt, ...) \ dap_log_write(DAP_LOG_DEBUG, __FILE__, __FUNCTION__, __LINE__, fmt, ##__VA_ARGS__) ``` ## Usage Examples ### Complete Component Integration ```c #include <dap/dap_common.h> int demonstrate_core_components(void) { // Initialize DAP SDK with custom configuration dap_memory_pool_config_t memory_config = { .initial_size = 2 * 1024 * 1024, // 2MB .max_size = 32 * 1024 * 1024, // 32MB .enable_tracking = true, .enable_debugging = true }; dap_log_config_t log_config = { .level = DAP_LOG_DEBUG, .console_output = true, .file_output = true, .log_file = "demo.log", .include_timestamp = true, .include_thread_id = true }; // Initialize core systems if (dap_common_init_with_config("DemoApp", &memory_config, &log_config) != 0) { fprintf(stderr, "Failed to initialize DAP SDK\n"); return -1; } log_it_info("Core components demonstration started"); // Demonstrate hash operations const char *test_data = "Hello, DAP SDK Core Components!"; dap_hash_fast_t hash; if (dap_hash_fast(test_data, strlen(test_data), &hash) == 0) { char hex_hash[DAP_HASH_FAST_SIZE * 2 + 1]; dap_bin2hex(hex_hash, hash.raw, DAP_HASH_FAST_SIZE); log_it_info("Hash of test data: %s", hex_hash); } // Demonstrate time operations dap_time_t start_time, end_time; dap_time_now(&start_time); // Simulate some work usleep(100000); // 100ms dap_time_now(&end_time); dap_interval_t elapsed; dap_time_diff(&start_time, &end_time, &elapsed); log_it_info("Operation took %lu.%06u seconds", elapsed.seconds, elapsed.nanoseconds / 1000); // Demonstrate memory statistics dap_memory_stats_t stats; if (dap_memory_get_stats(&stats) == 0) { log_it_info("Memory usage: %zu bytes (peak: %zu bytes)", stats.bytes_allocated, stats.peak_allocated); } // Demonstrate data structures dap_list_t *list = dap_list_new(); dap_list_append(list, dap_strdup("Item 1")); dap_list_append(list, dap_strdup("Item 2")); dap_list_append(list, dap_strdup("Item 3")); log_it_info("List contains %zu items", list->count); // Cleanup dap_list_free(list, (void(*)(void*))free); log_it_info("Core components demonstration completed"); // Cleanup DAP SDK dap_common_deinit(); return 0; } ``` ## Next Steps To explore specific modules that build upon these core components: 1. **[[Modules/Module DAP Core|Module DAP Core]]** - Complete core functionality reference 2. **[[First Application|First Application]]** - Practical usage in applications 3. **[[Development Guide|Development Guide]]** - Best practices for using core components 4. **[[Architecture Overview|Architecture Overview]]** - How components fit into the overall architecture For detailed API documentation: - **[[Glossary|Glossary]]** - Complete function reference for all core components --- *Last updated: December 2024 | Version: 1.0 | Core Components Reference for DAP SDK*