3
\$\begingroup\$

I am new to rust and I wrote a little program that takes a part CSS selector and returns the name of the element and two vectors containing its attributes (classes, ids)

Example

div#menu.big.pink => "div", ["menu'], ["big", "pink"]

Because I am new to rust I am looking for improvement to make this code better - more idiomatic faster, etc.

Thanks in advance for any suggestions, have a nice day :)

const LOOK_UP: [char; 2] = ['#', '.'];

fn find(string: &str) -> Option<(usize, usize)> {
    for (index, char) in string.chars().enumerate() {
        match LOOK_UP.iter().position(|&r| r == char) {
            Some(lookup_index) => return Some((index, lookup_index)),
            _ => continue,
        };
    };
    return None;
}

fn get_attributes(node_as_string: &str) -> (&str, [Vec<&str>; 2]) {
    match find(&node_as_string) {
        Some(first) => {
            let mut attributes: [Vec<&str>; 2] = [Vec::new(), Vec::new()];
            let mut current_index = first.0;
            let mut last_type = first.1;

            loop {
                match find(&node_as_string[current_index + 1..]) {
                    Some(next) => {
                        attributes[last_type].push(&node_as_string[current_index + 1..current_index + next.0 + 1]);
                        current_index += next.0 + 1;
                        last_type = next.1;
                        continue;
                    }
                    None => {
                        attributes[last_type].push(&node_as_string[current_index + 1..]);
                        break;
                    }
                }
            }
            return (&node_as_string[..first.0], attributes);
        }
        None => panic!("")
    }
}
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.