Owez / torro

A correct and easy-to-use BitTorrent library
MIT License
9 stars 0 forks source link

Streamline parser & reduce use of peeking #4

Closed Owez closed 4 years ago

Owez commented 4 years ago

Code is ugly with bad match statements, e.g.

/// Matches next peeked token in `token_iter` and consumes it until a relevant
/// data structure has been made
fn match_next_bencodeobj(
    peeked_token: &TokenType,
    token_iter: &mut std::iter::Peekable<std::slice::Iter<TokenType>>,
) -> Result<BencodeObj, ParseError> {
    match peeked_token {
        TokenType::IntStart => Ok(BencodeObj::Int(decode_int(token_iter)?)),
        TokenType::ListStart => Ok(BencodeObj::List(decode_list(token_iter)?)),
        TokenType::Char(c) => match c {
            '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => {
                Ok(BencodeObj::Str(decode_str(token_iter)?))
            }
            _ => return Err(ParseError::UnexpectedChar(*c)), // TODO better error
        },
        _ => unimplemented!(),
    }
}

That requires a peeked token and such which shouldn't be the case, should find a better non-peek way to make this more efficiant

Owez commented 4 years ago

Suggested "you can just lift consumption of the deciding char to the dispatching function"

Owez commented 4 years ago

Also suggesting to partially rewrite parser in the future, a new issue should be made about that if this is closed. This is due to the ugly signature of token_iter: &mut std::iter::Peekable<std::slice::Iter<TokenType>> in many of the parameters that could be replaced or significantly altered.

The decode_x functions themselves are fine, just the functions that call them are not the best quality. More of a back-burner issue though as i'd like to focus on new features rather than smaller optimizations and code nicities.