EbTech / rust-algorithms

Common data structures and algorithms in Rust
MIT License
3.74k stars 219 forks source link

Inconsistency between documentation and code implementation #26

Open YichiZhang0613 opened 6 months ago

YichiZhang0613 commented 6 months ago

I noticed a possible inconsistency between documentation and code implementation in rust-algorithms/src/string_proc.rs. The details can be found in the following code. The code does not check whether pattern is not empty before it is used but the constraint exists in the documentation.

    /// # Panics
    ///
    /// Panics if pattern is empty.
    pub fn new(pattern: &'a [C]) -> Self {
        let mut fail = Vec::with_capacity(pattern.len());
        fail.push(0);
        let mut len = 0;
        for ch in &pattern[1..] {
            while len > 0 && pattern[len] != *ch {
                len = fail[len - 1];
            }
            if pattern[len] == *ch {
                len += 1;
            }
            fail.push(len);
        }
        Self { pattern, fail }
    }
EbTech commented 6 months ago

I believe it panics on &pattern[1..], doesn't it?

YichiZhang0613 commented 6 months ago

I believe it panics on &pattern[1..], doesn't it?

If pattern is empty as your documentation read then the code would panic. So I think the code should check whether pattern is empty before it is used.