markrs/utils.rs
1use std::{
2 mem::take,
3 path::{Path, PathBuf},
4};
5
6/// Utility function for pushing a String buffer to a generic collection.
7///
8/// This function checks if the buffer is not empty, converts it to the type `T`, and pushes it to
9/// the collection.
10///
11/// # Type Parameters
12/// * `T` - The type to which the buffer will be converted. It must implement the
13/// `From<String>` trait.
14///
15/// # Arguments
16/// * `collection` - A mutable reference to the collection of type `Vec<T>` where the buffer will be pushed.
17/// * `buffer` - A mutable reference to the String buffer that will be converted and pushed.
18pub fn push_buffer_to_collection<T>(collection: &mut Vec<T>, buffer: &mut String)
19where
20 T: From<String>,
21{
22 if !buffer.is_empty() {
23 collection.push(T::from(take(buffer)));
24 }
25}
26
27/// Builds a relative prefix path based on the provided HTML relative path.
28/// Note that this function does not add the final file name, only the preceding directories.
29pub fn build_rel_prefix(html_rel_path: &str) -> PathBuf {
30 let rel_path = Path::new(html_rel_path);
31 let depth = rel_path.parent().map_or(0, |p| p.components().count());
32 let mut rel_prefix = PathBuf::new();
33 for _ in 0..depth {
34 rel_prefix.push("..");
35 }
36 rel_prefix
37}