pg_walstream 0.6.3

PostgreSQL logical replication protocol library - parse and handle PostgreSQL WAL streaming messages
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Buffer utilities for reading and writing replication protocol messages
//!
//! This module provides safe wrappers for reading and writing binary data
//! in PostgreSQL's logical replication protocol format using the bytes crate.

use crate::error::{ReplicationError, Result};
use bytes::{Buf, BufMut, Bytes, BytesMut};

/// Buffer reader for parsing binary protocol messages
///
/// This implementation uses the `bytes` crate for efficient, zero-copy buffer operations.
/// It provides safe methods for reading various integer types, strings, and byte arrays
/// from PostgreSQL's binary protocol format (network byte order / big-endian).
///
/// # Example
///
/// ```
/// use pg_walstream::BufferReader;
///
/// let data = vec![0x00, 0x01, 0x02, 0x03];
/// let mut reader = BufferReader::new(&data);
///
/// let byte = reader.read_u8().unwrap();
/// assert_eq!(byte, 0x00);
///
/// let remaining = reader.remaining();
/// assert_eq!(remaining, 3);
/// ```
pub struct BufferReader {
    data: Bytes,
}

impl BufferReader {
    /// Create a new buffer reader from a byte slice
    ///
    /// Copies the provided byte slice into an internal Bytes buffer.
    /// For zero-copy operation with existing Bytes, use `from_bytes()` instead.
    ///
    /// # Arguments
    ///
    /// * `data` - Byte slice to read from
    ///
    /// # Example
    ///
    /// ```
    /// use pg_walstream::BufferReader;
    ///
    /// let data = vec![0x01, 0x02, 0x03, 0x04];
    /// let reader = BufferReader::new(&data);
    /// ```
    #[inline]
    pub fn new(data: &[u8]) -> Self {
        Self {
            data: Bytes::copy_from_slice(data),
        }
    }

    /// Create a new buffer reader from Bytes
    #[inline]
    pub fn from_bytes(data: Bytes) -> Self {
        Self { data }
    }

    #[inline]
    pub fn from_vec(data: Vec<u8>) -> Self {
        Self {
            data: Bytes::from(data),
        }
    }

    /// Get current position in the buffer
    #[inline]
    pub fn position(&self) -> usize {
        self.data.len()
    }

    /// Get remaining bytes in the buffer
    #[inline]
    pub fn remaining(&self) -> usize {
        self.data.remaining()
    }

    /// Check if there are enough bytes remaining
    #[inline]
    fn ensure_bytes(&self, count: usize) -> Result<()> {
        if self.data.remaining() < count {
            return Self::short_buffer_err(count, self.data.remaining());
        }
        Ok(())
    }

    #[cold]
    #[inline(never)]
    fn short_buffer_err(needed: usize, have: usize) -> Result<()> {
        Err(ReplicationError::protocol(format!(
            "Not enough bytes remaining. Need {needed}, have {have}"
        )))
    }

    /// Read a single byte
    ///
    /// # Returns
    ///
    /// Returns the next byte from the buffer.
    ///
    /// # Errors
    ///
    /// Returns an error if there are insufficient bytes remaining in the buffer.
    #[inline]
    pub fn read_u8(&mut self) -> Result<u8> {
        self.ensure_bytes(1)?;
        Ok(self.data.get_u8())
    }

    /// Read a 16-bit unsigned integer in network byte order
    ///
    /// Reads 2 bytes and interprets them as a big-endian u16.
    ///
    /// # Returns
    ///
    /// Returns the next 16-bit unsigned integer.
    ///
    /// # Errors
    ///
    /// Returns an error if there are insufficient bytes remaining.
    #[inline]
    pub fn read_u16(&mut self) -> Result<u16> {
        self.ensure_bytes(2)?;
        Ok(self.data.get_u16())
    }

