Skip to content

UB in SizeValue::mul when multiplying by zero #108

@varies-rust

Description

@varies-rust

Hi maintainers, and thanks for your work on encase.

Our tool detects a minor Undefined Behavior case in SizeValue::mul when the multiplier is 0.

Minimal reproducer

fn test_function() {
    let _local0 = encase::internal::SizeValue::new(1);
    let _ = encase::internal::SizeValue::mul(_local0, 0);
}

Miri output

Undefined Behavior: entering unreachable code
  --> encase-0.12.0/src/core/size_value.rs:35:31
   |
35 |                 Self(unsafe { NonZeroU64::new_unchecked(val) })
   |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here

Location

src/core/size_value.rs line 35 (NonZeroU64::new_unchecked(val)).

Expected behavior

SizeValue::mul should handle zero safely (e.g. return an error / None / panic explicitly), but should not invoke UB.

Actual behavior

When multiplication results in 0, NonZeroU64::new_unchecked(0) is reached, which is UB.

Suggested fix

Add an explicit zero check before constructing NonZeroU64, or replace new_unchecked with a checked path (NonZeroU64::new(...)) and handle None accordingly.

If helpful, I can also open a PR with a patch and regression test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions