slice_trait/
lib.rs

1#![cfg_attr(not(test), no_std)]
2#![feature(trait_alias)]
3#![feature(const_trait_impl)]
4#![feature(ptr_metadata)]
5#![feature(const_index)]
6#![feature(const_convert)]
7#![cfg_attr(feature = "length", feature(associated_type_defaults))]
8#![cfg_attr(feature = "length", feature(int_roundings))]
9#![cfg_attr(feature = "length", feature(macro_metavar_expr_concat))]
10#![cfg_attr(feature = "length", feature(freeze))]
11#![cfg_attr(feature = "length", feature(generic_const_exprs))]
12#![cfg_attr(feature = "length", feature(const_result_trait_fn))]
13#![cfg_attr(feature = "length", feature(const_cmp))]
14#![cfg_attr(feature = "length", feature(const_default))]
15#![cfg_attr(feature = "length", feature(rustc_attrs))]
16#![cfg_attr(feature = "length", feature(const_destruct))]
17#![cfg_attr(feature = "same", feature(specialization))]
18#![cfg_attr(feature = "alloc", feature(allocator_api))]
19
20//! A trait for any slice, with item as an associated type.
21//!
22//! This crate is a subset of the crate [`slice_ops`](https://crates.io/crates/slice_ops).
23//!
24//! # Example
25//!
26//! ```rust
27//! #![feature(const_trait_impl)]
28//!
29//! use slice_trait::*;
30//!
31//! const A: &[i32] = [1, 2, 3].as_slice();
32//!
33//! const fn first<'a, S: ~const Slice + ?Sized>(slice: &'a S) -> Option<&'a S::Elem>
34//! where
35//!     S::Elem: Copy,
36//! {
37//!     slice.as_slice().first()
38//! }
39//!
40//! assert_eq!(first(A), Some(&1));
41//! ```
42
43#[cfg(feature = "alloc")]
44extern crate alloc;
45
46moddef::moddef!(
47    flat(pub) mod {
48        elem,
49        as_slice,
50        into_boxed_slice for cfg(feature = "alloc"),
51        slice,
52        boxed_slice for cfg(feature = "alloc")
53    },
54    pub mod {
55        same for cfg(feature = "same"),
56        length for cfg(feature = "length")
57    }
58);
59
60#[cfg(test)]
61mod test
62{
63    use crate::*;
64
65    #[test]
66    fn test()
67    {
68        const A: &[i32] = [1, 2, 3].as_slice();
69
70        const fn first<'a, S: [const] Slice + ?Sized>(slice: &'a S) -> Option<&'a S::Elem>
71        where
72            S::Elem: Copy
73        {
74            slice.as_slice().first()
75        }
76
77        assert_eq!(first(A), Some(&1));
78    }
79}
80
81mod private
82{
83    pub trait Slice: crate::AsSlice {}
84
85    impl<T> Slice for [T] {}
86
87    #[cfg(feature = "alloc")]
88    pub trait BoxedSlice: crate::IntoBoxedSlice {}
89
90    #[cfg(feature = "alloc")]
91    impl<T> BoxedSlice for alloc::boxed::Box<[T]> {}
92}