    /// Read a 32-bit unsigned integer in network byte order
    ///
    /// Reads 4 bytes and interprets them as a big-endian u32.
    ///
    /// # Returns
    ///
    /// Returns the next 32-bit unsigned integer.
    ///
    /// # Errors
    ///
    /// Returns an error if there are insufficient bytes remaining.
    #[inline]
    pub fn read_u32(&mut self) -> Result<u32> {
        self.ensure_bytes(4)?;
        Ok(self.data.get_u32())
    }

    /// Read a 64-bit unsigned integer in network byte order
    ///
    /// Reads 8 bytes and interprets them as a big-endian u64.
    /// This is commonly used for reading LSN values.
    ///
    /// # Returns
    ///
    /// Returns the next 64-bit unsigned integer.
    ///
    /// # Errors
    ///
    /// Returns an error if there are insufficient bytes remaining.
    #[inline]
    pub fn read_u64(&mut self) -> Result<u64> {
        self.ensure_bytes(8)?;
        Ok(self.data.get_u64())
    }

    /// Read a 16-bit signed integer in network byte order
    #[inline]
    pub fn read_i16(&mut self) -> Result<i16> {
        self.ensure_bytes(2)?;
        Ok(self.data.get_i16())
    }

    /// Read a 32-bit signed integer in network byte order
    #[inline]
    pub fn read_i32(&mut self) -> Result<i32> {
        self.ensure_bytes(4)?;
        Ok(self.data.get_i32())
    }

    /// Read a 64-bit signed integer in network byte order
    #[inline]
    pub fn read_i64(&mut self) -> Result<i64> {
        self.ensure_bytes(8)?;
        Ok(self.data.get_i64())
    }

    /// Read a null-terminated string
    #[inline]
    pub fn read_cstring(&mut self) -> Result<String> {
        let data_slice = self.data.chunk();

        // Find the null terminator using SIMD-accelerated scanning
        let bytes_to_read = memchr::memchr(0, data_slice).ok_or_else(|| {
            ReplicationError::protocol("Unterminated string in buffer".to_string())
        })?;

        // Validate UTF-8 on the borrowed slice (zero-copy), then create one owned String
        let result = std::str::from_utf8(&data_slice[..bytes_to_read])
            .map_err(|e| ReplicationError::protocol(format!("Invalid UTF-8 in string: {e}")))?
            .to_owned();

        // Advance past the string bytes and the null terminator
        self.data.advance(bytes_to_read + 1);

        Ok(result)
    }

    /// Read a fixed-length string without null terminator
    #[inline]
    pub fn read_string(&mut self, length: usize) -> Result<String> {
        self.ensure_bytes(length)?;
        let result = std::str::from_utf8(&self.data.chunk()[..length])
            .map_err(|e| ReplicationError::protocol(format!("Invalid UTF-8 in string: {e}")))?
            .to_owned();
        self.data.advance(length);
        Ok(result)
    }

    /// Read raw bytes
    #[inline]
    pub fn read_bytes(&mut self, length: usize) -> Result<Vec<u8>> {
        self.ensure_bytes(length)?;
        let mut out = vec![0u8; length];
        self.data.copy_to_slice(&mut out);
        Ok(out)
    }

    /// Get raw bytes as Bytes (zero-copy when possible)
    #[inline]
    pub fn read_bytes_buf(&mut self, length: usize) -> Result<Bytes> {
        self.ensure_bytes(length)?;
        Ok(self.data.copy_to_bytes(length))
    }

    /// Peek at the next byte without advancing position
    #[inline]
    pub fn peek_u8(&self) -> Result<u8> {
        self.ensure_bytes(1)?;
        Ok(self.data.chunk()[0])
    }

    /// Skip n bytes
    #[inline]
    pub fn skip(&mut self, count: usize) -> Result<()> {
        self.ensure_bytes(count)?;
        self.data.advance(count);
        Ok(())
    }
}

/// Buffer writer for creating binary protocol messages
///
/// This implementation uses BytesMut from the bytes crate for efficient buffer operations.
pub struct BufferWriter {
    data: BytesMut,
}

