Skip to main content

BufferSource

Struct BufferSource 

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

Source implementation for reading bencode data from a memory buffer In-memory byte vector input source supporting both binary byte streaming and Unicode UTF-8 character streaming.

Implementations§

Source§

impl BufferSource

Source

pub fn new(data: &[u8]) -> BufferSource

Creates a new BufferSource from a byte slice.

Examples found in repository?
examples/bencode_iterative.rs (line 21)
14fn main() {
15    println!("=== Iterative Parser Demo ===\n");
16
17    // Example 1: Simple parsing comparison
18    println!("1. Simple structure:");
19    let simple = b"d3:agei25e4:name4:Johne";
20
21    let mut source = BufferSource::new(simple);
22    match parse_iterative(&mut source) {
23        Ok(node) => {
24            println!("   Parsed successfully with iterative parser");
25            if let Ok(output) = stringify_to_bytes(&node) {
26                println!("   Output: {}", String::from_utf8_lossy(&output));
27            }
28        }
29        Err(e) => println!("   Error: {}", e),
30    }
31
32    // Example 2: Deeply nested lists
33    println!("\n2. Deeply nested structure (100 levels):");
34    let mut deeply_nested = String::from("i42e");
35    for _ in 0..100 {
36        deeply_nested = format!("l{}e", deeply_nested);
37    }
38    println!("   Created nested list with {} bytes", deeply_nested.len());
39
40    // Try with iterative parser (should work)
41    match babbel_bencode::parse_bytes_iterative(deeply_nested.as_bytes()) {
42        Ok(_) => println!("   ✓ Iterative parser succeeded"),
43        Err(e) => println!("   ✗ Iterative parser failed: {}", e),
44    }
45
46    // Try with recursive parser (works but uses more stack)
47    match babbel_bencode::parse_bytes(deeply_nested.as_bytes()) {
48        Ok(_) => println!("   ✓ Recursive parser succeeded (but used more stack)"),
49        Err(e) => println!("   ✗ Recursive parser failed: {}", e),
50    }
51
52    // Example 3: Very deeply nested (1000 levels) - only iterative should handle well
53    println!("\n3. Very deeply nested structure (1000 levels):");
54    let mut very_deep = String::from("i1e");
55    for _ in 0..1000 {
56        very_deep = format!("l{}e", very_deep);
57    }
58    println!("   Created nested list with {} bytes", very_deep.len());
59
60    match babbel_bencode::parse_bytes_iterative(very_deep.as_bytes()) {
61        Ok(_) => println!("   ✓ Iterative parser succeeded (no stack issues)"),
62        Err(e) => println!("   ✗ Iterative parser failed: {}", e),
63    }
64
65    // Example 4: Complex nested dictionary
66    println!("\n4. Complex nested dictionary:");
67    let complex = b"d4:infod6:lengthi123e4:name9:test.file12:piece lengthi16384eee";
68
69    let mut source = BufferSource::new(complex);
70    match parse_iterative(&mut source) {
71        Ok(node) => {
72            println!("   Parsed complex structure successfully");
73            if let Ok(output) = stringify_to_bytes(&node) {
74                println!("   Size: {} bytes", output.len());
75            }
76        }
77        Err(e) => println!("   Error: {}", e),
78    }
79
80    // Example 5: Deeply nested mixed structure
81    println!("\n5. Mixed nested structure:");
82    let mixed = b"d4:dictd1:ai1e1:bi2ee4:listlli1ei2eeli3ei4eeee";
83
84    let mut source = BufferSource::new(mixed);
85    match parse_iterative(&mut source) {
86        Ok(node) => {
87            println!("   Parsed mixed nested structure");
88            if let Ok(output) = stringify_to_bytes(&node) {
89                println!("   Output: {}", String::from_utf8_lossy(&output));
90            }
91        }
92        Err(e) => println!("   Error: {}", e),
93    }
94
95    println!("\n=== Advantages of Iterative Parser ===");
96    println!("✓ No recursion - uses explicit stack on heap");
97    println!("✓ Safe for deeply nested structures (>1000 levels)");
98    println!("✓ Predictable memory usage");
99    println!("✓ Ideal for embedded systems with limited stack space");
100    println!("✓ Same functionality as recursive parser");
101}
Source

pub fn from_vec(buffer: Vec<u8>) -> BufferSource

Creates a new BufferSource by taking ownership of a byte vector (zero-copy).

Source

pub fn next(&mut self)

Advances to the next character.

Source

pub fn current(&mut self) -> Option<char>

Returns the character at the current position.

Source

pub fn more(&mut self) -> bool

Checks if more characters are available.

Source

pub fn reset(&mut self)

Resets the position to 0.

Source

pub fn to_string(&self) -> String

