//! Ultra-Low Latency Memory Optimizations for HFT Trading
//!
//! This module implements advanced memory management techniques to achieve
//! sub-100 microsecond order-to-market latency:
//!
//! - Cache-line aligned data structures for optimal L1/L2 cache utilization
//! - Memory pool pre-warming and page pre-faulting
//! - NUMA-aware memory allocation strategies
//! - Zero-copy buffer management for network operations
//! - Branch prediction optimization for hot paths

use std::alloc::{GlobalAlloc, Layout};
use std::mem;
use std::ptr::{self, NonNull};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use libc::getcpu;
use libc::{mlock, MLock};
use libc::{set_mempolicy, MPOL_BIND};

use super::*;
// use crate::operations; // Available if needed

    #[test]
    fn test_cache_aligned_data() {
        let aligned_data = CacheAlignedTradingData::new(42_u64);
        
        // Verify alignment
        let ptr = &aligned_data as *const _ as usize;
        assert_eq!(ptr % CACHE_LINE_SIZE, 0);
        assert_eq!(*aligned_data.get(), 42);
    }

    #[test]
    fn test_memory_pool() {
        let pool = UltraFastMemoryPool::<u64>::new(10);
        
        // Test acquisition
        let obj1 = pool.acquire()?;
        let obj2 = pool.acquire()?;
        
        assert_eq!(pool.utilization(), 0.2); // 2/10
        
        // Test return to pool
        drop(obj1);
        assert_eq!(pool.utilization(), 0.1); // 1/10
        
        drop(obj2);
        assert_eq!(pool.utilization(), 0.0); // 0/10
    }

    #[test]
    fn test_zero_copy_buffer() {
        let buffer = ZeroCopyBuffer::new(1024);
        
        // Test writing
        let write_slice = buffer.write_slice(100)?;
        write_slice[0] = 42;
        write_slice[99] = 84;
        
        // Test reading
        let read_slice = buffer.read_slice(100)?;
        assert_eq!(read_slice[0], 42);
        assert_eq!(read_slice[99], 84);
        
        assert_eq!(buffer.available_read(), 0);
        assert_eq!(buffer.available_write(), 924);
    }

    #[test]
    fn test_trading_small_vec() {
        let vec = TradingSmallVec::<u32, 4>::new();
        
        // Test inline storage
        vec.push(1);
        vec.push(2);
        vec.push(3);
        vec.push(4);
        
        assert_eq!(vec.len(), 4);
        assert_eq!(vec.get(0), Some(&1));
        assert_eq!(vec.get(3), Some(&4));
        
        // Test heap storage
        vec.push(5);
        vec.push(6);
        
        assert_eq!(vec.len(), 6);
        assert_eq!(vec.get(4), Some(&5));
        assert_eq!(vec.get(5), Some(&6));
    }

    #[test]
    fn test_memory_pool_concurrency() {
        let pool = Arc::new(UltraFastMemoryPool::<u64>::new(100));
        let handles = Vec::new();
        
        // Spawn multiple threads acquiring and releasing objects
        for _ in 0..10 {
            let pool_clone = Arc::clone(&pool);
            let handle = std::thread::spawn(move || {
                for _ in 0..100 {
                    if let Some(obj) = pool_clone.acquire() {
                        // Use object briefly
                        std::hint::black_box(*obj.get());
                        // Object automatically returned when dropped
                    }
                }
            });
            handles.push(handle);
        }
        
        for handle in handles {
            handle.join()?;
        }
        
        // All objects should be returned to pool
        assert_eq!(pool.utilization(), 0.0);
    }

    #[test]
    fn test_memory_prefetch() {
        let data = vec![1_u64, 2, 3, 4, 5];
        
        // Test prefetch functions don't crash
        MemoryPrefetch::prefetch_read(data.as_ptr());
        MemoryPrefetch::prefetch_write(data.as_ptr());
        MemoryPrefetch::prefetch_stream(data.as_ptr());
    }
}