Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code shared from the Rust Playground
#![allow(dead_code)]
#![allow(unused_variables)]
mod naive {
fn foo(x: &[i32], y: i32) -> Option<usize> {
super::real_impl::find(x, y)
}
#[test]
fn test() {
assert_eq!(foo(&[1, 2, 3], 2), Some(1));
assert_eq!(foo(&[1, 2, 3], 4), None);
}
}
mod slice_partial_eq {
fn foo<El>(x: &[El], y: El) -> Option<usize>
where
El: PartialEq,
{
super::real_impl::find(x, y)
}
#[test]
fn test() {
assert_eq!(foo(&[1.0, 2.0, 3.0], 2.0), Some(1));
assert_eq!(foo(&[1.0, 2.0, 3.0], 4.0), None);
}
fn refl<El: PartialEq + Copy>(el: El) -> Option<usize> {
foo(&[el], el) // should always return Some(0), right?
}
#[test]
fn dont_find_nan() {
assert_eq!(refl(std::f64::NAN), None);
}
}
mod slice_eq {
fn foo<El>(x: &[El], y: El) -> Option<usize>
where
El: Eq,
{
super::real_impl::find(x, y)
}
}
mod seq {
fn foo<'a, El: 'a>(x: impl IntoIterator<Item = &'a El>, y: El) -> Option<usize>
where
El: Eq,
{
super::real_impl::find(x, y)
}
}
mod gen_arr {
use generic_array::{ArrayLength, GenericArray};
fn foo<El, Size>(x: GenericArray<El, Size>, y: El) -> Option<usize>
where
El: Eq,
Size: ArrayLength<El>,
{
super::real_impl::find(&x, y)
}
#[test]
fn test() {
let vec: GenericArray<_, typenum::U3> = vec![1, 2, 3].into_iter().collect();
assert_eq!(foo(vec, 2), Some(1));
assert_eq!(foo(vec, 4), None);
}
}
mod gen_arr_typed_out {
use generic_array::{ArrayLength, GenericArray};
use typenum::{IsLess, Unsigned, B1};
trait UnsignedLessThan<T> {
fn as_usize(&self) -> usize;
}
impl<Less, More> UnsignedLessThan<More> for Less
where
Less: IsLess<More, Output = B1>,
Less: Unsigned,
{
fn as_usize(&self) -> usize {
<Self as Unsigned>::USIZE
}
}
fn foo<El, Size>(x: GenericArray<El, Size>, y: El) -> Option<Box<dyn UnsignedLessThan<Size>>>
where
El: Eq,
Size: ArrayLength<El>,
{
unimplemented!(); // did you really think there'll be a one-liner here?
}
}
mod real_impl {
pub fn find<'a, El: 'a>(haystack: impl IntoIterator<Item = &'a El>, needle: El) -> Option<usize>
where
El: core::cmp::PartialEq,
{
haystack
.into_iter()
.enumerate()
.find(|(_, item)| item == &&needle)
.map(|(index, _)| index)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment