MCPcopy Create free account
hub / github.com/atomicdotdev/atomic / apply_budget

Function apply_budget

atomic-cli/src/commands/vault/context.rs:736–763  ·  view source on GitHub ↗

Truncate bodies so their combined length fits `budget_chars`. Start with an even allocation, then give unused capacity from short bodies to higher-ranked items instead of silently discarding available context.

(mut items: Vec<MemoryItem>, budget_chars: usize)

Source from the content-addressed store, hash-verified

734/// even allocation, then give unused capacity from short bodies to higher-ranked
735/// items instead of silently discarding available context.
736fn apply_budget(mut items: Vec<MemoryItem>, budget_chars: usize) -> Vec<MemoryItem> {
737 if items.is_empty() {
738 return items;
739 }
740 let lengths: Vec<usize> = items.iter().map(|item| item.body.chars().count()).collect();
741 let baseline = budget_chars / items.len();
742 let mut allocations: Vec<usize> = lengths
743 .iter()
744 .map(|length| (*length).min(baseline))
745 .collect();
746 let mut remaining = budget_chars.saturating_sub(allocations.iter().sum());
747 for (allocation, length) in allocations.iter_mut().zip(&lengths) {
748 let extra = length.saturating_sub(*allocation).min(remaining);
749 *allocation += extra;
750 remaining -= extra;
751 if remaining == 0 {
752 break;
753 }
754 }
755
756 for ((item, allocation), length) in items.iter_mut().zip(allocations).zip(lengths) {
757 if allocation < length {
758 item.body = truncate_chars(&item.body, allocation);
759 item.truncated = true;
760 }
761 }
762 items
763}
764
765/// Truncate to at most `max_chars` characters on a char boundary.
766fn truncate_chars(s: &str, max_chars: usize) -> String {

Calls 6

truncate_charsFunction · 0.85
iter_mutMethod · 0.80
is_emptyMethod · 0.45
iterMethod · 0.45
countMethod · 0.45
lenMethod · 0.45