Skip to content

Commit

Permalink
feat: add min and max functions to the stdlib (#4839)
Browse files Browse the repository at this point in the history
# Description

## Problem\*

Resolves #4781

## Summary\*

This PR adds an equivalent to Rust's `std::cmp:max` and `std::cmp::min`
https://doc.rust-lang.org/src/core/cmp.rs.html#1209

## Additional Context



## Documentation\*

Check one:
- [ ] No documentation needed.
- [ ] Documentation included in this PR.
- [ ] **[For Experimental Features]** Documentation to be submitted in a
separate PR.

# PR Checklist\*

- [ ] I have tested the changes locally.
- [ ] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
TomAFrench committed Apr 19, 2024
1 parent 9cc03a4 commit 6cfb328
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/docs/noir/standard_library/traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ impl<A, B, C, D, E> Eq for (A, B, C, D, E)
Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be
used on values of the type.

`std::cmp` also provides `max` and `min` functions for any type which implements the `Ord` trait.

Implementations:

```rust
Expand Down
52 changes: 52 additions & 0 deletions noir_stdlib/src/cmp.nr
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,55 @@ impl<A, B, C, D, E> Ord for (A, B, C, D, E) where A: Ord, B: Ord, C: Ord, D: Ord
result
}
}

// Compares and returns the maximum of two values.
//
// Returns the second argument if the comparison determines them to be equal.
//
// # Examples
//
// ```
// use std::cmp;
//
// assert_eq(cmp::max(1, 2), 2);
// assert_eq(cmp::max(2, 2), 2);
// ```
pub fn max<T>(v1: T, v2: T) -> T where T: Ord {
if v1 > v2 { v1 } else { v2 }
}

// Compares and returns the minimum of two values.
//
// Returns the first argument if the comparison determines them to be equal.
//
// # Examples
//
// ```
// use std::cmp;
//
// assert_eq(cmp::min(1, 2), 1);
// assert_eq(cmp::min(2, 2), 2);
// ```
pub fn min<T>(v1: T, v2: T) -> T where T: Ord {
if v1 > v2 { v2 } else { v1 }
}

mod cmp_tests {
use crate::cmp::{min, max};

#[test]
fn sanity_check_min() {
assert_eq(min(0 as u64, 1 as u64), 0);
assert_eq(min(0 as u64, 0 as u64), 0);
assert_eq(min(1 as u64, 1 as u64), 1);
assert_eq(min(255 as u8, 0 as u8), 0);
}

#[test]
fn sanity_check_max() {
assert_eq(max(0 as u64, 1 as u64), 1);
assert_eq(max(0 as u64, 0 as u64), 0);
assert_eq(max(1 as u64, 1 as u64), 1);
assert_eq(max(255 as u8, 0 as u8), 255);
}
}

0 comments on commit 6cfb328

Please sign in to comment.