//! Backward boundary detection for FASTA chunks.

use obikrope::{Rope, RopeCursor};

/// Scan the rope backward for the start of the last complete FASTA entry.
///
/// Returns the absolute byte offset of the `>` that begins the last complete
/// record, so that `rope[..offset]` is a self-contained chunk and
/// `rope[offset..]` is the remainder carried into the next chunk.
/// Returns `None` if no valid boundary is found (need more data).
pub fn end_of_last_fasta_entry(rope: &Rope) -> Option<usize> {
    let cursor = rope.bw_cursor();
    let mut state: u8 = 0;
    let mut last: usize = 0;

    for c in cursor.iter() {
        match state {
            0 if c == b'>' => {
                last = cursor.tell()?;
                state = 1;
            }
            1 if c == b'\n' || c == b'\r' => {
                if last > 0 {
                    return Some(last);
                }
                return None;
            }
            1 => {
                state = 0;
            }
            _ => {}
        }
    }
    None
}

#[cfg(test)]
#[path = "tests/fasta.rs"]
mod tests;
