dx-serializer 0.1.0

A token-efficient serialization format for LLM context windows with high-performance binary encoding
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
//! # Safety Validation Utilities
//!
//! This module provides zero-cost abstractions for common safety checks
//! required when working with unsafe code. It is designed to provide
//! consistent validation patterns for zero-copy operations.
//!
//! ## Attribution
//!
//! This code is inlined from the `dx-safety` crate to enable standalone
//! publishability of `dx-serializer` without path dependencies.
//! Original source: `crates/dx/dx-safety/src/lib.rs`
//!
//! ## Usage
//!
//! ```rust
//! use serializer::safety::{check_bounds, check_alignment, check_cast, SafetyError};
//!
//! fn safe_read<T: Copy>(buffer: &[u8]) -> Result<&T, SafetyError> {
//!     // Validate before any unsafe operation
//!     check_cast::<T>(buffer)?;
//!     
//!     // SAFETY: We verified size >= size_of::<T>() and alignment matches
//!     Ok(unsafe { &*(buffer.as_ptr() as *const T) })
//! }
//!
//! // Example usage
//! let data = [1u8, 0, 0, 0]; // Little-endian 1
//! let value: &u32 = safe_read(&data).unwrap();
//! assert_eq!(*value, 1);
//! ```

use core::fmt;
use core::mem::{align_of, size_of};

// ============================================================================
// ERROR TYPES
// ============================================================================

/// Error type for safety validation failures.
///
/// All variants include context information to aid debugging.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SafetyError {
    /// Buffer is too small for the requested type.
    ///
    /// Contains the number of bytes needed and the actual buffer size.
    BufferTooSmall {
        /// Minimum bytes required
        needed: usize,
        /// Actual buffer size
        actual: usize,
    },

    /// Pointer is not properly aligned for the requested type.
    ///
    /// Contains the required alignment and the actual misalignment offset.
    Misaligned {
        /// Required alignment in bytes
        needed: usize,
        /// Actual offset from aligned address (ptr % needed)
        actual: usize,
    },

    /// Offset would exceed buffer bounds.
    ///
    /// Contains the requested offset and the buffer length.
    OffsetOutOfBounds {
        /// Requested offset
        offset: usize,
        /// Buffer length
        length: usize,
    },

    /// Integer overflow occurred during size calculation.
    ///
    /// This typically happens when multiplying `count * size_of::<T>()`.
    Overflow,
}

impl fmt::Display for SafetyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BufferTooSmall { needed, actual } => {
                write!(
                    f,
                    "buffer too small: needed {} bytes, got {}",
                    needed, actual
                )
            }
            Self::Misaligned { needed, actual } => {
                write!(
                    f,
                    "pointer misaligned: needed {} byte alignment, offset is {}",
                    needed, actual
                )
            }
            Self::OffsetOutOfBounds { offset, length } => {
                write!(f, "offset {} out of bounds for length {}", offset, length)
            }
            Self::Overflow => write!(f, "integer overflow in size calculation"),
        }
    }
}

impl std::error::Error for SafetyError {}

// ============================================================================
// BOUNDS CHECKING UTILITIES
// ============================================================================

/// Check that a slice has sufficient length for type T.
///
/// This is a zero-cost check when the slice is large enough.
///
/// # Example
///
/// ```rust
/// use serializer::safety::{check_size, SafetyError};
///
/// let buffer = [0u8; 8];
/// assert!(check_size::<u64>(&buffer).is_ok());
/// assert!(check_size::<u128>(&buffer).is_err());
/// ```
#[inline(always)]
pub fn check_size<T>(slice: &[u8]) -> Result<(), SafetyError> {
    let needed = size_of::<T>();
    if slice.len() < needed {
        Err(SafetyError::BufferTooSmall {
            needed,
            actual: slice.len(),
        })
    } else {
        Ok(())
    }
}

/// Check that offset + size doesn't exceed buffer length.
///
/// This function also checks for integer overflow when adding offset + size.
///
/// # Example
///
/// ```rust
/// use serializer::safety::{check_bounds, SafetyError};
///
/// // Valid: offset 0, size 4, length 8
/// assert!(check_bounds(0, 4, 8).is_ok());
///
/// // Invalid: offset 6, size 4, length 8 (6 + 4 = 10 > 8)
/// assert!(matches!(
///     check_bounds(6, 4, 8),
///     Err(SafetyError::OffsetOutOfBounds { .. })
/// ));
///
/// // Overflow: very large values
/// assert!(matches!(
///     check_bounds(usize::MAX, 1, 100),
///     Err(SafetyError::Overflow)
/// ));
/// ```
#[inline(always)]
pub fn check_bounds(offset: usize, size: usize, length: usize) -> Result<(), SafetyError> {
    match offset.checked_add(size) {
        Some(end) if end <= length => Ok(()),
        Some(_) => Err(SafetyError::OffsetOutOfBounds { offset, length }),
        None => Err(SafetyError::Overflow),
    }
}

