use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq)]
struct Entity {
replacement_text: String,
start_index: usize,
end_index: usize,
}
impl Ord for Entity {
fn cmp(&self, other: &Self) -> Ordering {
self.start_index.cmp(&other.start_index)
}
}
impl PartialOrd for Entity {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn render_tweet(text: &str, entities: &mut Vec<Entity>) -> String {
entities.sort();
let mut rendered_text = String::new();
let mut previous_end = 0;
for entity in entities {
if entity.start_index < text.len() && entity.end_index <= text.len() {
rendered_text.push_str(&text[previous_end..entity.start_index]);
rendered_text.push_str(&entity.replacement_text);
previous_end = entity.end_index;
}
}
if previous_end < text.len() {
rendered_text.push_str(&text[previous_end..]);
}
rendered_text
}
fn main() {
let tweet = "Check out my new blog post at https://t.co/12345 and #learnrust!";
let mut entities = vec![
Entity {
replacement_text: String::from("[URL]"),
start_index: 27,
end_index: 49,
},
Entity {
replacement_text: String::from("#RustLearning"),
start_index: 53,
end_index: 63,
},
];
let rendered_tweet = render_tweet(&tweet, &mut entities);
println!("Original tweet: {}", tweet);
println!("Rendered tweet: {}", rendered_tweet);
}
This program defines a struct Entity and implements Ord, PartialOrd for sorting. The render_tweet function takes a reference to the tweet text and a mutable reference to a vector of entities. It sorts the entities by their start indices, then iterates through them and replaces the original text with the replacement text for each entity. Finally, it prints the original tweet and the rendered tweet.