rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Advanced memory management for high-performance tensor operations
//! 高性能テンソル演算のための高度なメモリ管理

use super::Tensor;
use crate::error::{RusTorchError, RusTorchResult};
type ParallelResult<T> = RusTorchResult<T>;
use num_traits::Float;
use std::alloc::{alloc_zeroed, dealloc, Layout};
use std::collections::{HashMap, VecDeque};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

/// Advanced memory alignment for different architectures
/// 異なるアーキテクチャ用の高度なメモリアライメント
/// Cache line size for optimal memory alignment
/// 最適なメモリアライメント用のキャッシュラインサイズ
pub const CACHE_LINE_SIZE: usize = 64;
/// Standard page size
/// 標準ページサイズ
pub const PAGE_SIZE: usize = 4096;
/// Huge page size for large memory allocations
/// 大容量メモリ割り当て用のヒュージページサイズ
pub const HUGE_PAGE_SIZE: usize = 2 * 1024 * 1024; // 2MB

/// Memory allocation strategy
/// メモリ割り当て戦略
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AllocationStrategy {
    /// Standard heap allocation
    /// 標準ヒープ割り当て
    Standard,
    /// Cache-aligned allocation
    /// キャッシュアライメント割り当て
    CacheAligned,
    /// Page-aligned allocation
    /// ページアライメント割り当て
    PageAligned,
    /// Huge page allocation for large tensors
    /// 大きなテンソル用のヒュージページ割り当て
    HugePage,
    /// Memory pool allocation
    /// メモリプール割り当て
    Pooled,
    /// NUMA-aware allocation
    /// NUMA対応割り当て
    NumaAware,
}

/// Memory pool configuration
/// メモリプール設定
#[derive(Debug, Clone)]
pub struct PoolConfig {
    /// Initial size of memory pool in bytes
    /// メモリプールの初期サイズ(バイト)
    pub initial_size: usize,
    /// Maximum size of memory pool in bytes
    /// メモリプールの最大サイズ(バイト)
    pub max_size: usize,
    /// Growth factor when expanding pool
    /// プール拡張時の成長率
    pub growth_factor: f32,
    /// Threshold for shrinking pool
    /// プール縮小しきい値
    pub shrink_threshold: f32,
    /// Memory alignment requirement
    /// メモリアライメント要件
    pub alignment: usize,
    /// Enable memory prefaulting
    /// メモリプリフォルトを有効にする
    pub enable_prefaulting: bool,
    /// Enable huge page support
    /// ヒュージページサポートを有効にする
    pub enable_huge_pages: bool,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            initial_size: 64 * 1024 * 1024, // 64MB
            max_size: 1024 * 1024 * 1024,   // 1GB
            growth_factor: 1.5,
            shrink_threshold: 0.25,
            alignment: CACHE_LINE_SIZE,
            enable_prefaulting: true,
            enable_huge_pages: false,
        }
    }
}

/// Memory block metadata
/// メモリブロックメタデータ
#[derive(Debug)]
struct MemoryBlock {
    ptr: NonNull<u8>,
    size: usize,
    alignment: usize,
    last_accessed: Instant,
    access_count: u64,
    is_huge_page: bool,
}

impl MemoryBlock {
    fn new(size: usize, alignment: usize, is_huge_page: bool) -> ParallelResult<Self> {
        let layout = Layout::from_size_align(size, alignment)
            .map_err(|e| RusTorchError::memory(format!("Invalid layout: {}", e)))?;

        let ptr = unsafe {
            let raw_ptr = if is_huge_page {
                Self::alloc_huge_page(size, alignment)?
            } else {
                alloc_zeroed(layout)
            };

            if raw_ptr.is_null() {
                return Err(RusTorchError::memory("Allocation failed"));
            }

            NonNull::new_unchecked(raw_ptr)
        };

        let now = Instant::now();
        Ok(Self {
            ptr,
            size,
            alignment,
            last_accessed: now,
            access_count: 0,
            is_huge_page,
        })
    }