/// Check bounds for reading `count` elements of type T starting at `offset`.
///
/// This combines overflow checking for `count * size_of::<T>()` with bounds checking.
///
/// # Example
///
/// ```rust
/// use serializer::safety::{check_slice_bounds, SafetyError};
///
/// let buffer = [0u8; 32];
///
/// // Valid: 4 u64s starting at offset 0 = 32 bytes
/// assert!(check_slice_bounds::<u64>(0, 4, buffer.len()).is_ok());
///
/// // Invalid: 5 u64s = 40 bytes > 32
/// assert!(check_slice_bounds::<u64>(0, 5, buffer.len()).is_err());
/// ```
#[inline(always)]
pub fn check_slice_bounds<T>(
    offset: usize,
    count: usize,
    length: usize,
) -> Result<(), SafetyError> {
    let size = size_of::<T>()
        .checked_mul(count)
        .ok_or(SafetyError::Overflow)?;
    check_bounds(offset, size, length)
}

// ============================================================================
// ALIGNMENT CHECKING UTILITIES
// ============================================================================

/// Check that a pointer is properly aligned for type T.
///
/// # Example
///
/// ```rust
/// use serializer::safety::{check_alignment, SafetyError};
///
/// let aligned: [u64; 2] = [0, 0];
/// let ptr = aligned.as_ptr() as *const u8;
///
/// // u64 requires 8-byte alignment
/// assert!(check_alignment::<u64>(ptr).is_ok());
///
/// // Offset by 1 byte - now misaligned for u64
/// let misaligned = unsafe { ptr.add(1) };
/// assert!(matches!(
///     check_alignment::<u64>(misaligned),
///     Err(SafetyError::Misaligned { needed: 8, actual: 1 })
/// ));
/// ```
#[inline(always)]
pub fn check_alignment<T>(ptr: *const u8) -> Result<(), SafetyError> {
    let needed = align_of::<T>();
    let actual = ptr as usize % needed;
    if actual != 0 {
        Err(SafetyError::Misaligned { needed, actual })
    } else {
        Ok(())
    }
}

/// Combined check for size and alignment before casting a slice to type T.
///
/// This is the primary validation function for zero-copy deserialization.
///
/// # Example
///
/// ```rust
/// use serializer::safety::{check_cast, SafetyError};
///
/// #[repr(C)]
/// struct Header {
///     magic: u32,
///     version: u32,
/// }
///
/// fn read_header(buffer: &[u8]) -> Result<&Header, SafetyError> {
///     check_cast::<Header>(buffer)?;
///     // SAFETY: We verified size and alignment
///     Ok(unsafe { &*(buffer.as_ptr() as *const Header) })
/// }
///
/// // Example usage with properly aligned buffer
/// let data = [0x44u8, 0x58, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00];
/// let header = read_header(&data).unwrap();
/// ```
#[inline(always)]
pub fn check_cast<T>(slice: &[u8]) -> Result<(), SafetyError> {
    check_size::<T>(slice)?;
    check_alignment::<T>(slice.as_ptr())?;
    Ok(())
}

// ============================================================================
// SAFE POINTER UTILITIES
// ============================================================================

/// Safely read a value of type T from a byte slice with full validation.
///
/// This is a convenience function that combines validation and reading.
///
/// # Safety
///
/// This helper borrows a `T` directly from caller-provided bytes. The caller
/// must only use types that can safely be viewed from raw bytes, such as
/// integer primitives or carefully audited `#[repr(C)]` POD structs. The
/// function validates length and alignment before the cast, but it cannot prove
/// that every possible bit pattern is valid for `T`.
///
/// # Example
///
/// ```rust
/// use serializer::safety::safe_read;
///
/// let buffer = 42u64.to_le_bytes();
/// let value: &u64 = safe_read(&buffer).unwrap();
/// assert_eq!(*value, 42);
/// ```
#[inline]
#[allow(unsafe_code)]
pub fn safe_read<T: Copy>(slice: &[u8]) -> Result<&T, SafetyError> {
    check_cast::<T>(slice)?;
    // SAFETY: length and alignment were checked immediately above. Validity of
    // the `T` bit pattern is part of this helper's documented contract.
    Ok(unsafe { &*(slice.as_ptr() as *const T) })
}

