From 56a5850018f128b918b385fe81d28fe2188f8601 Mon Sep 17 00:00:00 2001 From: cairoIover <193099744+cairoIover@users.noreply.github.com> Date: Mon, 6 Jan 2025 19:12:36 +0100 Subject: [PATCH] feat(corelib): range contains (#7008) --- corelib/src/ops/range.cairo | 18 +++++++++++++++++- corelib/src/test/range_test.cairo | 11 +++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/corelib/src/ops/range.cairo b/corelib/src/ops/range.cairo index f2bf7abae3b..954943e7290 100644 --- a/corelib/src/ops/range.cairo +++ b/corelib/src/ops/range.cairo @@ -40,7 +40,23 @@ pub struct Range { } #[generate_trait] -pub impl RangeImpl, +Drop, +PartialOrd> of RangeTrait { +pub impl RangeImpl, +PartialOrd<@T>> of RangeTrait { + /// Returns `true` if `item` is contained in the range. + /// + /// # Examples + /// + /// ``` + /// assert!(!(3..5).contains(@2)); + /// assert!( (3..5).contains(@3)); + /// assert!( (3..5).contains(@4)); + /// assert!(!(3..5).contains(@5)); + /// + /// assert!(!(3..3).contains(@3)); + /// assert!(!(3..2).contains(@3)); + fn contains(self: @Range, item: @T) -> bool { + self.start <= item && item < self.end + } + /// Returns `true` if the range contains no items. /// /// # Examples diff --git a/corelib/src/test/range_test.cairo b/corelib/src/test/range_test.cairo index 17cb513b606..fd7b9fe65de 100644 --- a/corelib/src/test/range_test.cairo +++ b/corelib/src/test/range_test.cairo @@ -7,6 +7,17 @@ fn test_range_is_empty() { assert!((3_u8..2_u8).is_empty()); } +#[test] +fn test_range_contains() { + assert!(!(3_u8..5).contains(@2)); + assert!((3_u8..5).contains(@3)); + assert!((3_u8..5).contains(@4)); + assert!(!(3_u8..5).contains(@5)); + + assert!(!(3_u8..3).contains(@3)); + assert!(!(3_u8..2).contains(@3)); +} + #[test] fn test_range_format() { assert!(format!("{:?}", 1..5) == "1..5");