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
use core::{
    ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
    str,
};

pub trait Sealed {
    fn __not_object_safe<T>() {}
}

/// This trait is similar to the `SliceIndex` trait in std/core, but it's
/// implemented for array types too.
pub trait SliceIndex<T: ?Sized>: Sealed {
    /// The output type when indexing `T` with this type
    type Output: ?Sized;
}

impl Sealed for usize {}

impl<T> SliceIndex<[T]> for usize {
    type Output = T;
}

impl<T, const N: usize> SliceIndex<[T; N]> for usize {
    type Output = T;
}

macro_rules! impl_si {
    ($($t:ty),* $(,)?) => { $(
        impl Sealed for $t {}

        impl SliceIndex<str> for $t {
            type Output = str;
        }

        impl<T> SliceIndex<[T]> for $t {
            type Output = [T];
        }

        impl<T, const N: usize> SliceIndex<[T; N]> for $t {
            type Output = [T];
        }
    )* };
}

impl_si!(
    Range<usize>,
    RangeFrom<usize>,
    RangeFull,
    RangeInclusive<usize>,
    RangeTo<usize>,
    RangeToInclusive<usize>,
);

pub struct SliceTypeCheck<'a, S: ?Sized, Index: SliceIndex<S>>(pub &'a S, pub Index);

/// A pending slice operation. This can be used to slice `&[T]` and `&str` in a const context
/// with any valid slice index.
///
/// You can use the [`slice!`], [`try_slice!`], [`split_slice_at!`] and [`try_split_slice_at!`]
/// convenience macros instead of using this directly.
///
/// ```rust
/// # use { const_it::Slice, core::ops::Range };
/// const STR: &str = Slice("const slice", ..5).index(); // "const"
/// const BYTES: &[u8] = Slice(b"01234", 1..=3).index(); // b"123"
/// ```
pub struct Slice<'a, S: ?Sized, Index>(pub &'a S, pub Index);

const fn slice<T>(s: &[T], start: usize, end: usize) -> Result<&[T], &'static str> {
    let ptr = s.as_ptr();
    let len = s.len();
    if start > end {
        return Err("slice index start is higher than end");
    }
    if end > len {
        return Err("slice index out of range");
    }
    let new_len = end - start;
    Ok(unsafe {
        // safety: the range has been checked to be valid above
        core::slice::from_raw_parts(ptr.add(start), new_len)
    })
}

const fn slice_inclusive<T>(s: &[T], start: usize, end: usize) -> Result<&[T], &'static str> {
    let ptr = s.as_ptr();
    let len = s.len();
    if start > end {
        return Err("slice index start is higher than end");
    }
    if end >= len {
        return Err("slice index out of range");
    }
    let new_len = end - start + 1;
    Ok(unsafe {
        // safety: the range has been checked to be valid above
        core::slice::from_raw_parts(ptr.add(start), new_len)
    })
}

const fn str_slice(s: &str, start: usize, end: usize) -> Result<&str, &'static str> {
    let bytes = s.as_bytes();
    let sliced = unwrap_ok_or_return!(slice(bytes, start, end));
    if (start < bytes.len() && bytes[start] & 0xc0 == 0x80)
        || (end < bytes.len() && bytes[end] & 0xc0 == 0x80)
    {
        return Err("slice splits utf-8 codepoint");
    }
    Ok(unsafe {
        // safety: the slice was valid utf-8 before and has been checked to not split codepoints
        str::from_utf8_unchecked(sliced)
    })
}

const fn str_slice_inclusive(s: &str, start: usize, end: usize) -> Result<&str, &'static str> {
    let bytes = s.as_bytes();
    let sliced = unwrap_ok_or_return!(slice_inclusive(bytes, start, end));
    if (start < bytes.len() && bytes[start] & 0xc0 == 0x80)
        || (end < usize::MAX && end + 1 < bytes.len() && bytes[end + 1] & 0xc0 == 0x80)
    {
        return Err("slice splits utf-8 codepoint");
    }
    Ok(unsafe {
        // safety: the slice was valid utf-8 before and has been checked to not split codepoints
        str::from_utf8_unchecked(sliced)
    })
}

macro_rules! impl_slice {
    ($(<$(@[$($gen:tt)*])? $slice:ty, $index:ty> $self:ident $imp:block)*) => { $(
        impl<'a $(, $($gen)*)?> Slice<'a, $slice, $index> {
            /// Evaluate this slice operation, or return `None` on error
            pub const fn get(&$self) -> Option<&'a <$index as SliceIndex<$slice>>::Output> {
                ok!($imp)
            }

            /// Evaluate this slice operation, or panic on error
            pub const fn index(&$self) -> &'a <$index as SliceIndex<$slice>>::Output {
                expect_ok!($imp)
            }
        }
    )* };
}

