secbuf 0.1.7

Secure, high-performance buffer management with automatic memory zeroing and aggressive cleanup
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// src/buffer/core.rs
//! Core buffer structure and basic operations
//!
//! This module provides the fundamental [`Buffer`] type with position tracking
//! and automatic secure memory zeroing on drop.

use crate::error::{BufferError, Result};
use zeroize::Zeroize;

/// Maximum single increment to prevent integer overflow
pub const BUF_MAX_INCR: usize = 1_000_000_000;
/// Maximum buffer size (1GB)
pub const BUF_MAX_SIZE: usize = 1_000_000_000;

/// 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;
/// # use secbuf::BufferError;
///
/// let mut buf = Buffer::new(1024);
/// buf.put_u32(42)?;
/// buf.put_bytes(b"hello")?;
/// # Ok::<(), BufferError>(())
/// ```
#[derive(Clone, Zeroize)]
#[zeroize(drop)]
pub struct Buffer {
    /// Internal data storage (securely erased on drop)
    pub(crate) data: Vec<u8>,
    /// Current read/write position
    pub(crate) pos: usize,
    /// Length of valid data
    pub(crate) len: usize,
}

impl Buffer {
    /// 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);
    /// ```
    #[inline]
    pub fn new(size: usize) -> Self {
        assert!(
            size <= BUF_MAX_SIZE,
            "Buffer size {} exceeds maximum {}",
            size,
            BUF_MAX_SIZE
        );
        Self {
            data: vec![0; size],
            pos: 0,
            len: 0,
        }
    }

