Skip to main content

Buffer

Struct Buffer 

Source
pub struct Buffer { /* private fields */ }
Expand description

A high-performance linear buffer with position tracking.

The buffer automatically and securely zeros its memory on drop using the zeroize crate, which provides compiler-resistant memory clearing.

§Memory Safety

All buffer memory is automatically zeroed when the buffer is dropped, preventing sensitive data from remaining in memory.

§Examples

use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_u32(42)?;
buf.put_bytes(b"hello")?;

Implementations§

Source§

impl Buffer

Source

pub fn new(size: usize) -> Self

Creates a new buffer with zeroed memory.

For large buffers (>4KB), the OS typically provides zero-filled pages efficiently via demand paging, making this nearly as fast as uninitialized allocation.

§Panics

Panics if size exceeds BUF_MAX_SIZE (1GB).

§Examples
use secbuf::Buffer;

let buf = Buffer::new(8192);
assert_eq!(buf.capacity(), 8192);
assert_eq!(buf.len(), 0);
Source

pub fn with_capacity(capacity: usize) -> Self

Creates a new buffer with pre-allocated capacity but zero length.

This is more efficient than new when you know the maximum size but want to grow the buffer incrementally. The internal Vec will only be zeroed for the portions actually used.

§Panics

Panics if capacity exceeds BUF_MAX_SIZE (1GB).

§Examples
use secbuf::Buffer;

let mut buf = Buffer::with_capacity(8192);
assert_eq!(buf.capacity(), 8192);
assert_eq!(buf.len(), 0);
Source

pub fn from_vec(data: Vec<u8>) -> Self

Creates a new buffer from existing data.

The buffer’s length is set to the vector’s length, and the position is set to 0.

§Examples
use secbuf::Buffer;

let data = vec![1, 2, 3, 4, 5];
let buf = Buffer::from_vec(data);
assert_eq!(buf.len(), 5);
assert_eq!(buf.pos(), 0);
Source

pub fn capacity(&self) -> usize

Returns the total capacity of the buffer.

§Examples
use secbuf::Buffer;

let buf = Buffer::new(1024);
assert_eq!(buf.capacity(), 1024);
Source

pub fn len(&self) -> usize

Returns the length of valid data in the buffer.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
assert_eq!(buf.len(), 0);

buf.put_u32(42)?;
assert_eq!(buf.len(), 4);
Source

pub fn is_empty(&self) -> bool

Returns true if the buffer contains no valid data.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
assert!(buf.is_empty());

buf.put_u32(42)?;
assert!(!buf.is_empty());
Source

pub fn pos(&self) -> usize

Returns the current read/write position.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
assert_eq!(buf.pos(), 0);

buf.put_u32(42)?;
assert_eq!(buf.pos(), 4);
Source

pub fn remaining(&self) -> usize

Returns the number of bytes available to read from current position.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_u32(42)?;
buf.put_u32(43)?;
buf.set_pos(0)?;

assert_eq!(buf.remaining(), 8);
buf.get_u32()?;
assert_eq!(buf.remaining(), 4);
Source

pub fn has_remaining(&self, count: usize) -> bool

Checks if at least count bytes are available to read.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_u32(42)?;
buf.set_pos(0)?;

assert!(buf.has_remaining(4));
assert!(!buf.has_remaining(5));
Source

pub fn set_pos(&mut self, pos: usize) -> Result<()>

Sets the read/write position.

§Errors

Returns BufferError::PositionOutOfBounds if pos exceeds the buffer length.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_u32(42)?;
buf.set_pos(0)?;

assert_eq!(buf.get_u32()?, 42);
Source

pub fn set_len(&mut self, len: usize) -> Result<()>

Sets the length of valid data.

When using with_capacity, this will grow the internal Vec if needed.

§Errors

Returns BufferError::SizeTooBig if len exceeds BUF_MAX_SIZE.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::with_capacity(1024);
buf.set_len(100)?;
assert_eq!(buf.len(), 100);
Source

pub fn incr_pos(&mut self, incr: usize) -> Result<()>

Increments the position by incr.

§Errors

Returns BufferError::IncrementTooLarge if the increment is too large or would exceed the buffer length.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_bytes(b"hello")?;
buf.set_pos(0)?;

buf.incr_pos(2)?;
assert_eq!(buf.pos(), 2);
Source

pub fn decr_pos(&mut self, decr: usize) -> Result<()>

Decrements the position by decr.

§Errors

Returns BufferError::PositionOutOfBounds if decr exceeds the current position.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_u32(42)?;

buf.decr_pos(2)?;
assert_eq!(buf.pos(), 2);
Source

pub fn incr_len(&mut self, incr: usize) -> Result<()>

Increments the length by incr.

When using with_capacity, this will grow the internal Vec if needed.

§Errors

Returns BufferError::IncrementTooLarge if the increment is too large. Returns BufferError::SizeTooBig if the new length would exceed BUF_MAX_SIZE.

Source

pub fn incr_write_pos(&mut self, incr: usize) -> Result<()>

Increments the write position and updates length if needed.

When using with_capacity, this will grow the internal Vec if needed.

§Errors

Returns BufferError::IncrementTooLarge if the increment is too large or the new position would exceed BUF_MAX_SIZE.

Source

pub fn reset(&mut self)

Resets the buffer for reuse by clearing position and length.

This does not free memory or zero the contents. Use burn for secure erasure.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_u32(42)?;
assert_eq!(buf.len(), 4);

buf.reset();
assert_eq!(buf.len(), 0);
assert_eq!(buf.pos(), 0);
Source

pub fn burn(&mut self)

