pkbuffer 0.7.0

Buffer objects made for arbitrary casting and addressing!
Documentation

PKBuffer

PKBuffer is a simple but flexible buffer library for reading and writing data to byte buffers using safe byte-copy operations. It was born of multiple memory parsing scenarios such as executable header parsing and game ROM memory mapping. Its name comes from the magic that is casting arbitrary structure definitions at byte buffers and the fact that I was reverse engineering the game EarthBound at the time.

You can read the documentation here, and see various use examples in the test file. The changelog can be found here.

Quick Start

use pkbuffer::{Buffer, VecBuffer};

let mut buffer = VecBuffer::new();
buffer.append_val::<u8>(&0x1);
buffer.append_val::<u16>(&0x0302);
buffer.append_val::<u32>(&0x07060504);
assert_eq!(buffer, [1, 2, 3, 4, 5, 6, 7]);

Aligned Reference Access (0.7.0+)

For well-aligned data, use get_aligned_ref and get_aligned_mut to get direct references:

use pkbuffer::{Buffer, VecBuffer};

let mut buffer = VecBuffer::with_initial_size(16);
buffer.write_val::<u32>(0, &0xDEADBEEF).unwrap();

// Get a reference at an aligned offset
let val: &u32 = buffer.get_aligned_ref(0).unwrap();
assert_eq!(*val, 0xDEADBEEF);

// Get a mutable reference for in-place modification
let val: &mut u32 = buffer.get_aligned_mut(0).unwrap();
*val = 0xFEEDFACE;  // writes directly to buffer

// Misaligned access returns an error
assert!(buffer.get_aligned_ref::<u32>(1).is_err());
// Error::AlignmentMismatch(offset, required_alignment)

Key Features

  • Safe byte-copy reads/writes: Use read_val<T>() and write_val<T>() to read/write any Copy type without alignment requirements
  • Two buffer types: PtrBuffer for unowned memory and VecBuffer for owned data
  • Rich search functionality: Search for byte patterns with search() and dynamic patterns with wildcards via search_dynamic()
  • No unsafe pointer casting: All type conversions use safe byte-copying instead of pointer casting
  • Aligned reference access: get_aligned_ref and get_aligned_mut provide direct references with alignment verification

API Changes in 0.6.0

This version removes the Castable trait and all methods that relied on unsafe pointer casting for type conversions. The new API uses safe byte-copy operations exclusively:

  • read_val<T: Copy>(offset) replaces get_ref<T: Castable>(offset)
  • write_val<T: Copy>(offset, &data) replaces write_ref<T: Castable>(offset, &data)
  • search(bytes) replaces search_ref(data)
  • contains(bytes) replaces contains_ref(data)

All Copy types (primitives like u8, u16, u32, etc.) work directly with the new API. No trait derivations required.