    /// Creates a new buffer with pre-allocated capacity but zero length.
    ///
    /// This is more efficient than [`new`](Self::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;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::with_capacity(8192);
    /// assert_eq!(buf.capacity(), 8192);
    /// assert_eq!(buf.len(), 0);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        assert!(
            capacity <= BUF_MAX_SIZE,
            "Buffer capacity {} exceeds maximum {}",
            capacity,
            BUF_MAX_SIZE
        );
        Self {
            data: Vec::with_capacity(capacity),
            pos: 0,
            len: 0,
        }
    }

    /// 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);
    /// ```
    pub fn from_vec(data: Vec<u8>) -> Self {
        let len = data.len();
        Self { data, pos: 0, len }
    }

    /// Returns the total capacity of the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    ///
    /// let buf = Buffer::new(1024);
    /// assert_eq!(buf.capacity(), 1024);
    /// ```
    #[inline(always)]
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Returns the length of valid data in the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// assert_eq!(buf.len(), 0);
    ///
    /// buf.put_u32(42)?;
    /// assert_eq!(buf.len(), 4);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the buffer contains no valid data.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// assert!(buf.is_empty());
    ///
    /// buf.put_u32(42)?;
    /// assert!(!buf.is_empty());
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the current read/write position.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// assert_eq!(buf.pos(), 0);
    ///
    /// buf.put_u32(42)?;
    /// assert_eq!(buf.pos(), 4);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline(always)]
    pub fn pos(&self) -> usize {
        self.pos
    }

    /// Returns the number of bytes available to read from current position.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// 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);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline(always)]
    pub fn remaining(&self) -> usize {
        self.len.saturating_sub(self.pos)
    }

    /// Checks if at least `count` bytes are available to read.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_u32(42)?;
    /// buf.set_pos(0)?;
    ///
    /// assert!(buf.has_remaining(4));
    /// assert!(!buf.has_remaining(5));
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline(always)]
    pub fn has_remaining(&self, count: usize) -> bool {
        self.remaining() >= count
    }

    /// Sets the read/write position.
    ///
    /// # Errors
    ///
    /// Returns [`BufferError::PositionOutOfBounds`] if `pos` exceeds the buffer length.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_u32(42)?;
    /// buf.set_pos(0)?;
    ///
    /// assert_eq!(buf.get_u32()?, 42);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline]
    pub fn set_pos(&mut self, pos: usize) -> Result<()> {
        if pos > self.len {
            return Err(BufferError::PositionOutOfBounds);
        }
        self.pos = pos;
        Ok(())
    }

    /// Sets the length of valid data.
    ///
    /// When using [`with_capacity`](Self::with_capacity), this will grow the
    /// internal `Vec` if needed.
    ///
    /// # Errors
    ///
    /// Returns [`BufferError::SizeTooBig`] if `len` exceeds [`BUF_MAX_SIZE`].
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::with_capacity(1024);
    /// buf.set_len(100)?;
    /// assert_eq!(buf.len(), 100);
    /// # Ok::<(), BufferError>(())
    /// ```
    pub fn set_len(&mut self, len: usize) -> Result<()> {
        if len > BUF_MAX_SIZE {
            return Err(BufferError::SizeTooBig);
        }

        // Grow Vec if needed (for with_capacity() usage)
        if len > self.data.len() {
            self.data.resize(len, 0);
        }

        self.len = len;
        self.pos = self.pos.min(len);
        Ok(())
    }

    /// 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;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_bytes(b"hello")?;
    /// buf.set_pos(0)?;
    ///
    /// buf.incr_pos(2)?;
    /// assert_eq!(buf.pos(), 2);
    /// # Ok::<(), BufferError>(())
    /// ```
    pub fn incr_pos(&mut self, incr: usize) -> Result<()> {
        if incr > BUF_MAX_INCR || self.pos + incr > self.len {
            return Err(BufferError::IncrementTooLarge);
        }
        self.pos += incr;
        Ok(())
    }

    /// Decrements the position by `decr`.
    ///
    /// # Errors
    ///
    /// Returns [`BufferError::PositionOutOfBounds`] if `decr` exceeds the current position.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_u32(42)?;
    ///
    /// buf.decr_pos(2)?;
    /// assert_eq!(buf.pos(), 2);
    /// # Ok::<(), BufferError>(())
    /// ```
    pub fn decr_pos(&mut self, decr: usize) -> Result<()> {
        if decr > self.pos {
            return Err(BufferError::PositionOutOfBounds);
        }
        self.pos -= decr;
        Ok(())
    }

    /// Increments the length by `incr`.
    ///
    /// When using [`with_capacity`](Self::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`].
    pub fn incr_len(&mut self, incr: usize) -> Result<()> {
        if incr > BUF_MAX_INCR {
            return Err(BufferError::IncrementTooLarge);
        }

        let new_len = self.len + incr;
        if new_len > BUF_MAX_SIZE {
            return Err(BufferError::SizeTooBig);
        }

        // Grow Vec if needed
        if new_len > self.data.len() {
            self.data.resize(new_len, 0);
        }

        self.len = new_len;
        Ok(())
    }

    /// Increments the write position and updates length if needed.
    ///
    /// When using [`with_capacity`](Self::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`].
    pub fn incr_write_pos(&mut self, incr: usize) -> Result<()> {
        if incr > BUF_MAX_INCR {
            return Err(BufferError::IncrementTooLarge);
        }

        let new_pos = self.pos + incr;
        if new_pos > BUF_MAX_SIZE {
            return Err(BufferError::IncrementTooLarge);
        }

        // Grow Vec if needed
        if new_pos > self.data.len() {
            self.data.resize(new_pos, 0);
        }

        self.pos = new_pos;
        if self.pos > self.len {
            self.len = self.pos;
        }
        Ok(())
    }

    /// Resets the buffer for reuse by clearing position and length.
    ///
    /// This does not free memory or zero the contents. Use [`burn`](Self::burn)
    /// for secure erasure.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// 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);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline]
    pub fn reset(&mut self) {
        self.pos = 0;
        self.len = 0;
    }

    /// Securely zeros all buffer memory and resets position and length.
    ///
    /// Uses compiler-resistant zeroing via the [`zeroize`] crate.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_bytes(b"sensitive data")?;
    /// buf.burn();
    /// # Ok::<(), BufferError>(())
    /// ```
    pub fn burn(&mut self) {
        // Use as_mut_slice() NOT self.data.zeroize() — Vec::zeroize() calls
        // Vec::clear() which sets data.len() to 0, breaking every subsequent
        // bounds check (put_u32 checks pos + 4 > data.len()) after pool return.
        // Slice zeroize wipes the bytes but preserves data.len() == capacity.
        self.data.as_mut_slice().zeroize();
        self.pos = 0;
        self.len = 0;
    }

    /// 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;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_bytes(b"secret")?;
    /// buf.burn_free(); // Buffer consumed and securely erased
    /// # Ok::<(), BufferError>(())
    /// ```
    pub fn burn_free(mut self) {
        self.data.as_mut_slice().zeroize();
        drop(self);
    }

    /// Returns a slice of all valid data in the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_bytes(b"hello")?;
    /// assert_eq!(buf.as_slice(), b"hello");
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        &self.data[..self.len]
    }

    /// Returns a mutable slice of all valid data.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// 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");
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.data[..self.len]
    }

    /// Resizes the buffer, preserving existing data.
    ///
    /// # Errors
    ///
    /// Returns [`BufferError::SizeTooBig`] if `new_size` exceeds [`BUF_MAX_SIZE`].
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.resize(2048)?;
    /// assert_eq!(buf.capacity(), 2048);
    /// # Ok::<(), BufferError>(())
    /// ```
    pub fn resize(&mut self, new_size: usize) -> Result<()> {
        if new_size > BUF_MAX_SIZE {
            return Err(BufferError::SizeTooBig);
        }
        self.data.resize(new_size, 0);
        self.len = self.len.min(new_size);
        self.pos = self.pos.min(new_size);
        Ok(())
    }

    /// 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);
    /// ```
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.data.reserve(additional);
    }

    /// Shrinks the buffer capacity to fit the current length.
    ///
    /// Frees unused memory.
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    /// # use secbuf::BufferError;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_bytes(b"hello")?;
    /// buf.shrink_to_fit();
    /// assert_eq!(buf.capacity(), 5);
    /// # Ok::<(), BufferError>(())
    /// ```
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.data.truncate(self.len);
        self.data.shrink_to_fit();
    }

    /// Consumes the buffer and returns the underlying `Vec<u8>`,
    /// truncated to valid data length (pos..len slice).
    ///
    /// The Vec is NOT zeroed — caller takes ownership and is responsible
    /// for its lifetime. Use only for non-secret data (e.g. tunnel payloads).
    ///
    /// # Examples
    ///
    /// ```
    /// use secbuf::Buffer;
    ///
    /// let mut buf = Buffer::new(1024);
    /// buf.put_bytes(b"hello").unwrap();
    /// let v = buf.into_vec();
    /// assert_eq!(v, b"hello");
    /// ```
    pub fn into_vec(mut self) -> Vec<u8> {
        self.data.truncate(self.len); // trim to valid data only
        let mut v = Vec::new();
        std::mem::swap(&mut self.data, &mut v); // steal the allocation
        // Now self.data is empty Vec — zeroize(drop) will zeroize nothing,
        // and v holds the original allocation with real data
        v
    }
}

