mardi 6 août 2019

Rust panicking on very basic if statement (array bounds checking)

I have a very basic rust back-end that reads a list of keywords from a CouchDB database. In the logic of my app, if it ever encounters the keyword "PAUSE" it should spin (sleep) and keep checking until a user manually goes in and actually deletes this from the list, then move on to processing the next keywords. However, I seem to be running into an issue with array bounds checking for the edge case where the PAUSE keyword is the last element of the list, in which case after its deletion its index is out of bounds and cannot be safely checked.

The way I am handling pause right now is by simply: spinning while the local copy of the keyword array still has a "PAUSE" at the very index it was found at, and after every sleep cycle fetching the database copy of the task list to see if there are any changes:

//while the keyword is 'PAUSE' sleep for 5 seconds then try again
    while ((index as usize) < v.len()) && (v[index as usize] == "PAUSE") {
        sleep(sleep_time);
        doc = conn.schd.get(document_ci.id.clone())
        .expect("Failed to grab document while checking for removal of 'PAUSE'.");

        json = doc.get_data().clone();
        v = serde_json::from_str(&json["tasks"].to_string()).unwrap();
        println!("{:?} - {}", v.len(), index);
    }


To handle edge case: the first part of my while loop (the bounds checking) is where its failing and giving the following error:

thread 'main' panicked at 'assertion failed: index < len', src\liballoc\vec.rs:918:9

Ideally I want to be able to catch this edge case where index is > len-1 (out of bounds) so that the while loop will break and the function returns.

Aucun commentaire:

Enregistrer un commentaire