impl BufferWriter {
    /// Create a new buffer writer with initial capacity
    pub fn new() -> Self {
        Self {
            data: BytesMut::new(),
        }
    }

    /// Create a new buffer writer with specified capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            data: BytesMut::with_capacity(capacity),
        }
    }

    /// Get current position in the buffer
    pub fn position(&self) -> usize {
        self.data.len()
    }

    /// Get bytes written so far
    pub fn bytes_written(&self) -> usize {
        self.data.len()
    }

    /// Get the data as bytes
    pub fn freeze(self) -> Bytes {
        self.data.freeze()
    }

    /// Get the data as a `Vec<u8>`
    pub fn into_vec(self) -> Vec<u8> {
        self.data.to_vec()
    }

    /// Write a single byte
    pub fn write_u8(&mut self, value: u8) -> Result<()> {
        self.data.put_u8(value);
        Ok(())
    }

    /// Write a 16-bit unsigned integer in network byte order
    pub fn write_u16(&mut self, value: u16) -> Result<()> {
        self.data.put_u16(value);
        Ok(())
    }

    /// Write a 16-bit signed integer in network byte order
    pub fn write_i16(&mut self, value: i16) -> Result<()> {
        self.data.put_i16(value);
        Ok(())
    }

    /// Write a 32-bit unsigned integer in network byte order
    pub fn write_u32(&mut self, value: u32) -> Result<()> {
        self.data.put_u32(value);
        Ok(())
    }

    /// Write a 64-bit unsigned integer in network byte order
    pub fn write_u64(&mut self, value: u64) -> Result<()> {
        self.data.put_u64(value);
        Ok(())
    }

    /// Write a 32-bit signed integer in network byte order
    pub fn write_i32(&mut self, value: i32) -> Result<()> {
        self.data.put_i32(value);
        Ok(())
    }

    /// Write a 64-bit signed integer in network byte order
    pub fn write_i64(&mut self, value: i64) -> Result<()> {
        self.data.put_i64(value);
        Ok(())
    }

    /// Write raw bytes
    pub fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
        self.data.put_slice(bytes);
        Ok(())
    }

    /// Write a null-terminated string
    ///
    /// Rejects strings containing embedded null bytes, which would produce
    /// malformed PostgreSQL protocol messages (the null byte is the terminator).
    pub fn write_cstring(&mut self, s: &str) -> Result<()> {
        if s.as_bytes().contains(&0) {
            return Err(ReplicationError::protocol(
                "string contains embedded null byte".to_string(),
            ));
        }
        self.data.put_slice(s.as_bytes());
        self.data.put_u8(0);
        Ok(())
    }

    /// Write a string without null terminator
    pub fn write_string(&mut self, s: &str) -> Result<()> {
        self.data.put_slice(s.as_bytes());
        Ok(())
    }

    /// Reserve capacity for at least additional bytes
    pub fn reserve(&mut self, additional: usize) {
        self.data.reserve(additional);
    }

    /// Clear the buffer, resetting length to 0
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Get remaining capacity
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Get a reference to the internal data  
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }
}

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

impl Default for BufferWriter {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_buffer_reader_basic() {
        let data = [0x01, 0x02, 0x03, 0x04];
        let mut reader = BufferReader::new(&data);

        assert_eq!(reader.read_u8().unwrap(), 0x01);
        assert_eq!(reader.read_u8().unwrap(), 0x02);
        assert_eq!(reader.remaining(), 2);
    }

    #[test]
    fn test_buffer_reader_u16() {
        let data = [0x01, 0x02];
        let mut reader = BufferReader::new(&data);
        assert_eq!(reader.read_u16().unwrap(), 0x0102);
    }

    #[test]
    fn test_buffer_reader_u32() {
        let data = [0x01, 0x02, 0x03, 0x04];
        let mut reader = BufferReader::new(&data);
        assert_eq!(reader.read_u32().unwrap(), 0x01020304);
    }