impl AsRef<[u8]> for Buffer {
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

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

    #[test]
    fn test_new() {
        let buf = Buffer::new(1024);
        assert_eq!(buf.capacity(), 1024);
        assert_eq!(buf.len(), 0);
        assert_eq!(buf.pos(), 0);
    }

    #[test]
    fn test_with_capacity() {
        let mut buf = Buffer::with_capacity(1024);
        assert_eq!(buf.capacity(), 1024);
        assert_eq!(buf.len(), 0);

        buf.data.extend_from_slice(b"hello");
        buf.len = 5;

        assert_eq!(buf.len(), 5);
        assert_eq!(buf.as_slice(), b"hello");
    }

    #[test]
    fn test_from_vec() {
        let data = vec![1, 2, 3, 4, 5];
        let buf = Buffer::from_vec(data);
        assert_eq!(buf.len(), 5);
        assert_eq!(buf.as_slice(), &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_incr_len_grows_vec() {
        let mut buf = Buffer::with_capacity(100);

        buf.incr_len(50).unwrap();
        assert_eq!(buf.len(), 50);
        assert!(buf.data.len() >= 50);
    }

    #[test]
    fn test_shrink_to_fit() {
        let mut buf = Buffer::new(1024);
        buf.len = 100;

        buf.shrink_to_fit();
        assert_eq!(buf.data.len(), 100);
        assert_eq!(buf.len(), 100);
    }

    #[test]
    fn test_reset() {
        let mut buf = Buffer::new(1024);
        buf.pos = 50;
        buf.len = 100;

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