Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/utils/string/BUILD.bazel
Normal file
6
akode-rs/utils/string/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "string",
|
||||
crate_name = "akode_utils_string",
|
||||
)
|
||||
19
akode-rs/utils/string/Cargo.toml
Normal file
19
akode-rs/utils/string/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "akode-utils-string"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
regex-lite = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
169
akode-rs/utils/string/src/json.rs
Normal file
169
akode-rs/utils/string/src/json.rs
Normal file
@@ -0,0 +1,169 @@
|
||||
//! JSON serialization helpers for ASCII-only transports and bounded output.
|
||||
|
||||
use std::io;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
struct AsciiJsonFormatter;
|
||||
|
||||
impl serde_json::ser::Formatter for AsciiJsonFormatter {
|
||||
// serde_json has no ensure_ascii flag; this formatter keeps its serializer
|
||||
// in charge and only escapes non-ASCII string fragments.
|
||||
fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
|
||||
where
|
||||
W: ?Sized + io::Write,
|
||||
{
|
||||
let mut start = 0;
|
||||
for (index, ch) in fragment.char_indices() {
|
||||
if ch.is_ascii() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if start < index {
|
||||
writer.write_all(&fragment.as_bytes()[start..index])?;
|
||||
}
|
||||
|
||||
let mut utf16 = [0; 2];
|
||||
for code_unit in ch.encode_utf16(&mut utf16) {
|
||||
write!(writer, "\\u{code_unit:04x}")?;
|
||||
}
|
||||
start = index + ch.len_utf8();
|
||||
}
|
||||
|
||||
if start < fragment.len() {
|
||||
writer.write_all(&fragment.as_bytes()[start..])?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize JSON while escaping non-ASCII string content as `\uXXXX`.
|
||||
///
|
||||
/// This is useful when JSON needs to remain parseable as JSON but must be
|
||||
/// carried through ASCII-safe transports such as HTTP headers.
|
||||
pub fn to_ascii_json_string<T>(value: &T) -> serde_json::Result<String>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
let mut bytes = Vec::new();
|
||||
let mut serializer = serde_json::Serializer::with_formatter(&mut bytes, AsciiJsonFormatter);
|
||||
value.serialize(&mut serializer)?;
|
||||
String::from_utf8(bytes)
|
||||
.map_err(|err| serde_json::Error::io(io::Error::new(io::ErrorKind::InvalidData, err)))
|
||||
}
|
||||
|
||||
/// Serialize UTF-8 JSON while retaining at most `max_bytes` of output.
|
||||
pub fn to_json_string_bounded<T>(value: &T, max_bytes: usize) -> serde_json::Result<String>
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
struct BoundedBuffer {
|
||||
bytes: Vec<u8>,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl io::Write for BoundedBuffer {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if bytes.len() > self.max_bytes.saturating_sub(self.bytes.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::WriteZero,
|
||||
"JSON byte limit exceeded",
|
||||
));
|
||||
}
|
||||
self.bytes.extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let mut buffer = BoundedBuffer {
|
||||
bytes: Vec::new(),
|
||||
max_bytes,
|
||||
};
|
||||
let mut serializer = serde_json::Serializer::new(&mut buffer);
|
||||
value.serialize(&mut serializer)?;
|
||||
String::from_utf8(buffer.bytes)
|
||||
.map_err(|err| serde_json::Error::io(io::Error::new(io::ErrorKind::InvalidData, err)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Serialize;
|
||||
use serde::ser::SerializeStruct;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
use super::to_ascii_json_string;
|
||||
use super::to_json_string_bounded;
|
||||
|
||||
#[test]
|
||||
fn to_ascii_json_string_escapes_non_ascii_strings() {
|
||||
struct TestPayload;
|
||||
|
||||
impl Serialize for TestPayload {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let workspaces = BTreeMap::from([("/tmp/東京", TestWorkspace)]);
|
||||
let mut state = serializer.serialize_struct("TestPayload", 1)?;
|
||||
state.serialize_field("workspaces", &workspaces)?;
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct TestWorkspace;
|
||||
|
||||
impl Serialize for TestWorkspace {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let mut state = serializer.serialize_struct("TestWorkspace", 2)?;
|
||||
state.serialize_field("label", "Agentlarım")?;
|
||||
state.serialize_field("emoji", "🚀")?;
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
let value = TestPayload;
|
||||
let expected_value = json!({
|
||||
"workspaces": {
|
||||
"/tmp/東京": {
|
||||
"label": "Agentlarım",
|
||||
"emoji": "🚀"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let serialized = to_ascii_json_string(&value).expect("serialize ascii json");
|
||||
|
||||
assert_eq!(
|
||||
serialized,
|
||||
r#"{"workspaces":{"/tmp/\u6771\u4eac":{"label":"Agentlar\u0131m","emoji":"\ud83d\ude80"}}}"#
|
||||
);
|
||||
assert!(serialized.is_ascii());
|
||||
assert!(!serialized.contains("東京"));
|
||||
assert!(!serialized.contains("Agentlarım"));
|
||||
assert!(!serialized.contains("🚀"));
|
||||
let parsed: Value = serde_json::from_str(&serialized).expect("serialized json");
|
||||
assert_eq!(parsed, expected_value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_json_counts_utf8_output_bytes() {
|
||||
assert_eq!(
|
||||
to_json_string_bounded(&"é", /*max_bytes*/ 4).unwrap(),
|
||||
r#""é""#
|
||||
);
|
||||
assert!(to_json_string_bounded(&"é", /*max_bytes*/ 3).is_err());
|
||||
assert!(to_json_string_bounded(&"a".repeat(100_000), 16 * 1024).is_err());
|
||||
}
|
||||
}
|
||||
169
akode-rs/utils/string/src/lib.rs
Normal file
169
akode-rs/utils/string/src/lib.rs
Normal file
@@ -0,0 +1,169 @@
|
||||
mod json;
|
||||
mod truncate;
|
||||
|
||||
pub use json::to_ascii_json_string;
|
||||
pub use json::to_json_string_bounded;
|
||||
pub use truncate::TextTruncation;
|
||||
pub use truncate::approx_bytes_for_tokens;
|
||||
pub use truncate::approx_token_count;
|
||||
pub use truncate::approx_tokens_from_byte_count;
|
||||
pub use truncate::plan_token_truncation;
|
||||
pub use truncate::truncate_middle_chars;
|
||||
pub use truncate::truncate_middle_with_marker;
|
||||
pub use truncate::truncate_middle_with_token_budget;
|
||||
|
||||
// Truncate a &str to a byte budget at a char boundary (prefix)
|
||||
#[inline]
|
||||
pub fn take_bytes_at_char_boundary(s: &str, maxb: usize) -> &str {
|
||||
if s.len() <= maxb {
|
||||
return s;
|
||||
}
|
||||
let mut last_ok = 0;
|
||||
for (i, ch) in s.char_indices() {
|
||||
let nb = i + ch.len_utf8();
|
||||
if nb > maxb {
|
||||
break;
|
||||
}
|
||||
last_ok = nb;
|
||||
}
|
||||
&s[..last_ok]
|
||||
}
|
||||
|
||||
/// Sanitize a tag value to comply with metric tag validation rules:
|
||||
/// only ASCII alphanumeric, '.', '_', '-', and '/' are allowed.
|
||||
pub fn sanitize_metric_tag_value(value: &str) -> String {
|
||||
const MAX_LEN: usize = 256;
|
||||
let sanitized: String = value
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-' | '/') {
|
||||
ch
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let trimmed = sanitized.trim_matches('_');
|
||||
if trimmed.is_empty() || trimmed.chars().all(|ch| !ch.is_ascii_alphanumeric()) {
|
||||
return "unspecified".to_string();
|
||||
}
|
||||
if trimmed.len() <= MAX_LEN {
|
||||
trimmed.to_string()
|
||||
} else {
|
||||
trimmed[..MAX_LEN].to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Find all UUIDs in a string.
|
||||
#[allow(clippy::unwrap_used)]
|
||||
pub fn find_uuids(s: &str) -> Vec<String> {
|
||||
static RE: std::sync::OnceLock<regex_lite::Regex> = std::sync::OnceLock::new();
|
||||
let re = RE.get_or_init(|| {
|
||||
regex_lite::Regex::new(
|
||||
r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}",
|
||||
)
|
||||
.unwrap() // Unwrap is safe thanks to the tests.
|
||||
});
|
||||
|
||||
re.find_iter(s).map(|m| m.as_str().to_string()).collect()
|
||||
}
|
||||
|
||||
/// Convert a markdown-style `#L..` location suffix into a terminal-friendly
|
||||
/// `:line[:column][-line[:column]]` suffix.
|
||||
pub fn normalize_markdown_hash_location_suffix(suffix: &str) -> Option<String> {
|
||||
let fragment = suffix.strip_prefix('#')?;
|
||||
let (start, end) = match fragment.split_once('-') {
|
||||
Some((start, end)) => (start, Some(end)),
|
||||
None => (fragment, None),
|
||||
};
|
||||
let (start_line, start_column) = parse_markdown_hash_location_point(start)?;
|
||||
let mut normalized = String::from(":");
|
||||
normalized.push_str(start_line);
|
||||
if let Some(column) = start_column {
|
||||
normalized.push(':');
|
||||
normalized.push_str(column);
|
||||
}
|
||||
if let Some(end) = end {
|
||||
let (end_line, end_column) = parse_markdown_hash_location_point(end)?;
|
||||
normalized.push('-');
|
||||
normalized.push_str(end_line);
|
||||
if let Some(column) = end_column {
|
||||
normalized.push(':');
|
||||
normalized.push_str(column);
|
||||
}
|
||||
}
|
||||
Some(normalized)
|
||||
}
|
||||
|
||||
fn parse_markdown_hash_location_point(point: &str) -> Option<(&str, Option<&str>)> {
|
||||
let point = point.strip_prefix('L')?;
|
||||
match point.split_once('C') {
|
||||
Some((line, column)) => Some((line, Some(column))),
|
||||
None => Some((point, None)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(warnings, clippy::all)]
|
||||
mod tests {
|
||||
use super::find_uuids;
|
||||
use super::normalize_markdown_hash_location_suffix;
|
||||
use super::sanitize_metric_tag_value;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn find_uuids_finds_multiple() {
|
||||
let input =
|
||||
"x 00112233-4455-6677-8899-aabbccddeeff-k y 12345678-90ab-cdef-0123-456789abcdef";
|
||||
assert_eq!(
|
||||
find_uuids(input),
|
||||
vec![
|
||||
"00112233-4455-6677-8899-aabbccddeeff".to_string(),
|
||||
"12345678-90ab-cdef-0123-456789abcdef".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_uuids_ignores_invalid() {
|
||||
let input = "not-a-uuid-1234-5678-9abc-def0-123456789abc";
|
||||
assert_eq!(find_uuids(input), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_uuids_handles_non_ascii_without_overlap() {
|
||||
let input = "🙂 55e5d6f7-8a7f-4d2a-8d88-123456789012abc";
|
||||
assert_eq!(
|
||||
find_uuids(input),
|
||||
vec!["55e5d6f7-8a7f-4d2a-8d88-123456789012".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_metric_tag_value_trims_and_fills_unspecified() {
|
||||
let msg = "///";
|
||||
assert_eq!(sanitize_metric_tag_value(msg), "unspecified");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_metric_tag_value_replaces_invalid_chars() {
|
||||
let msg = "bad value!";
|
||||
assert_eq!(sanitize_metric_tag_value(msg), "bad_value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_markdown_hash_location_suffix_converts_single_location() {
|
||||
assert_eq!(
|
||||
normalize_markdown_hash_location_suffix("#L74C3"),
|
||||
Some(":74:3".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_markdown_hash_location_suffix_converts_ranges() {
|
||||
assert_eq!(
|
||||
normalize_markdown_hash_location_suffix("#L74C3-L76C9"),
|
||||
Some(":74:3-76:9".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
163
akode-rs/utils/string/src/truncate.rs
Normal file
163
akode-rs/utils/string/src/truncate.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
//! Utilities for truncating large chunks of output while preserving a prefix
|
||||
//! and suffix on UTF-8 boundaries.
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
const APPROX_BYTES_PER_TOKEN: usize = 4;
|
||||
|
||||
/// Replaces one UTF-8-aligned range with a notice. Callers can apply the same
|
||||
/// edit to annotated text without losing the sources of the retained slices.
|
||||
pub struct TextTruncation {
|
||||
pub removed: Range<usize>,
|
||||
pub marker: String,
|
||||
}
|
||||
|
||||
impl TextTruncation {
|
||||
/// Applies this edit to the string it was planned from.
|
||||
pub fn apply(&self, original: &str) -> String {
|
||||
assemble_truncated_output(
|
||||
&original[..self.removed.start],
|
||||
&original[self.removed.end..],
|
||||
&self.marker,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Plans the existing head/tail token truncation. The marker is outside the
|
||||
/// retained-text budget, just as it is in [`truncate_middle_with_token_budget`].
|
||||
pub fn plan_token_truncation(s: &str, max_tokens: usize) -> Option<TextTruncation> {
|
||||
let max_bytes = approx_bytes_for_tokens(max_tokens);
|
||||
if s.len() <= max_bytes {
|
||||
return None;
|
||||
}
|
||||
let (left_budget, right_budget) = split_budget(max_bytes);
|
||||
let removed = s.floor_char_boundary(left_budget)..s.ceil_char_boundary(s.len() - right_budget);
|
||||
let removed_tokens = approx_tokens_from_byte_count(s.len() - max_bytes);
|
||||
Some(TextTruncation {
|
||||
removed,
|
||||
marker: format!("…{removed_tokens} tokens truncated…"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Retain at most `max_bytes` from a string's ends and add a character-count
|
||||
/// marker outside that budget.
|
||||
///
|
||||
/// Use [`truncate_middle_with_marker`] when the complete result must fit a hard
|
||||
/// byte limit.
|
||||
pub fn truncate_middle_chars(s: &str, max_bytes: usize) -> String {
|
||||
if s.len() <= max_bytes {
|
||||
return s.to_string();
|
||||
}
|
||||
let (left_budget, right_budget) = split_budget(max_bytes);
|
||||
let (removed_chars, left, right) = split_string(s, left_budget, right_budget);
|
||||
assemble_truncated_output(left, right, &format!("…{removed_chars} chars truncated…"))
|
||||
}
|
||||
|
||||
/// Truncate the middle of a UTF-8 string so the result, including `marker`, is
|
||||
/// at most `max_bytes` bytes.
|
||||
///
|
||||
/// Returns the original string when it already fits. If the marker itself does
|
||||
/// not fit, returns the longest original prefix that does.
|
||||
pub fn truncate_middle_with_marker(s: &str, max_bytes: usize, marker: &str) -> String {
|
||||
if s.len() <= max_bytes {
|
||||
return s.to_string();
|
||||
}
|
||||
|
||||
let Some(content_budget) = max_bytes.checked_sub(marker.len()) else {
|
||||
return s[..s.floor_char_boundary(max_bytes)].to_string();
|
||||
};
|
||||
let (left_budget, right_budget) = split_budget(content_budget);
|
||||
let prefix_end = s.floor_char_boundary(left_budget);
|
||||
let suffix_start = s.ceil_char_boundary(s.len().saturating_sub(right_budget));
|
||||
|
||||
assemble_truncated_output(&s[..prefix_end], &s[suffix_start..], marker)
|
||||
}
|
||||
|
||||
/// Truncate the middle of a UTF-8 string to at most `max_tokens` approximate
|
||||
/// tokens, preserving the beginning and the end. Returns the possibly
|
||||
/// truncated string and `Some(original_token_count)` if truncation occurred;
|
||||
/// otherwise returns the original string and `None`.
|
||||
pub fn truncate_middle_with_token_budget(s: &str, max_tokens: usize) -> (String, Option<u64>) {
|
||||
let Some(truncation) = plan_token_truncation(s, max_tokens) else {
|
||||
return (s.to_string(), None);
|
||||
};
|
||||
let truncated = truncation.apply(s);
|
||||
let total_tokens = u64::try_from(approx_token_count(s)).unwrap_or(u64::MAX);
|
||||
|
||||
if truncated == s {
|
||||
(truncated, None)
|
||||
} else {
|
||||
(truncated, Some(total_tokens))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn approx_token_count(text: &str) -> usize {
|
||||
let len = text.len();
|
||||
len.saturating_add(APPROX_BYTES_PER_TOKEN.saturating_sub(1)) / APPROX_BYTES_PER_TOKEN
|
||||
}
|
||||
|
||||
pub const fn approx_bytes_for_tokens(tokens: usize) -> usize {
|
||||
tokens.saturating_mul(APPROX_BYTES_PER_TOKEN)
|
||||
}
|
||||
|
||||
pub fn approx_tokens_from_byte_count(bytes: usize) -> u64 {
|
||||
let bytes_u64 = bytes as u64;
|
||||
bytes_u64.saturating_add((APPROX_BYTES_PER_TOKEN as u64).saturating_sub(1))
|
||||
/ (APPROX_BYTES_PER_TOKEN as u64)
|
||||
}
|
||||
|
||||
fn split_string(s: &str, beginning_bytes: usize, end_bytes: usize) -> (usize, &str, &str) {
|
||||
if s.is_empty() {
|
||||
return (0, "", "");
|
||||
}
|
||||
|
||||
let len = s.len();
|
||||
let tail_start_target = len.saturating_sub(end_bytes);
|
||||
let mut prefix_end = 0usize;
|
||||
let mut suffix_start = len;
|
||||
let mut removed_chars = 0usize;
|
||||
let mut suffix_started = false;
|
||||
|
||||
for (idx, ch) in s.char_indices() {
|
||||
let char_end = idx + ch.len_utf8();
|
||||
if char_end <= beginning_bytes {
|
||||
prefix_end = char_end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if idx >= tail_start_target {
|
||||
if !suffix_started {
|
||||
suffix_start = idx;
|
||||
suffix_started = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
removed_chars = removed_chars.saturating_add(1);
|
||||
}
|
||||
|
||||
if suffix_start < prefix_end {
|
||||
suffix_start = prefix_end;
|
||||
}
|
||||
|
||||
let before = &s[..prefix_end];
|
||||
let after = &s[suffix_start..];
|
||||
|
||||
(removed_chars, before, after)
|
||||
}
|
||||
|
||||
fn split_budget(budget: usize) -> (usize, usize) {
|
||||
let left = budget / 2;
|
||||
(left, budget - left)
|
||||
}
|
||||
|
||||
fn assemble_truncated_output(prefix: &str, suffix: &str, marker: &str) -> String {
|
||||
let mut out = String::with_capacity(prefix.len() + marker.len() + suffix.len() + 1);
|
||||
out.push_str(prefix);
|
||||
out.push_str(marker);
|
||||
out.push_str(suffix);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
165
akode-rs/utils/string/src/truncate/tests.rs
Normal file
165
akode-rs/utils/string/src/truncate/tests.rs
Normal file
@@ -0,0 +1,165 @@
|
||||
use super::split_string;
|
||||
use super::truncate_middle_chars;
|
||||
use super::truncate_middle_with_marker;
|
||||
use super::truncate_middle_with_token_budget;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn split_string_works() {
|
||||
assert_eq!(
|
||||
split_string(
|
||||
"hello world",
|
||||
/*beginning_bytes*/ 5,
|
||||
/*end_bytes*/ 5
|
||||
),
|
||||
(1, "hello", "world")
|
||||
);
|
||||
assert_eq!(
|
||||
split_string("abc", /*beginning_bytes*/ 0, /*end_bytes*/ 0),
|
||||
(3, "", "")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_string_handles_empty_string() {
|
||||
assert_eq!(
|
||||
split_string("", /*beginning_bytes*/ 4, /*end_bytes*/ 4),
|
||||
(0, "", "")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_string_only_keeps_prefix_when_tail_budget_is_zero() {
|
||||
assert_eq!(
|
||||
split_string("abcdef", /*beginning_bytes*/ 3, /*end_bytes*/ 0),
|
||||
(3, "abc", "")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_string_only_keeps_suffix_when_prefix_budget_is_zero() {
|
||||
assert_eq!(
|
||||
split_string("abcdef", /*beginning_bytes*/ 0, /*end_bytes*/ 3),
|
||||
(3, "", "def")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_string_handles_overlapping_budgets_without_removal() {
|
||||
assert_eq!(
|
||||
split_string("abcdef", /*beginning_bytes*/ 4, /*end_bytes*/ 4),
|
||||
(0, "abcd", "ef")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_string_respects_utf8_boundaries() {
|
||||
assert_eq!(
|
||||
split_string("😀abc😀", /*beginning_bytes*/ 5, /*end_bytes*/ 5),
|
||||
(1, "😀a", "c😀")
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
split_string(
|
||||
"😀😀😀😀😀",
|
||||
/*beginning_bytes*/ 1,
|
||||
/*end_bytes*/ 1
|
||||
),
|
||||
(5, "", "")
|
||||
);
|
||||
assert_eq!(
|
||||
split_string(
|
||||
"😀😀😀😀😀",
|
||||
/*beginning_bytes*/ 7,
|
||||
/*end_bytes*/ 7
|
||||
),
|
||||
(3, "😀", "😀")
|
||||
);
|
||||
assert_eq!(
|
||||
split_string(
|
||||
"😀😀😀😀😀",
|
||||
/*beginning_bytes*/ 8,
|
||||
/*end_bytes*/ 8
|
||||
),
|
||||
(1, "😀😀", "😀😀")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_with_token_budget_returns_original_when_under_limit() {
|
||||
let s = "short output";
|
||||
let limit = 100;
|
||||
let (out, original) = truncate_middle_with_token_budget(s, limit);
|
||||
assert_eq!(out, s);
|
||||
assert_eq!(original, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_with_token_budget_reports_truncation_at_zero_limit() {
|
||||
let s = "abcdef";
|
||||
let (out, original) = truncate_middle_with_token_budget(s, /*max_tokens*/ 0);
|
||||
assert_eq!(out, "…2 tokens truncated…");
|
||||
assert_eq!(original, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_tokens_handles_utf8_content() {
|
||||
let s = "😀😀😀😀😀😀😀😀😀😀\nsecond line with text\n";
|
||||
let (out, tokens) = truncate_middle_with_token_budget(s, /*max_tokens*/ 8);
|
||||
assert_eq!(out, "😀😀😀😀…8 tokens truncated… line with text\n");
|
||||
assert_eq!(tokens, Some(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_tokens_keeps_partial_characters_out_of_both_ends() {
|
||||
for (input, expected) in [
|
||||
("a😀b😀c", "a…2 tokens truncated…c"),
|
||||
("é中😀é", "é…2 tokens truncated…é"),
|
||||
("😀😀😀", "…2 tokens truncated…"),
|
||||
] {
|
||||
assert_eq!(
|
||||
truncate_middle_with_token_budget(input, /*max_tokens*/ 1),
|
||||
(expected.to_string(), Some(3)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_bytes_handles_utf8_content() {
|
||||
let s = "😀😀😀😀😀😀😀😀😀😀\nsecond line with text\n";
|
||||
let out = truncate_middle_chars(s, /*max_bytes*/ 20);
|
||||
assert_eq!(out, "😀😀…21 chars truncated…with text\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_with_marker_enforces_the_total_byte_limit() {
|
||||
let input = format!("head{}tail", "x".repeat(100));
|
||||
assert_eq!(
|
||||
truncate_middle_with_marker(&input, /*max_bytes*/ 32, "<truncated>"),
|
||||
"headxxxxxx<truncated>xxxxxxxtail"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_with_marker_preserves_utf8_boundaries() {
|
||||
assert_eq!(
|
||||
truncate_middle_with_marker("head🦀🦀🦀🦀🦀tail", /*max_bytes*/ 18, "..."),
|
||||
"head...🦀tail"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_with_marker_returns_input_that_fits() {
|
||||
assert_eq!(
|
||||
truncate_middle_with_marker("short", /*max_bytes*/ 5, "..."),
|
||||
"short"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_middle_with_marker_keeps_a_prefix_when_the_marker_does_not_fit() {
|
||||
assert_eq!(
|
||||
truncate_middle_with_marker("🦀abc", /*max_bytes*/ 4, "marker"),
|
||||
"🦀"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user