impl<'a, T> Slice<'a, [T], usize> {
    /// Split the slice at the stored index, or panic on error
    pub const fn split(&self) -> (&'a [T], &'a [T]) {
        self.0.split_at(self.1)
    }

    /// Split the slice at the stored index, or return `None` on error
    pub const fn try_split(&self) -> Option<(&'a [T], &'a [T])> {
        if self.1 <= self.0.len() {
            Some(self.split())
        } else {
            None
        }
    }
}

impl<'a, T, const N: usize> Slice<'a, [T; N], usize> {
    /// Split the slice at the stored index, or panic on error
    pub const fn split(&self) -> (&'a [T], &'a [T]) {
        self.0.split_at(self.1)
    }

    /// Split the slice at the stored index, or return `None` on error
    pub const fn try_split(&self) -> Option<(&'a [T], &'a [T])> {
        if self.1 <= self.0.len() {
            Some(self.split())
        } else {
            None
        }
    }
}

impl<'a> Slice<'a, str, usize> {
    /// Split the slice at the stored index, or panic on error
    pub const fn split(&self) -> (&'a str, &'a str) {
        expect_some!(
            self.try_split(),
            "index out of range or inside a unicode codepoint"
        )
    }

    /// Split the slice at the stored index, or return `None` on error
    pub const fn try_split(&self) -> Option<(&'a str, &'a str)> {
        let (a, b) = unwrap_some_or_return!(Slice(self.0.as_bytes(), self.1).try_split());
        if b[0] & 0xc0 == 0x80 {
            None
        } else {
            Some(unsafe {
                // safety: split wasn't in the middle of a codepoint
                (str::from_utf8_unchecked(a), str::from_utf8_unchecked(b))
            })
        }
    }
}

impl_slice! {
    <@[T] [T], usize> self { Ok::<_, &'static str>(&self.0[self.1]) }

    <@[T, const N: usize] [T; N], usize> self { Ok::<_, &'static str>(&self.0[self.1]) }

    <@[T] [T], Range<usize>> self {
        slice(self.0, self.1.start, self.1.end)
    }

    <@[T, const N: usize] [T; N], Range<usize>> self {
        slice(self.0, self.1.start, self.1.end)
    }

    <str, Range<usize>> self {
        str_slice(self.0, self.1.start, self.1.end)
    }

    <@[T] [T], RangeInclusive<usize>> self {
        slice_inclusive(self.0, *self.1.start(), *self.1.end())
    }

    <@[T, const N: usize] [T; N], RangeInclusive<usize>> self {
        slice_inclusive(self.0, *self.1.start(), *self.1.end())
    }

    <str, RangeInclusive<usize>> self {
        str_slice_inclusive(self.0, *self.1.start(), *self.1.end())
    }

    <@[T] [T], RangeFrom<usize>> self {
        slice(self.0, self.1.start, self.0.len())
    }

    <@[T, const N: usize] [T; N], RangeFrom<usize>> self {
        slice(self.0, self.1.start, self.0.len())
    }

    <str, RangeFrom<usize>> self {
        str_slice(self.0, self.1.start, self.0.len())
    }

    <@[T] [T], RangeFull> self {
        Ok::<_, &'static str>(self.0)
    }

    <@[T, const N: usize] [T; N], RangeFull> self {
        Ok::<_, &'static str>(self.0)
    }

    <str, RangeFull> self {
        Ok::<_, &'static str>(self.0)
    }

    <@[T] [T], RangeTo<usize>> self {
        slice(self.0, 0, self.1.end)
    }

    <@[T, const N: usize] [T; N], RangeTo<usize>> self {
        slice(self.0, 0, self.1.end)
    }

    <str, RangeTo<usize>> self {
        str_slice(self.0, 0, self.1.end)
    }

    <@[T] [T], RangeToInclusive<usize>> self {
        slice_inclusive(self.0, 0, self.1.end)
    }

    <@[T, const N: usize] [T; N], RangeToInclusive<usize>> self {
        slice_inclusive(self.0, 0, self.1.end)
    }

    <str, RangeToInclusive<usize>> self {
        str_slice_inclusive(self.0, 0, self.1.end)
    }
}