Securely zeros all buffer memory and resets position and length.

Uses compiler-resistant zeroing via the zeroize crate.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_bytes(b"sensitive data")?;
buf.burn();
Source

pub fn burn_free(self)

Consumes the buffer and securely frees its memory.

Equivalent to Dropbear’s buf_burn_free() pattern. Provides explicit ownership-consuming cleanup.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_bytes(b"secret")?;
buf.burn_free(); // Buffer consumed and securely erased
Source

pub fn as_slice(&self) -> &[u8]

Returns a slice of all valid data in the buffer.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_bytes(b"hello")?;
assert_eq!(buf.as_slice(), b"hello");
Source

pub fn as_mut_slice(&mut self) -> &mut [u8]

Returns a mutable slice of all valid data.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_bytes(b"hello")?;
buf.as_mut_slice()[0] = b'H';
assert_eq!(buf.as_slice(), b"Hello");
Source

pub fn resize(&mut self, new_size: usize) -> Result<()>

Resizes the buffer, preserving existing data.

§Errors

Returns BufferError::SizeTooBig if new_size exceeds BUF_MAX_SIZE.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.resize(2048)?;
assert_eq!(buf.capacity(), 2048);
Source

pub fn reserve(&mut self, additional: usize)

Ensures the buffer has at least the specified additional capacity.

Similar to Vec::reserve.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(100);
buf.reserve(1000);
assert!(buf.capacity() >= 1100);
Source

pub fn shrink_to_fit(&mut self)

Shrinks the buffer capacity to fit the current length.

Frees unused memory.

§Examples
use secbuf::Buffer;

let mut buf = Buffer::new(1024);
buf.put_bytes(b"hello")?;
buf.shrink_to_fit();
assert_eq!(buf.capacity(), 5);
Source§

impl Buffer

Source

pub fn put_u32(&mut self, val: u32) -> Result<()>

Writes a u32 in big-endian format with bounds checking.

Source

pub fn get_u32(&mut self) -> Result<u32>

Reads a u32 in big-endian format with bounds checking.

Source

pub fn put_u64(&mut self, val: u64) -> Result<()>

Writes a u64 in big-endian format with bounds checking.

Source

pub fn get_u64(&mut self) -> Result<u64>

Reads a u64 in big-endian format with bounds checking.

Source

pub fn put_bytes(&mut self, bytes: &[u8]) -> Result<()>

Writes bytes with a single bounds check.

Source

pub fn get_bytes(&mut self, len: usize) -> Result<Vec<u8>>

Reads bytes, returning an owned Vec.

Source

pub fn get_bytes_ref(&mut self, len: usize) -> Result<&[u8]>

Reads bytes as a slice reference (zero-copy).

Source

pub fn get_ptr(&self, len: usize) -> Result<&[u8]>

Gets a reference to data at current position without advancing.

Source

pub fn get_write_ptr(&mut self, len: usize) -> Result<&mut [u8]>

Gets a mutable reference to data at current position (for writing).

Source

pub fn put_byte(&mut self, val: u8) -> Result<()>

Writes a single byte.

Source

pub fn get_byte(&mut self) -> Result<u8>

Reads a single byte.

Source

pub fn get_bool(&mut self) -> Result<bool>

Reads a boolean (0 = false, non-zero = true).

Source

pub fn put_string(&mut self, s: &[u8]) -> Result<()>

Writes an SSH-style string (4-byte length prefix + data).

Source

pub fn get_string(&mut self) -> Result<Vec<u8>>

Reads an SSH-style string (4-byte length prefix + data).

Source

pub fn eat_string(&mut self) -> Result<()>

Skips over an SSH-style string without reading the data.

Source

pub fn put_bytes_fast(&mut self, bytes: &[u8]) -> Result<()>

SIMD-accelerated bulk copy for large buffers (≥64 bytes).

Source§

impl Buffer

Source

pub unsafe fn put_u32_unchecked(&mut self, val: u32)

Writes a u32 in big-endian format without bounds checking.

§Safety

Caller MUST guarantee: self.pos + 4 <= self.capacity().

Source

pub unsafe fn get_u32_unchecked(&mut self) -> u32

Reads a u32 in big-endian format without bounds checking.

§Safety

Caller MUST guarantee: self.pos + 4 <= self.len.

Source

pub unsafe fn put_u64_unchecked(&mut self, val: u64)

Writes a u64 in big-endian format without bounds checking.

§Safety

Caller MUST guarantee: self.pos + 8 <= self.capacity().

Source

pub unsafe fn get_u64_unchecked(&mut self) -> u64

Reads a u64 in big-endian format without bounds checking.

§Safety

Caller MUST guarantee: self.pos + 8 <= self.len.

Source

pub unsafe fn put_bytes_unchecked(&mut self, bytes: &[u8])

Writes bytes without bounds checking.

§Safety

Caller MUST guarantee: self.pos + bytes.len() <= self.capacity().

Source

pub unsafe fn get_bytes_unchecked(&mut self, len: usize) -> &[u8]

Reads bytes without bounds checking, returning a slice.

§Safety

Caller MUST guarantee: self.pos + len <= self.len.

Trait Implementations§

Source§

impl AsRef<[u8]> for Buffer

Source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Buffer

Source§

fn clone(&self) -> Buffer

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Zeroize for Buffer

Source§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.

Auto Trait Implementations§

§

impl Freeze for Buffer

§

impl RefUnwindSafe for Buffer

§

impl Send for Buffer

§

impl Sync for Buffer

§

impl Unpin for Buffer

§

impl UnwindSafe for Buffer

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.