    #[cfg(target_os = "linux")]
    fn alloc_huge_page(size: usize, alignment: usize) -> ParallelResult<*mut u8> {
        use std::fs::OpenOptions;
        use std::os::unix::io::AsRawFd;

        // Try to allocate using mmap with MAP_HUGETLB
        // MAP_HUGETLBを使用してmmapで割り当てを試行
        let fd = OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/zero")
            .map_err(|e| RusTorchError::IO(e))?;

        unsafe {
            let ptr = libc::mmap(
                std::ptr::null_mut(),
                size,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_HUGETLB,
                fd.as_raw_fd(),
                0,
            );

            if ptr == libc::MAP_FAILED {
                // Fallback to regular allocation
                // 通常の割り当てにフォールバック
                let layout = Layout::from_size_align(size, alignment)
                    .map_err(|e| RusTorchError::memory(format!("Invalid layout: {}", e)))?;
                Ok(alloc_zeroed(layout))
            } else {
                Ok(ptr as *mut u8)
            }
        }
    }

    #[cfg(not(target_os = "linux"))]
    fn alloc_huge_page(size: usize, alignment: usize) -> ParallelResult<*mut u8> {
        // Fallback to regular allocation on non-Linux systems
        // Linux以外のシステムでは通常の割り当てにフォールバック
        let layout = Layout::from_size_align(size, alignment)
            .map_err(|e| RusTorchError::memory(format!("Invalid layout: {}", e)))?;
        Ok(unsafe { alloc_zeroed(layout) })
    }

    fn update_access(&mut self) {
        self.last_accessed = Instant::now();
        self.access_count += 1;
    }

    fn idle_time(&self) -> Duration {
        self.last_accessed.elapsed()
    }
}

impl Drop for MemoryBlock {
    fn drop(&mut self) {
        unsafe {
            if self.is_huge_page {
                #[cfg(target_os = "linux")]
                {
                    libc::munmap(self.ptr.as_ptr() as *mut libc::c_void, self.size);
                }
                #[cfg(not(target_os = "linux"))]
                {
                    let layout = Layout::from_size_align_unchecked(self.size, self.alignment);
                    dealloc(self.ptr.as_ptr(), layout);
                }
            } else {
                let layout = Layout::from_size_align_unchecked(self.size, self.alignment);
                dealloc(self.ptr.as_ptr(), layout);
            }
        }
    }
}

/// Advanced memory pool with intelligent management
/// インテリジェント管理を備えた高度なメモリプール
pub struct AdvancedMemoryPool {
    config: PoolConfig,
    free_blocks: RwLock<HashMap<usize, VecDeque<MemoryBlock>>>,
    allocated_blocks: RwLock<HashMap<*mut u8, MemoryBlock>>,
    total_allocated: Arc<Mutex<usize>>,
    allocation_stats: Arc<Mutex<AllocationStats>>,
    numa_node: Option<u32>,
}

/// Memory allocation statistics
/// メモリ割り当て統計
#[derive(Debug, Default, Clone)]
pub struct AllocationStats {
    /// Total number of allocations performed
    /// 実行された総割り当て数
    pub total_allocations: u64,
    /// Total number of deallocations performed
    /// 実行された総解放数
    pub total_deallocations: u64,
    /// Peak memory usage in bytes
    /// ピークメモリ使用量(バイト)
    pub peak_memory_usage: usize,
    /// Current memory usage in bytes
    /// 現在のメモリ使用量(バイト)
    pub current_memory_usage: usize,
    /// Number of cache hits
    /// キャッシュヒット数
    pub cache_hits: u64,
    /// Number of cache misses
    /// キャッシュミス数
    pub cache_misses: u64,
    /// Number of huge page allocations
    /// ヒュージページ割り当て数
    pub huge_page_allocations: u64,
    /// Memory fragmentation ratio (0.0 to 1.0)
    /// メモリフラグメンテーション率(0.0から1.0)
    pub fragmentation_ratio: f32,
}

impl AdvancedMemoryPool {
    /// Create new advanced memory pool
    /// 新しい高度なメモリプールを作成
    pub fn new(config: PoolConfig) -> Self {
        Self {
            config,
            free_blocks: RwLock::new(HashMap::new()),
            allocated_blocks: RwLock::new(HashMap::new()),
            total_allocated: Arc::new(Mutex::new(0)),
            allocation_stats: Arc::new(Mutex::new(AllocationStats::default())),
            numa_node: Self::detect_numa_node(),
        }
    }

