use std::sync::{Arc, Mutex};
pub(super) fn take_delta_from_buffer(
buffer: &Arc<Mutex<Vec<u8>>>,
cursor: &mut usize,
) -> (Vec<u8>, usize) {
let guard = buffer.lock().unwrap_or_else(|e| e.into_inner());
let total = guard.len();
let start = (*cursor).min(total);
let delta = guard[start..].to_vec();
*cursor = total;
(delta, total)
}
pub(super) fn tail_from_buffer(
buffer: &Arc<Mutex<Vec<u8>>>,
max_tail_chars: usize,
) -> (usize, String) {
let guard = buffer.lock().unwrap_or_else(|e| e.into_inner());
let total = guard.len();
let mut tail_start = total.saturating_sub(max_tail_chars.saturating_mul(4));
while tail_start < total && (guard[tail_start] & 0xC0) == 0x80 {
tail_start += 1;
}
let tail_str = String::from_utf8_lossy(&guard[tail_start..]).into_owned();
(total, tail_text(&tail_str, max_tail_chars))
}
fn tail_text(text: &str, max_chars: usize) -> String {
if text.chars().count() <= max_chars {
return text.to_string();
}
let tail = text
.chars()
.rev()
.take(max_chars)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect::<String>();
format!("...{tail}")
}