rust-lang / rust-lang/rust

Tracking Issue for `clamp_to`

Open
#147,781 12 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-tracking-issue S-tracking-unimplemented T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Feature gate: #![feature(clamp_to)], as well as possibly perma-unstable #[feature(clamp_bounds)].

This is a tracking issue for rust-lang/libs-team#665, which adds less confusable alternatives for x.min(y) and x.max(y).

Public API

// Perma-unstable
trait ClampBounds<T> {
    fn clamp(self, x: T) -> T;
}

impl ClampBounds<T> for RangeInclusive<T> where T: Ord {}
impl ClampBounds<f32> for RangeInclusive<f32> {}
// likewise for RangeFrom, RangeToInclusive, and RangeFull, and for f16/f64/f128

trait Ord {
    fn clamp_to(self, range: impl ClampBounds<Self>) -> Self;
}

// For each floating-point type:
impl f32 {
    fn clamp_to(self, range: impl ClampBounds<Self>) -> Self;
}
Steps / History

(Remember to update the S-tracking-* label when checking boxes.)

  • ACP: rust-lang/libs-team#665
  • Implementation 1: #147786
  • Implementation 2: #150075
  • Final comment period (FCP)^1
  • Stabilization PR
Unresolved Questions
  • Is having these functions, where clamp_min == max, actually less confusing than the status quo?
    • It is not. Switched to clamp_to with ranges.
  • Should there be a lint that suggests replacing x.max(y) with x.clamp_to(y..)?
  • What semantics should the float versions have regarding NaN? NAN.max(0.0) is 0, while NAN.clamp(0.0, 0.0) is NaN, and 0.0.clamp(NAN, NAN) panics.

Contributor guide

Open the contributing guide

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.

Research direction

Read the API sketch and implementation PRs #147786 and #150075 first; this issue names no file or test entry point. The tracking work is complete when the open FCP and stabilization steps are resolved, including the listed float-NaN and lint questions.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.