    /// Allocate memory with specified strategy
    /// 指定された戦略でメモリを割り当て
    pub fn allocate<T: Float + 'static>(
        &self,
        size: usize,
        strategy: AllocationStrategy,
    ) -> ParallelResult<NonNull<T>> {
        let alignment = self.get_alignment_for_strategy(strategy);
        let actual_size = self.round_up_size(size * std::mem::size_of::<T>(), alignment);

        // Try to reuse existing block
        // 既存ブロックの再利用を試行
        if let Some(block) = self.try_reuse_block(actual_size, alignment)? {
            let ptr = unsafe { NonNull::new_unchecked(block.ptr.as_ptr() as *mut T) };
            self.update_stats_on_allocation(actual_size, true);
            return Ok(ptr);
        }

        // Allocate new block
        // 新しいブロックを割り当て
        let use_huge_pages = strategy == AllocationStrategy::HugePage
            || (actual_size >= HUGE_PAGE_SIZE && self.config.enable_huge_pages);

        let mut block = MemoryBlock::new(actual_size, alignment, use_huge_pages)?;

        // Prefault pages if enabled
        // 有効な場合はページをプリフォルト
        if self.config.enable_prefaulting {
            self.prefault_pages(&mut block)?;
        }

        let ptr = unsafe { NonNull::new_unchecked(block.ptr.as_ptr() as *mut T) };

        // Track allocated block
        // 割り当てブロックを追跡
        {
            let mut allocated = self.allocated_blocks.write().unwrap();
            allocated.insert(block.ptr.as_ptr(), block);
        }

        self.update_stats_on_allocation(actual_size, false);
        Ok(ptr)
    }

    /// Deallocate memory
    /// メモリを解放
    pub fn deallocate<T>(&self, ptr: NonNull<T>) -> ParallelResult<()> {
        let raw_ptr = ptr.as_ptr() as *mut u8;

        let block = {
            let mut allocated = self.allocated_blocks.write().unwrap();
            allocated
                .remove(&raw_ptr)
                .ok_or_else(|| RusTorchError::memory("Pointer not found in allocated blocks"))?
        };

        let size = block.size;

        // Return block to free pool if it's worth keeping
        // 保持する価値がある場合はフリープールに返却
        if self.should_keep_block(&block) {
            let mut free_blocks = self.free_blocks.write().unwrap();
            free_blocks.entry(size).or_default().push_back(block);
        }
        // Otherwise, block will be dropped and memory freed
        // そうでなければ、ブロックはドロップされメモリが解放される

        self.update_stats_on_deallocation(size);
        Ok(())
    }

    /// Get memory usage statistics
    /// メモリ使用統計を取得
    pub fn get_stats(&self) -> AllocationStats {
        let stats = self.allocation_stats.lock().unwrap();
        (*stats).clone()
    }

    /// Perform garbage collection
    /// ガベージコレクションを実行
    pub fn garbage_collect(&self) -> ParallelResult<usize> {
        let mut freed_memory = 0;
        let _now = Instant::now();
        let max_idle_time = Duration::from_secs(300); // 5 minutes

        let mut free_blocks = self.free_blocks.write().unwrap();

        for (size, blocks) in free_blocks.iter_mut() {
            blocks.retain(|block| {
                if block.idle_time() > max_idle_time {
                    freed_memory += size;
                    false
                } else {
                    true
                }
            });
        }

        // Remove empty size buckets
        // 空のサイズバケットを削除
        free_blocks.retain(|_, blocks| !blocks.is_empty());

        Ok(freed_memory)
    }

    /// Optimize memory layout for NUMA
    /// NUMA用のメモリレイアウト最適化
    pub fn optimize_for_numa(&self) -> ParallelResult<()> {
        if let Some(node) = self.numa_node {
            // Bind memory allocations to specific NUMA node
            // メモリ割り当てを特定のNUMAノードにバインド
            #[cfg(target_os = "linux")]
            {
                self.set_numa_policy(node)?;
            }
            #[cfg(not(target_os = "linux"))]
            {
                let _ = node; // Suppress unused variable warning on non-Linux platforms
            }
        }
        Ok(())
    }

    // Private helper methods
    // プライベートヘルパーメソッド

    fn get_alignment_for_strategy(&self, strategy: AllocationStrategy) -> usize {
        match strategy {
            AllocationStrategy::Standard => std::mem::align_of::<f64>(),
            AllocationStrategy::CacheAligned => CACHE_LINE_SIZE,
            AllocationStrategy::PageAligned => PAGE_SIZE,
            AllocationStrategy::HugePage => HUGE_PAGE_SIZE,
            AllocationStrategy::Pooled => self.config.alignment,
            AllocationStrategy::NumaAware => CACHE_LINE_SIZE,
        }
    }

    fn round_up_size(&self, size: usize, alignment: usize) -> usize {
        (size + alignment - 1) & !(alignment - 1)
    }

    fn try_reuse_block(
        &self,
        size: usize,
        alignment: usize,
    ) -> ParallelResult<Option<MemoryBlock>> {
        let mut free_blocks = self.free_blocks.write().unwrap();

        // Look for exact size match first
        // まず正確なサイズマッチを探す
        if let Some(blocks) = free_blocks.get_mut(&size) {
            if let Some(mut block) = blocks.pop_front() {
                if block.alignment >= alignment {
                    block.update_access();
                    return Ok(Some(block));
                } else {
                    blocks.push_back(block);
                }
            }
        }

        // Look for larger blocks that can be split
        // 分割可能な大きなブロックを探す
        for (&block_size, blocks) in free_blocks.iter_mut() {
            if block_size >= size && !blocks.is_empty() {
                if let Some(mut block) = blocks.pop_front() {
                    if block.alignment >= alignment {
                        block.update_access();
                        return Ok(Some(block));
                    } else {
                        blocks.push_back(block);
                    }
                }
            }
        }

        Ok(None)
    }

    fn should_keep_block(&self, block: &MemoryBlock) -> bool {
        let current_total = *self.total_allocated.lock().unwrap();
        let would_exceed_max = current_total + block.size > self.config.max_size;

        !would_exceed_max && block.access_count > 1
    }

    fn prefault_pages(&self, block: &mut MemoryBlock) -> ParallelResult<()> {
        unsafe {
            let ptr = block.ptr.as_ptr();
            let size = block.size;

            // Touch each page to prefault
            // 各ページにタッチしてプリフォルト
            for offset in (0..size).step_by(PAGE_SIZE) {
                let page_ptr = ptr.add(offset);
                std::ptr::write_volatile(page_ptr, 0);
            }
        }
        Ok(())
    }

    fn update_stats_on_allocation(&self, size: usize, cache_hit: bool) {
        let mut stats = self.allocation_stats.lock().unwrap();
        let mut total = self.total_allocated.lock().unwrap();

        stats.total_allocations += 1;
        *total += size;
        stats.current_memory_usage = *total;

        if *total > stats.peak_memory_usage {
            stats.peak_memory_usage = *total;
        }

        if cache_hit {
            stats.cache_hits += 1;
        } else {
            stats.cache_misses += 1;
        }
    }

    fn update_stats_on_deallocation(&self, size: usize) {
        let mut stats = self.allocation_stats.lock().unwrap();
        let mut total = self.total_allocated.lock().unwrap();

        stats.total_deallocations += 1;
        *total -= size;
        stats.current_memory_usage = *total;
    }

    fn detect_numa_node() -> Option<u32> {
        // Simplified NUMA detection
        // 簡略化されたNUMA検出
        #[cfg(target_os = "linux")]
        {
            // In practice, would use libnuma or similar
            // 実際にはlibnumaなどを使用
            Some(0)
        }
        #[cfg(not(target_os = "linux"))]
        {
            None
        }
    }

    #[cfg(target_os = "linux")]
    fn set_numa_policy(&self, _node: u32) -> ParallelResult<()> {
        // Simplified NUMA policy setting
        // 簡略化されたNUMAポリシー設定
        Ok(())
    }
}