Converts the buffer to a UTF-8 string.

Source

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

Returns a slice of the underlying buffer.

Source

pub fn position(&self) -> usize

Returns current byte offset.

Source

pub fn read_line(&mut self) -> Option<String>

Reads the next line into a String without trailing newline.

Source

pub fn read_line_into(&mut self, buf: &mut String) -> bool

Reads the next line into an existing buffer. Returns false at EOF.

Source

pub fn peek_byte(&mut self) -> Option<u8>

Peeks at current byte without advancing.

Source

pub fn read_byte(&mut self) -> Option<u8>

Reads current byte and advances position by one byte.

Source

pub fn advance(&mut self)

Advances position by one byte.

Source

pub fn has_more(&mut self) -> bool

Checks if there are more bytes available.

Trait Implementations§

Source§

impl Clone for BufferSource

Source§

fn clone(&self) -> BufferSource

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for BufferSource

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for BufferSource

Source§

fn default() -> BufferSource

Returns the “default value” for a type. Read more
Source§

impl IByteReader for BufferSource

Source§

fn read_byte(&mut self) -> Option<u8>

Reads current byte and advances position by one byte.
Source§

impl ICharStream for BufferSource

Source§

fn next(&mut self)

Advances reading position to next character.
Source§

fn current(&mut self) -> Option<char>

Returns character at current position.
Source§

fn more(&mut self) -> bool

Checks if more characters are available.
Source§

impl IIndentationAware for BufferSource

Source§

fn get_current_indent_level(&self) -> usize

Returns current indentation level (number of spaces or tab-stops).
Source§

fn is_indent_whitespace(&self, c: char) -> bool

Checks if character is considered indentation whitespace.
Source§

fn is_whitespace(&self, c: char) -> bool

Checks if character is whitespace (space or tab).
Source§

fn is_tab(&self, c: char) -> bool

Checks if character is a tab.
Source§

impl ILineReader for BufferSource

Source§

fn read_line_into(&mut self, buf: &mut String) -> bool

Reads the next line into an existing buffer to avoid heap allocations. Appends the line content without newline characters to buf. Returns true if a line (including an empty line) was read, false at EOF.
Source§

fn read_line(&mut self) -> Option<String>

Reads the next line up to \n or \r\n (or lone \r), returning it without trailing newline. Returns None when end of stream is reached and no characters were read.
Source§

fn lines(&mut self) -> LineIter<'_, Self> ⓘ
where Self: Sized,

Returns an iterator yielding lines from this stream.
Source§

impl ILocationAware for BufferSource

Source§

fn line(&self) -> usize

Returns 1-based line index.
Source§

fn column(&self) -> usize

Returns 1-based column index.
Source§

impl IPeekable for BufferSource

Source§

fn peek_byte(&mut self) -> Option<u8>

Peeks at current byte without advancing.
Source§

impl IPositionAware for BufferSource

Source§

fn position(&self) -> usize

Returns current absolute byte offset.
Source§

impl IRewindable for BufferSource

Source§

fn reset(&mut self)

Resets reading position to the beginning.
Source§

impl ISource for BufferSource

Source§

fn next(&mut self)

Advances reading position to next character.
Source§

fn current(&mut self) -> Option<char>

Returns character at current position.
Source§

fn more(&mut self) -> bool

Checks if more characters are available.
Source§

fn reset(&mut self)

Resets reading position to the beginning (default: no-op for forward-only streams).
Source§

fn can_rewind(&self) -> bool

Whether this source supports rewinding to the beginning.
Source§

impl ISource for Buffer

Source§

fn next(&mut self)

Advances the reading position to the next character.
Source§

fn current(&mut self) -> Option<char>

Returns the character at the current reading position.
Source§

fn more(&mut self) -> bool

Checks if there are more characters available to read.
Source§

impl IStatefulStream for BufferSource

Source§

fn save_state(&mut self) -> SaveState

Snapshots the source read position and metadata.
Source§

fn restore_state(&mut self, state: SaveState)

Restores a previously saved state.
Source§

impl RewindableRead for Buffer

Source§

fn reset(&mut self)

Resets the reading position to the beginning of the source.

Auto Trait Implementations§

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> IByteStream for T
where T: IByteReader + IPeekable + ?Sized,

Source§

fn advance(&mut self)

Advances position by one byte.
Source§

fn has_more(&mut self) -> bool

Checks if there are more bytes available.
Source§

impl<T> ICharReader for T
where T: ICharStream + ?Sized,

Source§

impl<T> ITracked for T

Source§

fn offset(&self) -> usize

Returns current absolute byte offset (delegates to IPositionAware::position).
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> 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 = !

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

fn try_from(value: U) -> Result<T, !>

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.