rpi-tools 0.35.0

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
Documentation
//! Bounded text previews with the same split and truncation metadata as an
//! eager UTF-8-lossy read. Exact line counts still require scanning the file.

use super::{start_line, ReadInput};
use crate::env::ReadFile;
use crate::error::FileError;
use crate::truncate::{
    truncate_head, TruncationLimit, TruncationOptions, TruncationResult, DEFAULT_MAX_BYTES,
};

pub(super) const READ_CHUNK_BYTES: usize = 64 * 1024;
const COUNT_CHUNK_BYTES: usize = 1024 * 1024;

pub(super) struct TextPage {
    pub(super) truncation: TruncationResult,
    pub(super) file_lines: usize,
    pub(super) selected_lines: usize,
    pub(super) first_line_bytes: usize,
}

pub(super) async fn read_text_preview(
    file: &dyn ReadFile,
    length: u64,
    mut bytes: Vec<u8>,
    input: &ReadInput,
) -> Result<TextPage, FileError> {
    let mut preview = TextPreview::new(input);
    let mut offset = bytes.len() as u64;
    let mut decoder = encoding_rs::UTF_8.new_decoder_without_bom_handling();
    let mut decoded = String::new();
    loop {
        let last = offset == length;
        if preview.selection_complete() {
            // An ASCII newline is preserved by lossy UTF-8 decoding, so
            // the unselected suffix only needs a raw byte count.
            preview.file_lines += memchr::memchr_iter(b'\n', &bytes).count();
        } else {
            decoded.clear();
            let capacity = decoder
                .max_utf8_buffer_length(bytes.len())
                .expect("text chunks are bounded to 64 KiB");
            decoded.reserve(capacity);
            let (result, consumed, _) = decoder.decode_to_string(&bytes, &mut decoded, last);
            debug_assert_eq!(result, encoding_rs::CoderResult::InputEmpty);
            debug_assert_eq!(consumed, bytes.len());
            preview.push(&decoded);
        }
        if last {
            return Ok(preview.finish());
        }
        let chunk_size = if preview.selection_complete() {
            COUNT_CHUNK_BYTES
        } else {
            READ_CHUNK_BYTES
        };
        let count = (length - offset).min(chunk_size as u64) as usize;
        bytes = file.read_range(offset, count).await?;
        offset += bytes.len() as u64;
    }
}

struct TextPreview {
    start: usize,
    end: usize,
    // The eager read uses split('\n'), including the final empty item.
    file_lines: usize,
    selected_bytes: usize,
    selected_newlines: usize,
    ends_with_newline: bool,
    first_line_bytes: usize,
    prefix: String,
}

impl TextPreview {
    fn new(input: &ReadInput) -> Self {
        let start = start_line(input);
        Self {
            start,
            end: input
                .limit
                .map_or(usize::MAX, |limit| start.saturating_add(limit as usize)),
            file_lines: 1,
            selected_bytes: 0,
            selected_newlines: 0,
            ends_with_newline: false,
            first_line_bytes: 0,
            prefix: String::new(),
        }
    }

    fn selection_complete(&self) -> bool {
        self.start == self.end || self.file_lines > self.end
    }

    fn push(&mut self, text: &str) {
        for part in text.split_inclusive('\n') {
            let line = self.file_lines - 1;
            let newline = part.ends_with('\n');
            self.file_lines += usize::from(newline);
            if line < self.start || line >= self.end {
                continue;
            }
            let content = part.strip_suffix('\n').unwrap_or(part);
            if line == self.start {
                self.first_line_bytes += content.len();
            }
            // join("\n") inserts separators between selected lines only.
            let selected = if self.file_lines - 1 == self.end {
                content
            } else {
                part
            };
            if selected.is_empty() {
                continue;
            }
            self.selected_bytes += selected.len();
            self.ends_with_newline = selected.ends_with('\n');
            self.selected_newlines += usize::from(self.ends_with_newline);
            self.keep_prefix(selected);
        }
    }

    fn keep_prefix(&mut self, text: &str) {
        // One byte past the cap lets truncate_head recognize a partial line.
        // Round up to a UTF-8 boundary so the retained prefix is valid text.
        let remaining = (DEFAULT_MAX_BYTES + 1).saturating_sub(self.prefix.len());
        let mut end = remaining.min(text.len());
        while !text.is_char_boundary(end) {
            end += 1;
        }
        self.prefix.push_str(&text[..end]);
    }

    fn finish(self) -> TextPage {
        let mut truncation = truncate_head(&self.prefix, TruncationOptions::default());
        if truncation.truncated_by.is_none() && self.selected_bytes > self.prefix.len() {
            truncation.truncated_by = Some(TruncationLimit::Bytes);
        }
        truncation.total_bytes = self.selected_bytes;
        truncation.total_lines = self.selected_newlines
            + usize::from(self.selected_bytes != 0 && !self.ends_with_newline);
        TextPage {
            truncation,
            file_lines: self.file_lines,
            selected_lines: self.file_lines.min(self.end).saturating_sub(self.start),
            first_line_bytes: self.first_line_bytes,
        }
    }
}