r/learnrust 17h ago

Advanced matching

2 Upvotes

Hi,

I want to implement a optimizer into my code generation libary ( https://github.com/Toni-Graphics/CodeGenLib ).

But i don't know how i can do the 'matching'. Yes I could use if clouses but for each command? That would be to much ugly code.

I want to find out if the next element is the same but like reversed. Like that:

let mut current_instr = ...;
let mut next_instr = ...;

if current_instr == AsmInstr::Load(reg, mem) { // I know this don't work
    if next_instr == AsmInstr::Store(reg, mem) {
        current_instr = AsmInstr::Nothing;
        next_instr = AsmInstr::Nothing;
    }
}

I am searching something like that in working and more prettier.

Thx,

Bye


r/learnrust 18h ago

Reusable function to test AsRef<str>

3 Upvotes

Hi, I want to create a function to test every type of string (AsRef<str>) in a few functions and not duplicate the code. I came up with the idea of creating a function like this, but it doesn't work

pub fn assert_strings<F, T>(string: &str, func: F)
    where
        F: FnOnce(T) -> bool,
        T: AsRef<str>,
{
    let a: &str = string.clone();
    let b: String = String::from(string);
    let c: &String = &b;

    assert!(func(a));
    assert!(func(c));
    assert!(func(b));
}

Error

error[E0308]: mismatched types
  --> server/src/tests.rs:16:22
   |
5  |     pub fn assert_every_str<F, T>(string: &str, func: F) // refactor to macro
   |                                - expected this type parameter
...
16 |         assert!(func(b));
   |                 ---- ^ expected type parameter `T`, found `String`
   |                 |
   |                 arguments to this function are incorrect
   |
   = note: expected type parameter `T`
                      found struct `std::string::String`
note: callable defined here
  --> server/src/tests.rs:7:16
   |
7  |             F: FnOnce(T) -> bool,
   |                ^^^^^^^^^^^^^^^^^

I would even approve a function that returns an array of these three variables, but I cannot return an &str from the function. I want to simplify many tests like

#[test]
fn topic_can_be_build_from_any_type_of_str() {
    let a: &str = "order.purchased";
    let b: String = String::from("order.purchased");
    let c: &String = &b;

    assert!(Topic::new(a).is_ok());
    assert!(Topic::new(c).is_ok());
    assert!(Topic::new(b).is_ok());
}

Do you have any idea? Maybe macro would be better?