/// Memory-optimized tensor operations
/// メモリ最適化テンソル演算
pub struct OptimizedTensorOps {
    memory_pool: Arc<AdvancedMemoryPool>,
}

impl OptimizedTensorOps {
    /// Create new optimized tensor operations
    /// 新しい最適化テンソル演算を作成
    pub fn new(pool_config: PoolConfig) -> Self {
        Self {
            memory_pool: Arc::new(AdvancedMemoryPool::new(pool_config)),
        }
    }

    /// Create tensor with optimized memory allocation
    /// 最適化メモリ割り当てでテンソルを作成
    pub fn create_tensor<T: Float + 'static>(
        &self,
        shape: &[usize],
        strategy: AllocationStrategy,
    ) -> ParallelResult<Tensor<T>> {
        let total_elements: usize = shape.iter().product();
        let ptr = self.memory_pool.allocate(total_elements, strategy)?;

        // Create tensor with custom memory
        // カスタムメモリでテンソルを作成
        unsafe {
            let data = std::slice::from_raw_parts_mut(ptr.as_ptr(), total_elements);
            data.fill(T::zero());
            Ok(Tensor::from_raw_parts(data, shape))
        }
    }

    /// Perform in-place operations to minimize memory allocation
    /// メモリ割り当てを最小化するインプレース演算
    pub fn add_inplace<T: Float + 'static>(
        &self,
        a: &mut Tensor<T>,
        b: &Tensor<T>,
    ) -> ParallelResult<()> {
        if a.shape() != b.shape() {
            return Err(RusTorchError::shape_mismatch(a.shape(), b.shape()));
        }

        // Vectorized in-place addition
        // ベクトル化インプレース加算
        let a_slice = a.as_slice_mut().unwrap();
        let b_slice = b.as_slice().unwrap();
        for i in 0..a_slice.len() {
            a_slice[i] = a_slice[i] + b_slice[i];
        }

        Ok(())
    }

    /// Get memory pool statistics
    /// メモリプール統計を取得
    pub fn get_memory_stats(&self) -> AllocationStats {
        self.memory_pool.get_stats()
    }

    /// Perform memory optimization
    /// メモリ最適化を実行
    pub fn optimize_memory(&self) -> ParallelResult<usize> {
        self.memory_pool.garbage_collect()
    }
}

