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)
| 754 | /// even allocation, then give unused capacity from short bodies to higher-ranked |
| 755 | /// items instead of silently discarding available context. |
| 756 | fn apply_budget(mut items: Vec<MemoryItem>, budget_chars: usize) -> Vec<MemoryItem> { |
| 757 | if items.is_empty() { |
| 758 | return items; |
| 759 | } |
| 760 | let lengths: Vec<usize> = items.iter().map(|item| item.body.chars().count()).collect(); |
| 761 | let baseline = budget_chars / items.len(); |
| 762 | let mut allocations: Vec<usize> = lengths |
| 763 | .iter() |
| 764 | .map(|length| (*length).min(baseline)) |
| 765 | .collect(); |
| 766 | let mut remaining = budget_chars.saturating_sub(allocations.iter().sum()); |
| 767 | for (allocation, length) in allocations.iter_mut().zip(&lengths) { |
| 768 | let extra = length.saturating_sub(*allocation).min(remaining); |
| 769 | *allocation += extra; |
| 770 | remaining -= extra; |
| 771 | if remaining == 0 { |
| 772 | break; |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | for ((item, allocation), length) in items.iter_mut().zip(allocations).zip(lengths) { |
| 777 | if allocation < length { |
| 778 | item.body = truncate_chars(&item.body, allocation); |
| 779 | item.truncated = true; |
| 780 | } |
| 781 | } |
| 782 | items |
| 783 | } |
| 784 | |
| 785 | /// Truncate to at most `max_chars` characters on a char boundary. |
| 786 | fn truncate_chars(s: &str, max_chars: usize) -> String { |