3 个版本
| 0.1.3 | 2023年12月22日 |
|---|---|
| 0.1.2 | 2023年12月19日 |
| 0.1.1 |
|
| 0.1.0 | 2023年11月26日 |
#4 in #inclusive
9KB
123 行
range-utils
动机
标准库有 6(甚至更多?)种不同的范围类型,例如 0..=256,..=256,0..,.. 在 u8 中表示相同的范围(如 0..3 和 ..3 是一些未列出的更多范围)。标准库提供的唯一“实用工具”是 RangeBounds,如果需要更高级/通用化的使用,则相当无用。例如,.start_bound() 如果起始位置未定义,则不会返回实际的 start_bound,这使得为不同的范围类型实现函数变得更加困难。
用法
此软件包包含以下方法的 RangeUtil<T> 特质
starts_at(&self) -> T:包含起始界限,例如(0..3).starts_at() == 0,(..3_u8).starts_at() == 0ends_at(&self) -> T:包含结束边界,例如(0..3).ends_at() == 2,(0..=2).ends_at() == 2,(..=2).ends_at() == 2,...
以下方法具有默认实现(可能不需要更改)
includes(&self, &T) -> bool:来自标准库的.contains(&T)的RangeBounds<T>,但使用starts_at()和ends_at()实现intersects(&self, other: &impl RangeUtil<T>) -> bool:两个范围是否相交,例如0..=2和2..3是相交的,而0..2和2..3则不相交intersection(&self, other: &impl RangeUtil<T>) -> Option<RangeInclusive<T>>:返回两个范围集合的交集,结果为包含范围,例如:(0..=3).intersects(&(1..)) == Some(1..=3)setminus(&self, other: &impl RangeUtil<T>) -> (Option<RangeInclusive<T>>, Option<RangeInclusive<T>>):从集合self中去除other中的元素,例如:(..100u8).setminus(&(50..)) == (Some(0..=50), None),或者:(..100u8).setminus(&(25..75)) == (Some(0..=24), Some(75..=99))