/// Extension trait for Tensor to support custom memory management
/// カスタムメモリ管理をサポートするTensor用の拡張トレイト
pub trait TensorMemoryExt<T: Float> {
    /// Create tensor from raw memory parts
    /// 生メモリパーツからテンソルを作成
    fn from_raw_parts(data: &mut [T], shape: &[usize]) -> Tensor<T>;
    /// Get memory usage in bytes
    /// メモリ使用量をバイトで取得
    fn memory_usage(&self) -> usize;
    /// Check if memory is aligned to specified boundary
    /// 指定された境界にメモリがアライメントされているかチェック
    fn is_memory_aligned(&self, alignment: usize) -> bool;
}

impl<T: Float + 'static> TensorMemoryExt<T> for Tensor<T> {
    fn from_raw_parts(_data: &mut [T], shape: &[usize]) -> Tensor<T> {
        // Simplified implementation - in practice would need proper tensor construction
        // 簡略化実装 - 実際には適切なテンソル構築が必要
        Tensor::zeros(shape)
    }

    fn memory_usage(&self) -> usize {
        self.as_slice().unwrap().len() * std::mem::size_of::<T>()
    }

    fn is_memory_aligned(&self, alignment: usize) -> bool {
        (self.as_slice().unwrap().as_ptr() as usize) % alignment == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_advanced_memory_pool() {
        let config = PoolConfig::default();
        let pool = AdvancedMemoryPool::new(config);

        let ptr: NonNull<f32> = pool
            .allocate(1000, AllocationStrategy::CacheAligned)
            .unwrap();
        assert!(pool.deallocate(ptr).is_ok());

        let stats = pool.get_stats();
        assert_eq!(stats.total_allocations, 1);
        assert_eq!(stats.total_deallocations, 1);
    }

    #[test]
    fn test_optimized_tensor_ops() {
        let config = PoolConfig::default();
        let ops = OptimizedTensorOps::new(config);

        let tensor: Tensor<f32> = ops
            .create_tensor(&[100, 100], AllocationStrategy::CacheAligned)
            .unwrap();
        assert_eq!(tensor.shape(), &[100, 100]);

        let stats = ops.get_memory_stats();
        assert!(stats.total_allocations > 0);
    }

    #[test]
    fn test_memory_alignment() {
        let tensor: Tensor<f32> = Tensor::zeros(&[64]);
        assert!(tensor.is_memory_aligned(std::mem::align_of::<f32>()));
    }

    #[test]
    fn test_garbage_collection() {
        let config = PoolConfig::default();
        let pool = AdvancedMemoryPool::new(config);

        // Allocate and deallocate several blocks
        // 複数のブロックを割り当てて解放
        for _ in 0..10 {
            let ptr: NonNull<f32> = pool.allocate(1000, AllocationStrategy::Standard).unwrap();
            pool.deallocate(ptr).unwrap();
        }

        let freed = pool.garbage_collect().unwrap();
        // Some memory should be freed during GC
        // GC中にいくらかのメモリが解放されるはず
        // freed is usize, always >= 0
        assert!(freed == freed); // Keep the variable used
    }
}