konst/macros/const_eq_macros.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
/// Compares two values for equality.
///
/// The arguments must implement the [`ConstCmp`] trait.
/// Non-standard library types must define a `const_eq` method taking a reference.
///
/// # Limitations
///
/// The arguments must be concrete types, and have a fully inferred type.
/// eg: if you pass an integer literal it must have a suffix to indicate its type.
///
/// # Example
///
/// ```rust
/// use konst::{const_eq, impl_cmp};
///
/// use std::ops::Range;
///
/// struct Fields<'a> {
/// foo: u32,
/// bar: Option<bool>,
/// baz: Range<usize>,
/// qux: &'a str,
/// }
///
/// impl_cmp!{
/// impl['a] Fields<'a>;
/// pub const fn const_eq(&self, other: &Self) -> bool {
/// self.foo == other.foo &&
/// const_eq!(self.bar, other.bar) &&
/// const_eq!(self.baz, other.baz) &&
/// const_eq!(self.qux, other.qux)
/// }
/// }
///
/// const _: () = {
/// let foo = Fields {
/// foo: 10,
/// bar: None,
/// baz: 10..20,
/// qux: "hello",
/// };
///
/// let bar = Fields {
/// foo: 99,
/// bar: Some(true),
/// baz: 0..5,
/// qux: "world",
/// };
///
/// assert!( const_eq!(foo, foo));
/// assert!(!const_eq!(foo, bar));
/// assert!(!const_eq!(bar, foo));
/// assert!( const_eq!(bar, bar));
/// };
/// ```
///
/// [`ConstCmp`]: crate::cmp::ConstCmp
#[cfg(feature = "cmp")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "cmp")))]
#[macro_export]
macro_rules! const_eq {
($left:expr, $right:expr $(,)*) => {
match $crate::coerce_to_cmp!($left, $right) {
(left, right) => left.const_eq(right),
}
};
}
/// Compares two standard library types for equality,
/// that can't be compared with [`const_eq`].
///
/// <span id = "types-section"></span>
/// # Types
///
/// This macro supports multiple types with different prefixes:
///
/// - `slice`: for comparing `&[T]`. [example](#compare_slices_structs)
///
/// - `option`: for comparing `Option<T>`. [example](#compare_options)
///
/// - `range`: for comparing `Range<T>`. [example](#compare_ranges)
///
/// - `range_inclusive`: for comparing `RangeInclusive<T>`.
/// [example](#compare_ranges_incluside)
///
/// <span id = "limitations-section"></span>
/// # Limitations
///
/// The arguments must be concrete types, and have a fully inferred type.
/// eg: if you pass an integer literal it must have a suffix to indicate its type.
///
/// <span id = "arguments-section"></span>
/// # Arguments
///
/// The arguments take this form
///
/// ```text
/// const_eq_for!(type; left_value, right_value <comparator> )
/// ```
///
/// ### Comparator argument
///
/// The `<comparator>` argument can be any of:
///
/// - ` `(passing nothing): Compares the item using the [`const_eq`] macro.
/// [example](#compare_slices_structs)
///
/// - `, |item| <expression>`:
/// Converts the item with `<expression>` to a type that can be compared using the
/// [`const_eq`] macro.
/// [example](#compare_slices_fieldless_enums)
///
/// - `, |left_item, right_item| <expression>`:
/// Compares the items with `<expression>`, which must evaluate to a `bool`.
/// [example](#compare_options)
///
/// - `, path::to::function`:
/// Compares the items using the passed function, which must evaluate to a `bool`.
/// [example](#compare_ranges_incluside)
///
///
///
/// # Examples
///
/// <span id = "compare_slices_structs"></span>
/// ### Comparing slices of structs
///
/// ```
/// use konst::{const_eq_for, eq_str};
///
/// #[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// pub struct Location {
/// pub file: &'static str,
/// pub column: u32,
/// pub line: u32,
/// }
///
/// konst::impl_cmp! {
/// impl Location;
///
/// pub const fn const_eq(&self, other: &Self) -> bool {
/// eq_str(self.file, other.file) &&
/// self.column == other.column &&
/// self.line == other.line
/// }
/// }
/// #
/// # macro_rules! here {
/// # () => {
/// # $crate::Location{file: file!(), column: column!(), line: line!()}
/// # }
/// # }
/// #
///
/// # fn main () {
/// const HERE: &[Location] = &[here!(), here!(), here!(), here!()];
///
/// const THERE: &[Location] = &[here!(), here!(), here!(), here!()];
///
/// const _: () = {
/// assert!( const_eq_for!(slice; HERE, HERE));
/// assert!(!const_eq_for!(slice; HERE, THERE));
/// assert!( const_eq_for!(slice; THERE, THERE));
/// };
/// # }
///
/// ```
///
/// <span id = "compare_slices_fieldless_enums"></span>
/// ### Comparing slices of field-less enums
///
/// ```rust
/// #[derive(Copy, Clone)]
/// enum Direction {
/// Left,
/// Right,
/// Up,
/// Down,
/// }
///
/// use Direction::*;
///
/// const fn eq_slice_direction(left: &[Direction], right: &[Direction]) -> bool {
/// konst::const_eq_for!(slice; left, right, |&x| x as u8)
/// }
///
/// const CHEAT_CODE: &[Direction] = &[Up, Up, Down, Down, Left, Right, Left, Right];
///
/// const CLOCKWISE: &[Direction] = &[Up, Right, Down, Left];
///
/// const _: () = {
/// assert!( eq_slice_direction(CHEAT_CODE, CHEAT_CODE));
/// assert!(!eq_slice_direction(CHEAT_CODE, CLOCKWISE));
/// assert!( eq_slice_direction(CLOCKWISE, CLOCKWISE));
/// };
///
/// ```
///
/// <span id = "compare_options"></span>
/// ### Comparing `Option`s
///
/// ```rust
/// use konst::const_eq_for;
///
/// const SOME: Option<(u32, u32)> = Some((3, 5));
/// const NONE: Option<(u32, u32)> = None;
///
/// const fn eq_opt_tuple(left: &Option<(u32, u32)>, right: &Option<(u32, u32)>) -> bool {
/// const_eq_for!(option; left, right, |l, r| l.0 == r.0 && l.1 == r.1 )
/// }
///
/// const _: () = {
/// assert!( eq_opt_tuple(&SOME, &SOME));
/// assert!(!eq_opt_tuple(&SOME, &NONE));
/// assert!( eq_opt_tuple(&NONE, &NONE));
/// };
///
/// ```
///
///
/// <span id = "compare_ranges"></span>
/// ### Comparing `Range`s
///
/// ```rust
/// use konst::{const_eq_for, impl_cmp};
///
/// use std::ops::Range;
///
/// #[derive(Copy, Clone)]
/// pub enum Month {
/// January,
/// February,
/// March,
/// April,
/// May,
/// June,
/// July,
/// August,
/// September,
/// October,
/// November,
/// December,
/// }
///
/// use Month::*;
///
/// konst::impl_cmp! {
/// impl Month;
///
/// pub const fn const_eq(&self, other: &Self) -> bool {
/// *self as u8 == *other as u8
/// }
/// }
///
/// const FOO: Range<Month> = January..April;
/// const BAR: Range<Month> = October..December;
///
/// const _: () = {
/// assert!( const_eq_for!(range; FOO, FOO));
/// assert!(!const_eq_for!(range; FOO, BAR));
/// assert!( const_eq_for!(range; BAR, BAR));
/// };
///
/// ```
///
/// <span id = "compare_ranges_incluside"></span>
/// ### Comparing `RangeInclusive`s
///
/// ```rust
/// use konst::{const_eq_for, impl_cmp};
///
/// use std::ops::RangeInclusive;
///
/// #[derive(Copy, Clone)]
/// pub enum WeekDay {
/// Monday,
/// Tuesday,
/// Wednesday,
/// Thursday,
/// Friday,
/// Saturday,
/// Sunday,
/// }
///
/// use WeekDay::*;
///
/// konst::impl_cmp! {
/// impl WeekDay;
///
/// pub const fn const_eq(&self, other: &Self) -> bool {
/// *self as u8 == *other as u8
/// }
/// }
///
/// const FOO: RangeInclusive<WeekDay> = Monday..=Thursday;
/// const BAR: RangeInclusive<WeekDay> = Friday..=Sunday;
///
/// const _: () = {
/// assert!( const_eq_for!(range_inclusive; FOO, FOO));
/// assert!(!const_eq_for!(range_inclusive; FOO, BAR, WeekDay::const_eq));
/// assert!( const_eq_for!(range_inclusive; BAR, BAR, WeekDay::const_eq));
/// };
///
/// ```
///
/// [`ConstCmp`]: const::cmp::ConstCmp
/// [`const_eq`]: macro.const_eq.html
#[cfg(feature = "cmp")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "cmp")))]
#[macro_export]
macro_rules! const_eq_for {
(
slice;
$left_slice:expr,
$right_slice:expr
$(, $($comparison:tt)* )?
) => {
match ($left_slice, $right_slice) {
(left_slice, right_slice) => {
let mut returned = left_slice.len() == right_slice.len();
if returned {
let mut i = 0;
while i != left_slice.len() {
let are_eq = $crate::__priv_const_eq_for!(
left_slice[i],
right_slice[i],
$( $($comparison)* )?
);
if !are_eq {
returned = false;
break;
}
i += 1;
}
}
returned
}
}
};
(
option;
$left_opt:expr,
$right_opt:expr
$(, $($comparison:tt)* )?
) => {
match (&$left_opt, &$right_opt) {
(Some(l), Some(r)) =>
$crate::__priv_const_eq_for!(*l, *r, $( $($comparison)* )?),
(None, None) => true,
_ => false,
}
};
(
range;
$left_range:expr,
$right_range:expr
$(, $($comparison:tt)* )?
) => {
match (&$left_range, &$right_range) {
(left_range, right_range) => {
$crate::__priv_const_eq_for!(
left_range.start,
right_range.start,
$( $($comparison)* )?
) &&
$crate::__priv_const_eq_for!(
left_range.end,
right_range.end,
$( $($comparison)* )?
)
}
}
};
(
range_inclusive;
$left_range:expr,
$right_range:expr
$(, $($comparison:tt)* )?
) => {
match (&$left_range, &$right_range) {
(left_range, right_range) => {
$crate::__priv_const_eq_for!(
left_range.start(),
right_range.start(),
$( $($comparison)* )?
) &&
$crate::__priv_const_eq_for!(
left_range.end(),
right_range.end(),
$( $($comparison)* )?
)
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __priv_const_eq_for {
($left:expr, $right:expr, ) => {
$crate::coerce_to_cmp!($left).const_eq(&$right)
};
($left:expr, $right:expr, |$l:pat_param| $key_expr:expr $(,)*) => {
$crate::coerce_to_cmp!({
let $l = &$left;
$key_expr
})
.const_eq(&{
let $l = &$right;
$key_expr
})
};
($left:expr, $right:expr, |$l:pat_param, $r:pat_param| $eq_expr:expr $(,)*) => {{
let $l = &$left;
let $r = &$right;
$eq_expr
}};
($left:expr, $right:expr, $func:path $(,)*) => {
$func(&$left, &$right)
};
}