    #[test]
    fn test_buffer_writer_basic() {
        let mut writer = BufferWriter::new();

        writer.write_u8(0x01).unwrap();
        writer.write_u16(0x0203).unwrap();
        writer.write_u32(0x04050607).unwrap();

        assert_eq!(writer.bytes_written(), 7);

        let data = writer.freeze();
        assert_eq!(&data[..], &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]);
    }

    #[test]
    fn test_buffer_reader_strings() {
        let data = b"hello\x00world";
        let mut reader = BufferReader::new(data);

        let s = reader.read_cstring().unwrap();
        assert_eq!(s, "hello");

        let s2 = reader.read_string(5).unwrap();
        assert_eq!(s2, "world");
    }

    #[test]
    fn test_buffer_writer_strings() {
        let mut writer = BufferWriter::new();

        writer.write_cstring("hello").unwrap();
        writer.write_string("world").unwrap();

        let data = writer.freeze();
        assert_eq!(&data[..], b"hello\x00world");
    }

    #[test]
    fn test_buffer_reader_zero_copy() {
        let data = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        let bytes = Bytes::from(data);
        let mut reader = BufferReader::from_bytes(bytes);

        let chunk = reader.read_bytes_buf(3).unwrap();
        assert_eq!(&chunk[..], &[0x01, 0x02, 0x03]);
        assert_eq!(reader.remaining(), 2);
    }

    #[test]
    fn test_buffer_reader_signed_integers() {
        // Test i16
        let data = [0xFF, 0xFE]; // -2 in two's complement
        let mut reader = BufferReader::new(&data);
        assert_eq!(reader.read_i16().unwrap(), -2);

        // Test i32
        let data = [0xFF, 0xFF, 0xFF, 0xFE]; // -2 in two's complement
        let mut reader = BufferReader::new(&data);
        assert_eq!(reader.read_i32().unwrap(), -2);

        // Test i64
        let data = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE]; // -2
        let mut reader = BufferReader::new(&data);
        assert_eq!(reader.read_i64().unwrap(), -2);
    }

    #[test]
    fn test_buffer_reader_peek() {
        let data = [0x01, 0x02, 0x03];
        let mut reader = BufferReader::new(&data);

        // Peek should not advance position
        assert_eq!(reader.peek_u8().unwrap(), 0x01);
        assert_eq!(reader.remaining(), 3);
        assert_eq!(reader.peek_u8().unwrap(), 0x01);

        // Read should advance position
        assert_eq!(reader.read_u8().unwrap(), 0x01);
        assert_eq!(reader.remaining(), 2);
        assert_eq!(reader.peek_u8().unwrap(), 0x02);
    }

    #[test]
    fn test_buffer_reader_skip() {
        let data = [0x01, 0x02, 0x03, 0x04, 0x05];
        let mut reader = BufferReader::new(&data);

        reader.skip(2).unwrap();
        assert_eq!(reader.remaining(), 3);
        assert_eq!(reader.read_u8().unwrap(), 0x03);

        reader.skip(1).unwrap();
        assert_eq!(reader.read_u8().unwrap(), 0x05);
    }

    #[test]
    fn test_buffer_reader_errors() {
        let data = [0x01, 0x02];
        let mut reader = BufferReader::new(&data);

        // Try to read more bytes than available
        assert!(reader.read_u32().is_err());
        assert!(reader.read_u64().is_err());

        // After error, buffer should still be valid
        assert_eq!(reader.read_u8().unwrap(), 0x01);
    }

    #[test]
    fn test_buffer_reader_unterminated_string() {
        let data = b"hello world"; // No null terminator
        let mut reader = BufferReader::new(data);

        let result = reader.read_cstring();
        assert!(result.is_err());
    }

    #[test]
    fn test_buffer_reader_invalid_utf8() {
        let data = [0xFF, 0xFE, 0x00]; // Invalid UTF-8 followed by null
        let mut reader = BufferReader::new(&data);

        let result = reader.read_cstring();
        assert!(result.is_err());
    }

    #[test]
    fn test_buffer_reader_cstring_empty_string() {
        // Null byte at start → empty string
        let data = [0x00, 0x01, 0x02];
        let mut reader = BufferReader::new(&data);
        let s = reader.read_cstring().unwrap();
        assert_eq!(s, "");
        assert_eq!(reader.remaining(), 2); // consumed 1 byte (the null)
    }

    #[test]
    fn test_buffer_reader_cstring_consecutive() {
        // Two back-to-back C strings
        let data = b"hello\x00world\x00";
        let mut reader = BufferReader::new(data);
        assert_eq!(reader.read_cstring().unwrap(), "hello");
        assert_eq!(reader.read_cstring().unwrap(), "world");
        assert_eq!(reader.remaining(), 0);
    }

    #[test]
    fn test_buffer_reader_cstring_long_string() {
        // 256-byte string — tests memchr SIMD vectorization beyond a single 16/32-byte lane
        let mut data = vec![b'A'; 256];
        data.push(0x00);
        let mut reader = BufferReader::new(&data);
        let s = reader.read_cstring().unwrap();
        assert_eq!(s.len(), 256);
        assert!(s.chars().all(|c| c == 'A'));
        assert_eq!(reader.remaining(), 0);
    }

    #[test]
    fn test_buffer_reader_cstring_from_bytes_zero_copy() {
        // Verify read_cstring works correctly via from_bytes (zero-copy path)
        let data = Bytes::from_static(b"test\x00rest");
        let mut reader = BufferReader::from_bytes(data);
        assert_eq!(reader.read_cstring().unwrap(), "test");
        assert_eq!(reader.remaining(), 4); // "rest"
    }

    #[test]
    fn test_buffer_reader_from_vec() {
        let data = vec![0x01, 0x02, 0x03];
        let mut reader = BufferReader::from_vec(data);

        assert_eq!(reader.read_u8().unwrap(), 0x01);
        assert_eq!(reader.remaining(), 2);
    }

    #[test]
    fn test_buffer_writer_signed_integers() {
        let mut writer = BufferWriter::new();

        writer.write_i16(-2).unwrap();
        writer.write_i32(-2).unwrap();
        writer.write_i64(-2).unwrap();

        let data = writer.freeze();
        assert_eq!(data.len(), 2 + 4 + 8);

        let mut reader = BufferReader::from_bytes(data);
        assert_eq!(reader.read_i16().unwrap(), -2);
        assert_eq!(reader.read_i32().unwrap(), -2);
        assert_eq!(reader.read_i64().unwrap(), -2);
    }

    #[test]
    fn test_buffer_writer_with_capacity() {
        let mut writer = BufferWriter::with_capacity(100);
        writer.write_u64(0x0102030405060708).unwrap();
        assert_eq!(writer.bytes_written(), 8);
    }

    #[test]
    fn test_buffer_writer_bytes() {
        let mut writer = BufferWriter::new();
        writer.write_bytes(&[0x01, 0x02, 0x03]).unwrap();
        writer.write_bytes(&[0x04, 0x05]).unwrap();

        let data = writer.freeze();
        assert_eq!(&data[..], &[0x01, 0x02, 0x03, 0x04, 0x05]);
    }

    #[test]
    fn test_buffer_reader_read_bytes() {
        let data = [0x01, 0x02, 0x03, 0x04, 0x05];
        let mut reader = BufferReader::new(&data);

        let bytes = reader.read_bytes(3).unwrap();
        assert_eq!(bytes, vec![0x01, 0x02, 0x03]);
        assert_eq!(reader.remaining(), 2);
    }

    #[test]
    fn test_buffer_empty() {
        let data: &[u8] = &[];
        let mut reader = BufferReader::new(data);

        assert_eq!(reader.remaining(), 0);
        assert!(reader.read_u8().is_err());
        assert!(reader.peek_u8().is_err());
    }

    #[test]
    fn test_buffer_reader_from_bytes() {
        let bytes = Bytes::from_static(&[0x01, 0x02, 0x03]);
        let mut reader = BufferReader::from_bytes(bytes);
        assert_eq!(reader.read_u8().unwrap(), 0x01);
        assert_eq!(reader.remaining(), 2);
    }

    #[test]
    fn test_buffer_reader_from_vec_full() {
        let data = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let mut reader = BufferReader::from_vec(data);
        assert_eq!(reader.read_u32().unwrap(), 0xAABBCCDD);
        assert_eq!(reader.remaining(), 0);
    }

    #[test]
    fn test_buffer_writer_write_i16() {
        let mut writer = BufferWriter::new();
        writer.write_i16(0x1234).unwrap();
        let data = writer.freeze();
        assert_eq!(&data[..], &[0x12, 0x34]);
    }

    #[test]
    fn test_buffer_writer_write_i32() {
        let mut writer = BufferWriter::new();
        writer.write_i32(0x12345678).unwrap();
        let data = writer.freeze();
        assert_eq!(&data[..], &[0x12, 0x34, 0x56, 0x78]);
    }

    #[test]
    fn test_buffer_writer_write_i64() {
        let mut writer = BufferWriter::new();
        writer.write_i64(0x0102030405060708).unwrap();
        let data = writer.freeze();
        assert_eq!(&data[..], &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]);
    }

    #[test]
    fn test_buffer_writer_write_cstring() {
        let mut writer = BufferWriter::new();
        writer.write_cstring("test").unwrap();
        let data = writer.freeze();
        assert_eq!(&data[..], b"test\x00");
    }

    #[test]
    fn test_buffer_writer_write_cstring_rejects_embedded_null() {
        let mut writer = BufferWriter::new();
        let result = writer.write_cstring("hello\x00world");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("embedded null"),
            "Expected embedded null error, got: {err}"
        );
    }

    #[test]
    fn test_buffer_writer_write_string() {
        let mut writer = BufferWriter::new();
        writer.write_string("hello").unwrap();
        let data = writer.freeze();
        assert_eq!(&data[..], b"hello");
    }

    #[test]
    fn test_buffer_writer_reserve() {
        let mut writer = BufferWriter::new();
        writer.reserve(1024);
        assert!(writer.capacity() >= 1024);
    }

    #[test]
    fn test_buffer_writer_clear() {
        let mut writer = BufferWriter::new();
        writer.write_u8(0x01).unwrap();
        writer.write_u8(0x02).unwrap();
        assert_eq!(writer.bytes_written(), 2);

        writer.clear();
        assert_eq!(writer.bytes_written(), 0);
        assert_eq!(writer.position(), 0);
    }

    #[test]
    fn test_buffer_writer_capacity() {
        let writer = BufferWriter::with_capacity(256);
        assert!(writer.capacity() >= 256);
    }

    #[test]
    fn test_buffer_writer_as_bytes() {
        let mut writer = BufferWriter::new();
        writer.write_u8(0xAA).unwrap();
        writer.write_u8(0xBB).unwrap();
        assert_eq!(writer.as_bytes(), &[0xAA, 0xBB]);
    }

    #[test]
    fn test_buffer_writer_as_ref() {
        let mut writer = BufferWriter::new();
        writer.write_u8(0x01).unwrap();
        let slice: &[u8] = writer.as_ref();
        assert_eq!(slice, &[0x01]);
    }

    #[test]
    fn test_buffer_writer_default() {
        let mut writer = BufferWriter::default();
        writer.write_u8(0xFF).unwrap();
        assert_eq!(writer.bytes_written(), 1);
    }

    #[test]
    fn test_buffer_writer_into_vec() {
        let mut writer = BufferWriter::new();
        writer.write_u8(0x01).unwrap();
        writer.write_u16(0x0203).unwrap();
        let vec = writer.into_vec();
        assert_eq!(vec, vec![0x01, 0x02, 0x03]);
    }

    #[test]
    fn test_buffer_reader_u64() {
        let data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
        let mut reader = BufferReader::new(&data);
        assert_eq!(reader.read_u64().unwrap(), 0x0102030405060708);
    }

    #[test]
    fn test_buffer_reader_position() {
        let data = [0x01, 0x02, 0x03, 0x04];
        let reader = BufferReader::new(&data);
        // position returns data.len() which is the remaining bytes
        assert_eq!(reader.position(), 4);
    }

    #[test]
    fn test_buffer_writer_position() {
        let mut writer = BufferWriter::new();
        assert_eq!(writer.position(), 0);
        writer.write_u32(0x12345678).unwrap();
        assert_eq!(writer.position(), 4);
    }

    #[test]
    fn test_buffer_roundtrip_complex() {
        let mut writer = BufferWriter::new();
        writer.write_u8(0x42).unwrap();
        writer.write_u16(0x1234).unwrap();
        writer.write_u32(0xDEADBEEF).unwrap();
        writer.write_u64(0xCAFEBABE12345678).unwrap();
        writer.write_i16(-100).unwrap();
        writer.write_i32(-200).unwrap();
        writer.write_i64(-300).unwrap();
        writer.write_cstring("hello").unwrap();
        writer.write_bytes(&[0x01, 0x02]).unwrap();

        let data = writer.freeze();
        let mut reader = BufferReader::from_bytes(data);

        assert_eq!(reader.read_u8().unwrap(), 0x42);
        assert_eq!(reader.read_u16().unwrap(), 0x1234);
        assert_eq!(reader.read_u32().unwrap(), 0xDEADBEEF);
        assert_eq!(reader.read_u64().unwrap(), 0xCAFEBABE12345678);
        assert_eq!(reader.read_i16().unwrap(), -100);
        assert_eq!(reader.read_i32().unwrap(), -200);
        assert_eq!(reader.read_i64().unwrap(), -300);
        assert_eq!(reader.read_cstring().unwrap(), "hello");
        assert_eq!(reader.read_bytes(2).unwrap(), vec![0x01, 0x02]);
        assert_eq!(reader.remaining(), 0);
    }

    #[test]
    fn test_buffer_reader_skip_insufficient() {
        let data = [0x01, 0x02];
        let mut reader = BufferReader::new(&data);
        assert!(reader.skip(5).is_err());
    }

    #[test]
    fn test_buffer_reader_read_string_insufficient() {
        let data = [0x01, 0x02];
        let mut reader = BufferReader::new(&data);
        assert!(reader.read_string(5).is_err());
    }

    #[test]
    fn test_buffer_reader_read_bytes_insufficient() {
        let data = [0x01];
        let mut reader = BufferReader::new(&data);
        assert!(reader.read_bytes(5).is_err());
    }

    #[test]
    fn test_buffer_reader_read_bytes_buf_insufficient() {
        let data = [0x01];
        let mut reader = BufferReader::new(&data);
        assert!(reader.read_bytes_buf(5).is_err());
    }

    /// Pin the error message format produced by the `#[cold]`
    /// `short_buffer_err` helper. Several layers above (parser, stream)
    /// surface this string in logs, so format regressions would silently
    /// degrade diagnostics.
    #[test]
    fn test_buffer_reader_short_buffer_err_message_format() {
        let data = [0x01, 0x02];
        let mut reader = BufferReader::new(&data);
        let err = reader.read_bytes_buf(5).unwrap_err();
        let s = err.to_string();
        assert!(
            s.contains("Not enough bytes remaining"),
            "expected 'Not enough bytes remaining' in error, got: {s}"
        );
        assert!(s.contains("Need 5"), "expected 'Need 5', got: {s}");
        assert!(s.contains("have 2"), "expected 'have 2', got: {s}");
    }
}