Zigzag signed encode/decode overflow

Open Beginner friendly
#8 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Quiet
Tech stack
rust
Domain
backend

Research direction

Read the sign helper in src/lib.rs and reproduce the failure with the provided test_roundtrip_i64_min test. Check that decoding the encoded i64::MIN returns i64::MIN without overflow in debug or release builds; consider the reported overflow in unsign as part of the investigation.

Written by the indexing model from the issue text.

Description

The zigzag decode helper sign, on input u64::MAX, panics in debug builds and silently returns 0 instead of i64::MIN in release builds.

In src/lib.rs:

fn sign(value: u64) -> i64 {
    if value & 1 != 0 {
        -(((value + 1) / 2) as i64)
    } else {
        (value / 2) as i64
    }
}

u64::MAX is odd, so we enter the if-branch. u64::MAX + 1 overflows u64:

  • Debug: panic with "attempt to add with overflow"
  • Release: wraps to 0, so sign(u64::MAX) silently returns 0 instead of the correct i64::MIN (-9223372036854775808)

This can lead to data corruption. Unit test to reproduce:

#[test]
fn test_roundtrip_i64_min() {
    let mut buf = [0u8; 10];
    let n = signed_encode(i64::MIN, &mut buf);
    let mut out = 0i64;
    signed_decode(&buf[..n], &mut out);
    assert_eq!(out, i64::MIN); // fails: out == 0
}

The encode side (unsign) has a similar overflow (i64::MIN * -2), but wrapping arithmetic accidentally produces the correct result (u64::MAX), so encode works in release.

Dominant language
Rust
Stars
15
Forks
2
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from datrs/varinteger

All issues in datrs/varinteger

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.