Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add uNN::checked_sub_nonzero #549

Open
scottmcm opened this issue Feb 26, 2025 · 2 comments
Open

Add uNN::checked_sub_nonzero #549

scottmcm opened this issue Feb 26, 2025 · 2 comments
Labels
api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api

Comments

@scottmcm
Copy link
Member

scottmcm commented Feb 26, 2025

Proposal

Problem statement

It's really nice now that uNN::checked_sub gives you a safe way to get a uNN::unchecked_sub.

However, that's only a smooth replacement for code doing if a >= b { process(a - b) }.

It would also be nice to have a smooth replacement for code doing if a > b { process(a - b) }, especially if you want a NonZero.

Motivating examples or use cases

This is particularly common when implementing Iterator::advance_by, where the return type includes a NonZero, and the usual implementation involves comparing the passed-in n to the iterator's length, but what you want is essentially if n > len { self.exhaust(); return Err(n-len); }, but those types don't work out.

Solution sketch

impl u8/u16/... {
    pub const fn checked_sub_nonzero(self, subtrahend: Self) -> Option<NonZero<Self>> {
        if self > subtrahend { Some(unsafe { NonZero::new_unchecked(self.unchecked_sub(subtrahend)) }) }
        else { None }
    }
}

That encapsulates both unsafe calls in a useful safe API.

Alternatives

  • People can continue to write if n > len { foo(NonZero::new(n - len).unwrap()) } and count on the optimizer to remove the panic path.
  • Give a three-sized version of this that would work more like cmp, giving Greater(NonZero<T>)/Equal/Less(NonZero<T>), which could work on signed types too.
  • Use something other than Option as a return type, so maybe you could have Result<u32, NonZeroU32> or Result<NonZeroU32, u32> as a return type (so you'd a.foo(b) or b.foo(a) depending which side you want the zero to be included on)
  • Have other kinds of safe NonZero constructors, perhaps something like |a: u32, b: u32| if a > b { NonZero::new_unchecked(a) } that can work because for any value of b, if a is greater then it must be non-zero.
  • Other names, like maybe checked_nonzero_sub would be more consistent with other ones like checked_signed_diff, or some other thing I'm not thinking of right now.
  • Making this an associated thing on NonZero, like <NonZero<u32>>::checked_sub(len, n), rather than it being on the integer types.

Links and related work

rust-lang/rust#124114 made checked_sub use unchecked_sub internally for unsigned integers, and rust-lang/rust#124701 suggests it in the docs as a situational alternative to calling unchecked_sub directly.

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.
@scottmcm scottmcm added api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api labels Feb 26, 2025
@quaternic
Copy link

quaternic commented Feb 27, 2025

This could also be written a.checked_sub(b).and_then(NonZero::new), though maybe writing out the if a > b { ... } is still clearer about what the condition actually is (and doesn't completely break if the integers are signed).

edit: Oh, also NonZero::new(a.saturating_sub(b)). Only realized after noticing that LLVM optimizes the above to just usub.sat. NonZero::new is basically a no-op at that level since the zero-niche gets used for None.

Actually, TIL, it's a no-op (transmute) to begin with: https://doc.rust-lang.org/src/core/num/nonzero.rs.html#384

@scottmcm
Copy link
Member Author

scottmcm commented Mar 2, 2025

Only realized after noticing that LLVM optimizes the above to just usub.sat.

Only if you're unlucky and the Option doesn't get elided away entirely. I was thinking of this for situations more like

pub fn foo(a: u32, b: u32) {
    if a > b { do_something(NonZero::new(a - b).unwrap()) }
}

where you don't want a sat, just the sub nuw

define void @bar(i32 noundef %a, i32 noundef %b) unnamed_addr {
start:
  %.not = icmp ugt i32 %a, %b
  br i1 %.not, label %bb1, label %bb2

bb1:
  %0 = sub nuw i32 %a, %b
  tail call void @do_something(i32 noundef %0) #1
  br label %bb2

bb2:
  ret void
}

Though you're right that

if let Some(d) = NonZero::new(a.saturating_sub(b))

does optimize to that too https://rust.godbolt.org/z/Y9bsa99xW

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api
Projects
None yet
Development

No branches or pull requests

2 participants