/// Safely read a slice of values from a byte buffer with full validation.
///
/// # Safety
///
/// This helper borrows a `[T]` directly from caller-provided bytes. The caller
/// must only use types that can safely be viewed from raw bytes. The function
/// validates length and alignment, but validity of each `T` value remains part
/// of the caller contract.
///
/// # Example
///
/// ```rust
/// use serializer::safety::{safe_read_slice, SafetyError};
///
/// // Create a properly aligned buffer
/// let values: [u32; 4] = [1, 2, 3, 4];
/// let bytes: &[u8] = bytemuck::cast_slice(&values);
/// let read_values: &[u32] = safe_read_slice(bytes, 4).unwrap();
/// assert_eq!(read_values, &[1, 2, 3, 4]);
/// ```
#[inline]
#[allow(unsafe_code)]
pub fn safe_read_slice<T: Copy>(slice: &[u8], count: usize) -> Result<&[T], SafetyError> {
    check_slice_bounds::<T>(0, count, slice.len())?;
    check_alignment::<T>(slice.as_ptr())?;
    // SAFETY: bounds and alignment were checked immediately above. Validity of
    // each `T` bit pattern is part of this helper's documented contract.
    Ok(unsafe { core::slice::from_raw_parts(slice.as_ptr() as *const T, count) })
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_check_size_success() {
        let buffer = [0u8; 16];
        assert!(check_size::<u8>(&buffer).is_ok());
        assert!(check_size::<u16>(&buffer).is_ok());
        assert!(check_size::<u32>(&buffer).is_ok());
        assert!(check_size::<u64>(&buffer).is_ok());
        assert!(check_size::<u128>(&buffer).is_ok());
    }

    #[test]
    fn test_check_size_failure() {
        let buffer = [0u8; 4];
        assert!(matches!(
            check_size::<u64>(&buffer),
            Err(SafetyError::BufferTooSmall {
                needed: 8,
                actual: 4
            })
        ));
    }

    #[test]
    fn test_check_bounds_success() {
        assert!(check_bounds(0, 4, 8).is_ok());
        assert!(check_bounds(4, 4, 8).is_ok());
        assert!(check_bounds(0, 8, 8).is_ok());
        assert!(check_bounds(0, 0, 0).is_ok());
    }

    #[test]
    fn test_check_bounds_failure() {
        assert!(matches!(
            check_bounds(5, 4, 8),
            Err(SafetyError::OffsetOutOfBounds {
                offset: 5,
                length: 8
            })
        ));
    }

    #[test]
    fn test_check_bounds_overflow() {
        assert!(matches!(
            check_bounds(usize::MAX, 1, 100),
            Err(SafetyError::Overflow)
        ));
    }

    #[test]
    fn test_check_alignment_success() {
        let aligned: [u64; 2] = [0, 0];
        let ptr = aligned.as_ptr() as *const u8;
        assert!(check_alignment::<u64>(ptr).is_ok());
        assert!(check_alignment::<u32>(ptr).is_ok());
        assert!(check_alignment::<u16>(ptr).is_ok());
        assert!(check_alignment::<u8>(ptr).is_ok());
    }

    #[test]
    fn test_check_alignment_failure() {
        let aligned: [u64; 2] = [0, 0];
        let ptr = aligned.as_ptr() as *const u8;
        let misaligned = ptr.wrapping_add(1);

        let result = check_alignment::<u64>(misaligned);
        assert!(matches!(
            result,
            Err(SafetyError::Misaligned {
                needed: 8,
                actual: 1
            })
        ));
    }

    #[test]
    fn test_safe_read() {
        let value: u64 = 0x1234567890ABCDEF;
        let bytes = value.to_le_bytes();

        let read_value: &u64 = safe_read(&bytes).unwrap();
        assert_eq!(*read_value, value);
    }

    #[test]
    fn test_safe_read_slice() {
        let values: [u32; 4] = [1, 2, 3, 4];
        #[repr(align(4))]
        struct AlignedBytes([u8; 16]);

        let mut bytes = AlignedBytes([0; 16]);
        for (chunk, value) in bytes.0.chunks_exact_mut(4).zip(values) {
            chunk.copy_from_slice(&value.to_ne_bytes());
        }

        let read_values: &[u32] = safe_read_slice(&bytes.0, 4).unwrap();
        assert_eq!(read_values, &[1, 2, 3, 4]);
    }

    #[test]
    fn test_error_display() {
        let err = SafetyError::BufferTooSmall {
            needed: 8,
            actual: 4,
        };
        assert_eq!(err.to_string(), "buffer too small: needed 8 bytes, got 4");

        let err = SafetyError::Misaligned {
            needed: 8,
            actual: 3,
        };
        assert_eq!(
            err.to_string(),
            "pointer misaligned: needed 8 byte alignment, offset is 3"
        );

        let err = SafetyError::OffsetOutOfBounds {
            offset: 10,
            length: 8,
        };
        assert_eq!(err.to_string(), "offset 10 out of bounds for length 8");

        let err = SafetyError::Overflow;
        assert_eq!(err.to_string(), "integer overflow in size calculation");
    }
}