Error handling, I should make it better though

This commit is contained in:
2025-11-30 01:25:58 +00:00
parent aa4cf930b9
commit 173cf9085f
3 changed files with 78 additions and 74 deletions

60
src/pages.rs Normal file
View File

@@ -0,0 +1,60 @@
// TODO these functions are so shit
/// Finds the index of the first occurrence of search_bytes in bytes.
fn find_pattern(bytes: &[u8], search_bytes: &[u8]) -> Option<usize>
{
bytes.windows(search_bytes.len())
.position(|window| window == search_bytes)
}
/// Finds the closing brace of the opening brace passed as a param
fn find_closing_brace(bytes: &[u8], opening_brace_index: usize) -> Option<usize>
{
let mut depth: i8 = 0;
for i in opening_brace_index..bytes.len()-1
{
if bytes[i] == 5 {
depth += 1; }
else if bytes[i] == 6
{
depth -= 1;
if depth == 0 { return Some(i) }
}
//println!("{}\t{}", bytes[i], depth);
}
None
}
/// Searches the bytes for a particular page
pub fn get_page(bytes: &[u8], page: &str) -> Vec<u8>
{
let mut page_bytes: Vec<u8> = vec![1];
let search_pages_bytes: Vec<u8> = vec![3, 112, 97, 103, 101, 115, 4];
let mut search_bytes: Vec<u8> = vec![3];
search_bytes.append(&mut page.as_bytes().to_vec());
search_bytes.push(4);
if let Some(opening_index) = find_pattern(&bytes, &search_pages_bytes)
{
if let Some(closing_index) = find_closing_brace(&bytes, opening_index+search_pages_bytes.len())
{
//println!("found pages: {} to {}", opening_index, closing_index);
if let Some(opening_page_index) = find_pattern(&bytes[opening_index..closing_index+1], &search_bytes)
{
//println!("{:?}", &bytes[opening_index+opening_page_index..]);
if let Some(closing_page_index) = find_closing_brace
(
&bytes[opening_index+opening_page_index..],
search_bytes.len()
)
{
//println!("found page: {} to {}", opening_index+opening_page_index, opening_index+closing_page_index);
//println!("found page: {:?}", &bytes[opening_index+opening_page_index..opening_index+opening_page_index+closing_page_index+1]);
page_bytes.append(&mut bytes[opening_page_index+opening_index..opening_page_index+closing_page_index+opening_index+1].to_vec());
page_bytes.push(2);
return page_bytes
}
}
}
}
page_bytes.push(10); // Page not found error message
page_bytes.push(2);
page_bytes
}