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
//! Vector to bytes conversion utilities for storage.
//!
//! Provides safe conversion between `&[f32]` vectors and `&[u8]` byte slices
//! for persistence in memory-mapped storage.
//!
//! # Safety (EPIC-032/US-001)
//!
//! - `vector_to_bytes`: Safe because f32 has no invalid bit patterns
//! - `bytes_to_vector`: Safe because it copies bytes into a new aligned `Vec<f32>`
//! using `ptr::copy_nonoverlapping`, which doesn't require source alignment
/// Converts a vector slice to a byte slice.
///
/// # Safety
///
/// This is safe because:
/// - f32 has no invalid bit patterns
/// - The slice layout is well-defined
/// - The lifetime of the returned slice is tied to the input
#[inline]
pub(super) fn vector_to_bytes(vector: &[f32]) -> &[u8] {
// SAFETY: `from_raw_parts` requires a valid pointer and byte length.
// - Condition 1: `vector.as_ptr()` is valid for `size_of_val(vector)` bytes.
// - Condition 2: Lifetime of returned bytes is tied to `vector`.
// SAFETY: Zero-copy view avoids allocating during persistence writes.
unsafe {
std::slice::from_raw_parts(vector.as_ptr().cast::<u8>(), std::mem::size_of_val(vector))
}
}
/// Converts bytes back to a vector.
///
/// # Arguments
///
/// * `bytes` - Raw bytes to convert (must be at least `dimension * 4` bytes)
/// * `dimension` - Expected vector dimension
///
/// # Returns
///
/// A new `Vec<f32>` containing the converted data.
///
/// # Safety contract
///
/// Caller must ensure `bytes.len() >= dimension * size_of::<f32>()`.
/// The mmap reader (`vector_io.rs`) validates offset bounds before calling.
#[inline]
pub(super) fn bytes_to_vector(bytes: &[u8], dimension: usize) -> Vec<f32> {
let vector_size = dimension * std::mem::size_of::<f32>();
// Hard assert: this guards a `copy_nonoverlapping` below. In release builds
// a `debug_assert!` would be elided, allowing out-of-bounds reads (UB).
assert!(
bytes.len() >= vector_size,
"bytes_to_vector: buffer too small ({} < {vector_size})",
bytes.len(),
);
let mut vector = vec![0.0f32; dimension];
// SAFETY: `copy_nonoverlapping` requires valid, non-overlapping ranges.
// - Condition 1: Source has at least `vector_size` bytes (assert above,
// plus caller bounds-checks in mmap_io before calling).
// - Condition 2: Destination is freshly allocated `Vec<f32>` storage.
// SAFETY: Copying into aligned owned memory avoids alignment UB from direct cast reads.
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
vector.as_mut_ptr().cast::<u8>(),
vector_size,
);
}
vector
}