1use crate::error::{HiveGpuError, Result};
4
5pub mod memory_utils {
7 use super::*;
8
9 pub fn calculate_vector_memory_size(dimension: usize, count: usize) -> usize {
11 count * dimension * std::mem::size_of::<f32>()
12 }
13
14 pub fn calculate_metadata_memory_size(count: usize) -> usize {
16 count * 256 }
18
19 pub fn is_memory_allocation_safe(
21 requested: usize,
22 available: usize,
23 safety_margin: f32,
24 ) -> bool {
25 let safe_limit = (available as f32 * safety_margin) as usize;
26 requested <= safe_limit
27 }
28
29 pub fn calculate_optimal_buffer_size(
31 current_size: usize,
32 growth_factor: f32,
33 max_size: usize,
34 ) -> usize {
35 let new_size = (current_size as f32 * growth_factor) as usize;
36 new_size.min(max_size)
37 }
38}
39
40pub mod buffer_utils {
42 use super::*;
43
44 pub const BUFFER_ALIGNMENT: usize = 256;
46
47 pub fn align_buffer_size(size: usize) -> usize {
49 ((size + BUFFER_ALIGNMENT - 1) / BUFFER_ALIGNMENT) * BUFFER_ALIGNMENT
50 }
51
52 pub fn calculate_buffer_pool_size(
54 vector_count: usize,
55 dimension: usize,
56 pool_factor: f32,
57 ) -> usize {
58 let base_size = memory_utils::calculate_vector_memory_size(dimension, vector_count);
59 (base_size as f32 * pool_factor) as usize
60 }
61
62 pub fn validate_buffer_parameters(
64 size: usize,
65 alignment: usize,
66 max_size: usize,
67 ) -> Result<()> {
68 if size == 0 {
69 return Err(HiveGpuError::BufferAllocationFailed(
70 "Zero buffer size".to_string(),
71 ));
72 }
73
74 if size > max_size {
75 return Err(HiveGpuError::BufferAllocationFailed(format!(
76 "Buffer size {} exceeds maximum {}",
77 size, max_size
78 )));
79 }
80
81 if size % alignment != 0 {
82 return Err(HiveGpuError::BufferAllocationFailed(format!(
83 "Buffer size {} not aligned to {}",
84 size, alignment
85 )));
86 }
87
88 Ok(())
89 }
90}