#include "secure_mem.h"
#include <cstring>

namespace fetchml::common {

// Constant-time memory comparison
// Returns 0 if equal, non-zero otherwise
int secure_memcmp(const void* a, const void* b, size_t len) {
    const volatile unsigned char* pa = (const volatile unsigned char*)a;
    const volatile unsigned char* pb = (const volatile unsigned char*)b;
    volatile unsigned char result = 0;
    
    for (size_t i = 0; i < len; i++) {
        result |= pa[i] ^ pb[i];
    }
    
    return result;
}

// Secure memory clear using volatile to prevent optimization
void secure_memzero(void* ptr, size_t len) {
    volatile unsigned char* p = (volatile unsigned char*)ptr;
    while (len--) {
        *p++ = 0;
    }
}

// Safe strncpy - always null terminates, returns -1 on truncation
int safe_strncpy(char* dst, const char* src, size_t dst_size) {
    if (!dst || !src || dst_size == 0) {
        return -1;
    }
    
    size_t i;
    for (i = 0; i < dst_size - 1 && src[i] != '\0'; i++) {
        dst[i] = src[i];
    }
    dst[i] = '\0';
    
    // Check if truncation occurred
    if (src[i] != '\0') {
        return -1;  // src was longer than dst_size - 1
    }
    
    return 0;
}

} // namespace fetchml::common
