Created
September 10, 2024 06:12
-
-
Save theMackabu/a5cb451727fb473f2568698c8e540c33 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct GridLayout { | |
raw: String, | |
lines: Vec<String>, | |
line_starts: Vec<usize>, | |
} | |
impl GridLayout { | |
fn new(raw: String, max_width: usize) -> Self { | |
let mut lines = Vec::new(); | |
let mut line_starts = Vec::new(); | |
let mut current_index = 0; | |
for line in raw.split('\n') { | |
let mut current_line = String::new(); | |
let mut words = line.split_whitespace().peekable(); | |
while let Some(word) = words.next() { | |
if current_line.len() + word.len() > max_width && !current_line.is_empty() { | |
lines.push(current_line.trim().to_string()); | |
line_starts.push(current_index); | |
current_index += current_line.len(); | |
current_line = String::new(); | |
} | |
current_line.push_str(word); | |
if words.peek().is_some() { | |
current_line.push(' '); | |
} | |
} | |
if !current_line.is_empty() { | |
lines.push(current_line.trim().to_string()); | |
line_starts.push(current_index); | |
current_index += current_line.len(); | |
} | |
} | |
GridLayout { raw, lines, line_starts } | |
} | |
fn find_position(&self, raw_index: usize) -> (usize, usize) { | |
for (row, &start) in self.line_starts.iter().enumerate() { | |
if row + 1 == self.line_starts.len() || self.line_starts[row + 1] > raw_index { | |
return (row, raw_index - start); | |
} | |
} | |
(self.lines.len() - 1, self.lines.last().unwrap().len()) | |
} | |
fn get_line(&self, row: usize) -> &str { &self.lines[row] } | |
fn line_count(&self) -> usize { self.lines.len() } | |
} | |
fn main() { | |
let raw = "I have a lovely lemon sorbet".to_string(); | |
let grid = GridLayout::new(raw, 12); | |
let target_index = 16; | |
let (row, column) = grid.find_position(target_index); | |
println!("Raw index {} is at row {}, column {}", target_index, row, column); | |
for i in 0..grid.line_count() { | |
println!("Line {}: '{}'", i, grid.get_line(i)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment