Skip to main content

vstd/std_specs/
slice.rs

1use super::super::prelude::*;
2use super::super::slice::SliceIndexSpec;
3use super::cmp::OrdSpec;
4use super::core::IndexSpec;
5use super::iter::IteratorSpec;
6use super::range::{
7    ExRange, RangeBoundsSpec, slice_range_end, slice_range_start, slice_range_valid,
8    spec_range_inclusive_is_empty,
9};
10
11use core::cmp::Ordering;
12use core::ops::{
13    Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
14};
15use core::slice::{Chunks, Iter, IterMut, SliceIndex};
16
17use verus as verus_skip_verusfmt;
18verus_skip_verusfmt! {
19
20impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for usize {
21    open spec fn in_bounds(&self, slice: &[T]) -> bool {
22        *self < slice@.len()
23    }
24
25    open spec fn index_postcondition(&self, slice: &[T], r: &T) -> bool {
26        r == slice@[self as int]
27    }
28
29    open spec fn index_mut_postcondition(
30        &self,
31        old_slice: &[T],
32        final_slice: &[T],
33        immediate_output: &T,
34        final_output: &T,
35    ) -> bool {
36        &&& *immediate_output == old_slice@[*self as int]
37        &&& final_slice@ == old_slice@.update(*self as int, *final_output)
38    }
39}
40
41pub assume_specification<T>[ <usize as SliceIndex<[T]>>::get ](i: usize, slice: &[T]) -> Option<&T>;
42
43pub assume_specification<T>[ <usize as SliceIndex<[T]>>::index ](i: usize, slice: &[T]) -> &T
44;
45
46pub assume_specification<T>[ <usize as SliceIndex<[T]>>::get_mut ](i: usize, slice: &mut [T]) -> Option<&mut T>;
47
48pub assume_specification<T>[ <usize as SliceIndex<[T]>>::index_mut ](i: usize, slice: &mut [T]) -> (output: &mut T)
49;
50
51pub open spec fn generic_slice_in_bounds<R: RangeBoundsSpec<usize>, T>(
52    range: &R,
53    s: Seq<T>
54) -> bool {
55    slice_range_valid(range, s.len())
56}
57
58pub open spec fn generic_slice_index_postcondition<R: RangeBoundsSpec<usize>, T>(
59    range: &R,
60    slice: Seq<T>,
61    r: Seq<T>,
62) -> bool {
63    r == slice[slice_range_start(range)..slice_range_end(range, slice.len())]
64}
65
66pub open spec fn generic_slice_index_mut_postcondition<R: RangeBoundsSpec<usize>, T>(
67    range: &R,
68    old_slice: Seq<T>,
69    final_slice: Seq<T>,
70    immediate_output: Seq<T>,
71    final_output: Seq<T>,
72) -> bool {
73    &&& immediate_output == old_slice[slice_range_start(range)..slice_range_end(range, old_slice.len())]
74    &&& final_slice.len() == old_slice.len()
75    &&& final_slice[..slice_range_start(range)] == old_slice[..slice_range_start(range)]
76    &&& final_slice[slice_range_start(range)..slice_range_end(range, old_slice.len())] == final_output
77    &&& final_slice[slice_range_end(range, old_slice.len())..old_slice.len()] ==
78        old_slice[slice_range_end(range, old_slice.len())..old_slice.len()]
79    // The following conjunct can be derived from the above four, but
80    // it's useful to include anyway.
81    &&& final_slice == old_slice[..slice_range_start(range)] + final_output + old_slice[
82           slice_range_end(range, old_slice.len())..old_slice.len()]
83}
84
85impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for Range<usize> {
86    open spec fn in_bounds(&self, slice: &[T]) -> bool {
87        generic_slice_in_bounds(self, slice@)
88    }
89
90    open spec fn index_postcondition(&self, slice: &[T], r: &[T]) -> bool {
91        generic_slice_index_postcondition(self, slice@, r@)
92    }
93
94    open spec fn index_mut_postcondition(
95        &self,
96        old_slice: &[T],
97        final_slice: &[T],
98        immediate_output: &[T],
99        final_output: &[T]
100    ) -> bool {
101        generic_slice_index_mut_postcondition(self, old_slice@, final_slice@, immediate_output@, final_output@)
102    }
103}
104
105pub assume_specification<T>[ <Range<usize> as SliceIndex<[T]>>::get ](i: Range<usize>, slice: &[T]) -> Option<&[T]>;
106
107pub assume_specification<T>[ <Range<usize> as SliceIndex<[T]>>::index ](i: Range<usize>, slice: &[T]) -> (r: &[T])
108;
109
110pub assume_specification<T>[ <Range<usize> as SliceIndex<[T]>>::get_mut ](i: Range<usize>, slice: &mut [T]) -> Option<&mut [T]>;
111
112pub assume_specification<T>[ <Range<usize> as SliceIndex<[T]>>::index_mut ](i: Range<usize>, slice: &mut [T]) -> (r: &mut [T])
113;
114
115impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for RangeTo<usize> {
116    open spec fn in_bounds(&self, slice: &[T]) -> bool {
117        generic_slice_in_bounds(self, slice@)
118    }
119
120    open spec fn index_postcondition(&self, slice: &[T], r: &[T]) -> bool {
121        generic_slice_index_postcondition(self, slice@, r@)
122    }
123
124    open spec fn index_mut_postcondition(
125        &self,
126        old_slice: &[T],
127        final_slice: &[T],
128        immediate_output: &[T],
129        final_output: &[T]
130    ) -> bool {
131        generic_slice_index_mut_postcondition(self, old_slice@, final_slice@, immediate_output@, final_output@)
132    }
133}
134
135pub assume_specification<T>[ <RangeTo<usize> as SliceIndex<[T]>>::get ](i: RangeTo<usize>, slice: &[T]) -> Option<&[T]>;
136
137pub assume_specification<T>[ <RangeTo<usize> as SliceIndex<[T]>>::index ](i: RangeTo<usize>, slice: &[T]) -> (r: &[T])
138;
139
140pub assume_specification<T>[ <RangeTo<usize> as SliceIndex<[T]>>::get_mut ](i: RangeTo<usize>, slice: &mut [T]) -> Option<&mut [T]>;
141
142pub assume_specification<T>[ <RangeTo<usize> as SliceIndex<[T]>>::index_mut ](i: RangeTo<usize>, slice: &mut [T]) -> (r: &mut [T])
143;
144
145impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for RangeFrom<usize> {
146    open spec fn in_bounds(&self, slice: &[T]) -> bool {
147        generic_slice_in_bounds(self, slice@)
148    }
149
150    open spec fn index_postcondition(&self, slice: &[T], r: &[T]) -> bool {
151        generic_slice_index_postcondition(self, slice@, r@)
152    }
153
154    open spec fn index_mut_postcondition(
155        &self,
156        old_slice: &[T],
157        final_slice: &[T],
158        immediate_output: &[T],
159        final_output: &[T]
160    ) -> bool {
161        generic_slice_index_mut_postcondition(self, old_slice@, final_slice@, immediate_output@, final_output@)
162    }
163}
164
165pub assume_specification<T>[ <RangeFrom<usize> as SliceIndex<[T]>>::get ](i: RangeFrom<usize>, slice: &[T]) -> Option<&[T]>;
166
167pub assume_specification<T>[ <RangeFrom<usize> as SliceIndex<[T]>>::index ](i: RangeFrom<usize>, slice: &[T]) -> (r: &[T])
168;
169
170pub assume_specification<T>[ <RangeFrom<usize> as SliceIndex<[T]>>::get_mut ](i: RangeFrom<usize>, slice: &mut [T]) -> Option<&mut [T]>;
171
172pub assume_specification<T>[ <RangeFrom<usize> as SliceIndex<[T]>>::index_mut ](i: RangeFrom<usize>, slice: &mut [T]) -> (r: &mut [T])
173;
174
175impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for RangeToInclusive<usize> {
176    open spec fn in_bounds(&self, slice: &[T]) -> bool {
177        generic_slice_in_bounds(self, slice@)
178    }
179
180    open spec fn index_postcondition(&self, slice: &[T], r: &[T]) -> bool {
181        generic_slice_index_postcondition(self, slice@, r@)
182    }
183
184    open spec fn index_mut_postcondition(
185        &self,
186        old_slice: &[T],
187        final_slice: &[T],
188        immediate_output: &[T],
189        final_output: &[T]
190    ) -> bool {
191        generic_slice_index_mut_postcondition(self, old_slice@, final_slice@, immediate_output@, final_output@)
192    }
193}
194
195pub assume_specification<T>[ <RangeToInclusive<usize> as SliceIndex<[T]>>::get ](i: RangeToInclusive<usize>, slice: &[T]) -> Option<&[T]>;
196
197pub assume_specification<T>[ <RangeToInclusive<usize> as SliceIndex<[T]>>::index ](i: RangeToInclusive<usize>, slice: &[T]) -> (r: &[T])
198;
199
200pub assume_specification<T>[ <RangeToInclusive<usize> as SliceIndex<[T]>>::get_mut ](i: RangeToInclusive<usize>, slice: &mut [T]) -> Option<&mut [T]>;
201
202pub assume_specification<T>[ <RangeToInclusive<usize> as SliceIndex<[T]>>::index_mut ](i: RangeToInclusive<usize>, slice: &mut [T]) -> (r: &mut [T])
203;
204
205impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for RangeFull {
206    open spec fn in_bounds(&self, slice: &[T]) -> bool {
207        generic_slice_in_bounds(self, slice@)
208    }
209
210    open spec fn index_postcondition(&self, slice: &[T], r: &[T]) -> bool {
211        generic_slice_index_postcondition(self, slice@, r@)
212    }
213
214    open spec fn index_mut_postcondition(
215        &self,
216        old_slice: &[T],
217        final_slice: &[T],
218        immediate_output: &[T],
219        final_output: &[T]
220    ) -> bool {
221        generic_slice_index_mut_postcondition(self, old_slice@, final_slice@, immediate_output@, final_output@)
222    }
223}
224
225pub assume_specification<T>[ <RangeFull as SliceIndex<[T]>>::get ](i: RangeFull, slice: &[T]) -> Option<&[T]>;
226
227pub assume_specification<T>[ <RangeFull as SliceIndex<[T]>>::index ](i: RangeFull, slice: &[T]) -> (r: &[T])
228;
229
230pub assume_specification<T>[ <RangeFull as SliceIndex<[T]>>::get_mut ](i: RangeFull, slice: &mut [T]) -> Option<&mut [T]>;
231
232pub assume_specification<T>[ <RangeFull as SliceIndex<[T]>>::index_mut ](i: RangeFull, slice: &mut [T]) -> (r: &mut [T])
233;
234
235// Indexing with an empty range doesn't verify, since std doesn't say whether it
236// panics. `get` still verifies and returns `None` or an empty slice.
237pub uninterp spec fn spec_range_inclusive_unspecified_slice_in_bounds<T>(
238    range: &RangeInclusive<usize>,
239    slice: &[T],
240) -> bool;
241
242impl<T> super::super::slice::SliceIndexSpecImpl<[T]> for RangeInclusive<usize> {
243    open spec fn in_bounds(&self, slice: &[T]) -> bool {
244        if spec_range_inclusive_is_empty(self) {
245            spec_range_inclusive_unspecified_slice_in_bounds(self, slice)
246        } else {
247            generic_slice_in_bounds(self, slice@)
248        }
249    }
250
251    open spec fn index_postcondition(&self, slice: &[T], r: &[T]) -> bool {
252        if spec_range_inclusive_is_empty(self) {
253            r@.len() == 0
254        } else {
255            generic_slice_index_postcondition(self, slice@, r@)
256        }
257    }
258
259    open spec fn index_mut_postcondition(
260        &self,
261        old_slice: &[T],
262        final_slice: &[T],
263        immediate_output: &[T],
264        final_output: &[T]
265    ) -> bool {
266        if spec_range_inclusive_is_empty(self) {
267            &&& immediate_output@.len() == 0
268            &&& final_slice@ == old_slice@
269        } else {
270            generic_slice_index_mut_postcondition(self, old_slice@, final_slice@, immediate_output@, final_output@)
271        }
272    }
273}
274
275pub assume_specification<T>[ <RangeInclusive<usize> as SliceIndex<[T]>>::get ](i: RangeInclusive<usize>, slice: &[T]) -> Option<&[T]>;
276
277pub assume_specification<T>[ <RangeInclusive<usize> as SliceIndex<[T]>>::index ](i: RangeInclusive<usize>, slice: &[T]) -> (r: &[T])
278;
279
280pub assume_specification<T>[ <RangeInclusive<usize> as SliceIndex<[T]>>::get_mut ](i: RangeInclusive<usize>, slice: &mut [T]) -> Option<&mut [T]>;
281
282pub assume_specification<T>[ <RangeInclusive<usize> as SliceIndex<[T]>>::index_mut ](i: RangeInclusive<usize>, slice: &mut [T]) -> (r: &mut [T])
283;
284
285// starts_with
286// Rust compares `needle == &slice[..needle.len()]`
287pub open spec fn spec_slice_starts_with<T: PartialEq>(slice: &[T], needle: &[T]) -> bool {
288    &&& needle@.len() <= slice@.len()
289    &&& forall|i: int| #![auto]
290        0 <= i < needle@.len() ==>
291            <T as super::cmp::PartialEqSpec<T>>::eq_spec(
292                &needle@[i],
293                &slice@[i],
294            )
295}
296
297#[verifier::when_used_as_spec(spec_slice_starts_with)]
298pub assume_specification<T: PartialEq>[ <[T]>::starts_with ](
299    slice: &[T],
300    needle: &[T],
301) -> (result: bool)
302    ensures
303        needle@.len() > slice@.len() ==> !result,
304        <T as super::cmp::PartialEqSpec<T>>::obeys_eq_spec() ==> (result == spec_slice_starts_with(
305            slice,
306            needle,
307        )),
308;
309
310// ends_with
311// Rust compares `needle == &slice[slice.len() - needle.len()..]`.
312pub open spec fn spec_slice_ends_with<T: PartialEq>(slice: &[T], needle: &[T]) -> bool {
313    &&& needle@.len() <= slice@.len()
314    &&& forall|i: int| #![auto]
315        0 <= i < needle@.len() ==>
316            <T as super::cmp::PartialEqSpec<T>>::eq_spec(
317                &needle@[i],
318                &slice@[slice@.len() - needle@.len() + i],
319            )
320}
321
322#[verifier::when_used_as_spec(spec_slice_ends_with)]
323pub assume_specification<T: PartialEq>[ <[T]>::ends_with ](
324    slice: &[T],
325    needle: &[T],
326) -> (result: bool)
327    ensures
328        needle@.len() > slice@.len() ==> !result,
329        <T as super::cmp::PartialEqSpec<T>>::obeys_eq_spec() ==> (result == spec_slice_ends_with(
330            slice,
331            needle,
332        )),
333;
334
335impl<T, I: SliceIndex<[T]>> super::core::IndexSpecImpl<I> for [T] {
336    open spec fn index_req(&self, index: &I) -> bool {
337        index.in_bounds(self)
338    }
339}
340
341pub assume_specification<T, I>[ <[T]>::get::<I> ](slice: &[T], i: I) -> (b: Option<
342    &<I as SliceIndex<[T]>>::Output,
343>) where I: SliceIndex<[T]>
344    ensures
345        call_ensures(<I as SliceIndex<[T]>>::get, (i, slice), b),
346;
347
348pub assume_specification<T, I>[ <[T]>::get_mut::<I> ](slice: &mut [T], i: I) -> (b: Option<
349    &mut <I as SliceIndex<[T]>>::Output,
350>) where I: SliceIndex<[T]>
351    ensures
352        call_ensures(<I as SliceIndex<[T]>>::get_mut, (i, slice), b),
353;
354
355pub assume_specification<T, I: SliceIndex<[T]>>[ <[T] as Index<I>>::index ](
356    slice: &[T],
357    index: I,
358) -> (output: &<I as SliceIndex<[T]>>::Output)
359    ensures
360        call_ensures(<I as SliceIndex<[T]>>::index, (index, slice), output),
361;
362
363pub assume_specification<T, I: SliceIndex<[T]>>[ <[T] as IndexMut<I>>::index_mut ](
364    slice: &mut [T],
365    index: I,
366) -> (output: &mut <I as SliceIndex<[T]>>::Output)
367    ensures
368        call_ensures(<I as SliceIndex<[T]>>::index_mut, (index, slice), output),
369;
370
371// `get_unchecked(i)`/`get_unchecked_mut(i)` share the contract of `index`/`index_mut`, with
372// the in-bounds check as a safety precondition (UB if violated) rather than a panic.
373pub assume_specification<T, I>[ <[T]>::get_unchecked::<I> ](
374    slice: &[T],
375    index: I,
376) -> (output: &<I as SliceIndex<[T]>>::Output) where I: SliceIndex<[T]>
377    requires
378        index.in_bounds(slice),
379    ensures
380        index.index_postcondition(slice, output),
381;
382
383pub assume_specification<T, I>[ <[T]>::get_unchecked_mut::<I> ](
384    slice: &mut [T],
385    index: I,
386) -> (output: &mut <I as SliceIndex<[T]>>::Output) where I: SliceIndex<[T]>
387    requires
388        index.in_bounds(&*old(slice)),
389    ensures
390        index.index_mut_postcondition(&*old(slice), &*final(slice), output, &*final(output)),
391;
392
393impl<T, I, const N: usize> super::core::IndexSpecImpl<I> for [T; N]
394where
395    [T]: Index<I>,
396{
397    open spec fn index_req(&self, index: &I) -> bool {
398        <[T] as IndexSpec<I>>::index_req(self, index)
399    }
400}
401
402pub assume_specification<T, I, const N: usize>[ <[T; N]>::index ](array: &[T; N], index: I) -> (output: &<[T; N] as Index<I>>::Output)
403    where
404        [T]: Index<I>,
405    ensures
406        call_ensures(<[T]>::index, (array, index), output),
407;
408
409pub assume_specification<T, I, const N: usize>[ <[T; N]>::index_mut ](array: &mut [T; N], index: I) -> (output: &mut <[T; N] as Index<I>>::Output)
410    where
411        [T]: IndexMut<I>,
412    ensures
413        exists|slice: &mut [T]| {
414            &&& #[trigger] slice@ == old(array)@
415            &&& final(slice)@ == final(array)@
416            &&& call_ensures(<[T]>::index_mut, (slice, index), output)
417        },
418;
419
420pub assume_specification[ core::hint::unreachable_unchecked ]() -> !
421    requires
422        false,
423;
424
425// slice == slice
426pub assume_specification<T: PartialEq<U>, U>[ <[T] as PartialEq<[U]>>::eq ](
427    left: &[T],
428    right: &[U],
429) -> bool
430;
431
432impl<T, U> super::cmp::PartialEqSpecImpl<[U]> for [T] where T: PartialEq<U> + super::cmp::PartialEqSpec<U> {
433    open spec fn obeys_eq_spec() -> bool {
434        <T as super::cmp::PartialEqSpec<U>>::obeys_eq_spec()
435    }
436
437    open spec fn eq_spec(&self, other: &[U]) -> bool {
438        &&& self@.len() == other@.len()
439        &&& forall|i: int|
440            #![auto]
441            0 <= i < self@.len() ==> <T as super::cmp::PartialEqSpec<U>>::eq_spec(&self@[i], &other@[i])
442    }
443}
444
445// contains
446pub open spec fn spec_slice_contains<T: PartialEq<T>>(slice: &[T], value: &T) -> bool {
447    exists |i: int| #![auto] 0 <= i < slice@.len()
448        && <T as super::cmp::PartialEqSpec<T>>::eq_spec(&slice[i], value)
449}
450
451#[verifier::when_used_as_spec(spec_slice_contains)]
452pub assume_specification<T>[ <[T]>::contains ] (slice: &[T], value: &T) -> (result: bool)
453    where
454        T: PartialEq<T>,
455        ensures
456            <T as super::cmp::PartialEqSpec<T>>::obeys_eq_spec() ==> result == spec_slice_contains(slice, value),
457;
458
459// reverse
460pub assume_specification<T>[ <[T]>::reverse ](slice: &mut [T])
461    ensures
462        final(slice)@ == old(slice)@.reverse(),
463;
464
465// swap
466pub assume_specification<T>[ <[T]>::swap ](slice: &mut [T], a: usize, b: usize)
467    requires
468        a < old(slice)@.len(),
469        b < old(slice)@.len(),
470    ensures
471        final(slice)@ == old(slice)@.update(a as int, old(slice)@[b as int]).update(b as int, old(slice)@[a as int]),
472    no_unwind
473;
474
475// rotate_left
476pub assume_specification<T>[ <[T]>::rotate_left ](slice: &mut [T], mid: usize)
477    requires
478        mid <= old(slice)@.len(),
479    ensures
480        final(slice)@ == old(slice)@[mid as int..] + old(slice)@[..mid as int],
481    no_unwind
482;
483
484// rotate_right
485pub assume_specification<T>[ <[T]>::rotate_right ](slice: &mut [T], k: usize)
486    requires
487        k <= old(slice)@.len(),
488    ensures
489        final(slice)@ == old(slice)@[old(slice)@.len() - k..] + old(slice)@[..old(slice)@.len() - k],
490    no_unwind
491;
492
493// The `iter` method of a `<T>` returns an iterator of type `Iter<'_, T>`,
494// so we specify that type here.
495#[verifier::external_type_specification]
496#[verifier::external_body]
497#[verifier::accept_recursive_types(T)]
498pub struct ExIter<'a, T: 'a>(Iter<'a, T>);
499
500// To allow reasoning about the "contents" of the slice iterator, without using
501// a prophecy, we need a function that gives us the underlying sequence of the original slice.
502pub uninterp spec fn into_iter_elts<'a, T: 'a>(i: Iter<'a, T>) -> Seq<T>;
503
504impl <'a, T: 'a> super::iter::IteratorSpecImpl for Iter<'a, T> {
505    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
506        true
507    }
508
509    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
510    #[verifier::prophetic]
511    open spec fn produces(&self) -> Seq<bool> {
512        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
513    }
514    uninterp spec fn decrease(&self) -> Option<nat>;
515
516    open spec fn peek(&self, index: int) -> Option<Self::Item> {
517        if 0 <= index < into_iter_elts(*self).len() {
518            Some(&into_iter_elts(*self)[index])
519        } else {
520            None
521        }
522    }
523}
524
525pub assume_specification<'a, T>[ <[T]>::iter ](s: &'a [T]) -> (iter: Iter<'a, T>)
526    ensures
527        IteratorSpec::remaining(&iter) == s@.as_ref(),
528        // Stated via `len()` so callers learn that the length fits in a `usize`
529        // (needed, e.g., by `enumerate` and `position`)
530        IteratorSpec::remaining(&iter).len() == s.len(),
531        into_iter_elts(iter) == IteratorSpec::remaining(&iter).unref(),
532        IteratorSpec::decrease(&iter) is Some,
533;
534
535pub assume_specification<'a, T> [<&'a [T] as core::iter::IntoIterator>::into_iter] (s: &'a [T]) ->
536    (iter: Iter<'a, T>)
537    ensures
538        IteratorSpec::remaining(&iter) == s@.as_ref(),
539        IteratorSpec::remaining(&iter).len() == s.len(),
540        into_iter_elts(iter) == IteratorSpec::remaining(&iter).unref(),
541        IteratorSpec::decrease(&iter) is Some,
542;
543
544/***********************************************************************************************
545 * Definitions for `slice::IterMut` (the iterator behind `<[T]>::iter_mut` and `Vec::iter_mut`)
546 ***********************************************************************************************/
547#[verifier::external_type_specification]
548#[verifier::external_body]
549#[verifier::accept_recursive_types(T)]
550pub struct ExIterMut<'a, T: 'a>(IterMut<'a, T>);
551
552// See exampes/iterators/slice_iter_mut.rs for a verified implementation of this interface.
553// Any changes here should first be verified over there.
554impl<'a, T: 'a> super::iter::IteratorSpecImpl for IterMut<'a, T> {
555    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
556        true
557    }
558
559    #[verifier::prophetic]
560    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
561
562    #[verifier::prophetic]
563    open spec fn produces(&self) -> Seq<bool> {
564        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
565    }
566
567    uninterp spec fn decrease(&self) -> Option<nat>;
568
569    open spec fn peek(&self, index: int) -> Option<Self::Item> { None }
570}
571
572// Also covers `vec.iter_mut(), which reaches this slice fn through `Vec`'s `DerefMut`
573pub assume_specification<'a, T>[ <[T]>::iter_mut ](slice: &'a mut [T]) -> (iter: IterMut<'a, T>)
574    ensures
575        IteratorSpec::remaining(&iter).len() == old(slice)@.len() == final(slice)@.len(),
576        IteratorSpec::remaining(&iter).len() == old(slice).len(),
577        // Each yielded reference initially points at the corresponding element...
578        forall|i: int| #![trigger IteratorSpec::remaining(&iter)[i]]
579            0 <= i < old(slice)@.len() ==> *(IteratorSpec::remaining(&iter)[i]) == old(slice)@[i],
580        // ...and its eventual value flows back to the corresponding element.
581        forall|i: int|
582            #![trigger IteratorSpec::remaining(&iter)[i]]
583            #![trigger final(slice)@[i]]
584            0 <= i < old(slice)@.len() ==> *final(IteratorSpec::remaining(&iter)[i]) == final(slice)@[i],
585        IteratorSpec::obeys_prophetic_iter_laws(&iter),
586        IteratorSpec::produces(&iter).all(|p: bool| p),
587        IteratorSpec::decrease(&iter) is Some,
588;
589
590pub assume_specification<T> [ <[T]>::first ](slice: &[T]) -> (res: Option<&T>)
591    ensures
592        slice.len() == 0 ==> res.is_none(),
593        slice.len() != 0 ==> res.is_some() && res.unwrap() == slice[0]
594    no_unwind
595;
596
597pub assume_specification<T> [ <[T]>::last ](slice: &[T]) -> (res: Option<&T>)
598    ensures
599        slice.len() == 0 ==> res.is_none(),
600        slice.len() != 0 ==> res.is_some() && res.unwrap() == slice@.last()
601    no_unwind
602;
603
604#[doc(hidden)]
605pub assume_specification<T> [ <[T]>::first_mut ](slice: &mut [T]) -> (res: Option<&mut T>)
606    ensures
607        old(slice).len() == 0 ==> res.is_none() && final(slice)@ == seq![],
608        old(slice).len() != 0 ==> res.is_some() && *res.unwrap() == old(slice)[0]
609            && final(slice)@ == old(slice)@.update(0, *final(res.unwrap()))
610    no_unwind
611;
612
613#[doc(hidden)]
614pub assume_specification<T> [ <[T]>::last_mut ](slice: &mut [T]) -> (res: Option<&mut T>)
615    ensures
616        old(slice).len() == 0 ==> res.is_none() && final(slice)@ == seq![],
617        old(slice).len() != 0 ==> res.is_some() && *res.unwrap() == old(slice)@.last()
618            && final(slice)@ == old(slice)@.update(old(slice).len() - 1, *final(res.unwrap()))
619    no_unwind
620;
621
622pub assume_specification<T> [ <[T]>::split_at ](slice: &[T], mid: usize) -> (ret: (&[T], &[T]))
623    requires
624        0 <= mid <= slice.len(),
625    ensures
626        ret.0@ == slice@[..mid],
627        ret.1@ == slice@[mid..],
628    no_unwind
629;
630
631#[doc(hidden)]
632pub assume_specification<T> [ <[T]>::split_at_mut ](slice: &mut [T], mid: usize) -> (ret: (&mut [T], &mut [T]))
633    requires
634        0 <= mid <= slice.len(),
635    ensures
636        ret.0@ == old(slice)@[..mid],
637        ret.1@ == old(slice)@[mid..],
638        final(slice)@ == final(ret.0)@ + final(ret.1)@,
639    no_unwind
640;
641
642// The non-panicking (`Option`-returning) form of `split_at`: `Some((a, b))` split at `mid`
643// when `mid <= len`, else `None`.
644pub assume_specification<T> [ <[T]>::split_at_checked ](slice: &[T], mid: usize) -> (ret: Option<(&[T], &[T])>)
645    ensures
646        mid <= slice.len() ==> (ret matches Some((a, b))
647            && a@ == slice@[..mid]
648            && b@ == slice@[mid..]),
649        mid > slice.len() ==> ret is None,
650    no_unwind
651;
652
653pub assume_specification<T> [ <[T]>::split_at_unchecked ](slice: &[T], mid: usize) -> (ret: (&[T], &[T]))
654    requires
655        0 <= mid <= slice.len(),
656    ensures
657        ret.0@ == slice@[..mid],
658        ret.1@ == slice@[mid..],
659    no_unwind
660;
661
662#[doc(hidden)]
663pub assume_specification<T> [ <[T]>::split_at_mut_unchecked ](slice: &mut [T], mid: usize) -> (ret: (&mut [T], &mut [T]))
664    requires
665        0 <= mid <= slice.len(),
666    ensures
667        ret.0@ == old(slice)@[..mid],
668        ret.1@ == old(slice)@[mid..],
669        final(slice)@ == final(ret.0)@ + final(ret.1)@,
670    no_unwind
671;
672
673pub assume_specification<T> [ <[T]>::split_first ](slice: &[T]) -> (ret: Option<(&T, &[T])>)
674    ensures
675        slice.len() == 0 ==> ret.is_none(),
676        slice.len() > 0 ==> (ret matches Some((a, b)) && a == slice[0] && b@ == slice@[1..])
677    no_unwind
678;
679
680pub assume_specification<T> [ <[T]>::split_first_mut ](slice: &mut [T]) -> (ret: Option<(&mut T, &mut [T])>)
681    ensures
682        old(slice).len() == 0 ==> ret.is_none() && final(slice)@ == seq![],
683        old(slice).len() > 0 ==> (ret matches Some((a, b))
684            && *a == old(slice)[0]
685            && b@ == old(slice)@[1..]
686            && b@.len() == final(b)@.len()
687            && final(slice)@ == seq![*final(a)] + final(b)@
688        )
689    no_unwind
690;
691
692/// Copy the contents of `src` into `dst`, which must have the same length.
693pub assume_specification<T: Copy>[ <[T]>::copy_from_slice ](dst: &mut [T], src: &[T])
694    requires
695        old(dst)@.len() == src@.len(),
696    ensures
697        final(dst)@ == src@,
698;
699
700/// The sequence resulting from copying `old_slice[src_start..src_end]` to start
701/// at index `dest`, leaving all other positions unchanged. Reads are taken from
702/// `old_slice`, so overlapping source and destination ranges are handled like
703/// std's `<[T]>::copy_within` (which uses `ptr::copy`).
704pub open spec fn copy_within_result<T>(
705    old_slice: Seq<T>,
706    src_start: int,
707    src_end: int,
708    dest: int,
709) -> Seq<T> {
710    let count = src_end - src_start;
711    Seq::new(
712        old_slice.len(),
713        |i: int|
714            if dest <= i && i < dest + count {
715                old_slice[src_start + (i - dest)]
716            } else {
717                old_slice[i]
718            },
719    )
720}
721
722/// Copy the elements in range `src` within the slice to start at index `dest`.
723pub assume_specification<T: Copy, R: core::ops::RangeBounds<usize>>[ <[T]>::copy_within::<R> ](
724    slice: &mut [T],
725    src: R,
726    dest: usize,
727)
728    requires
729        slice_range_valid(&src, old(slice)@.len()),
730        (dest as int) + (slice_range_end(&src, old(slice)@.len()) - slice_range_start(&src))
731            <= old(slice)@.len(),
732    ensures
733        final(slice)@ == copy_within_result(
734            old(slice)@,
735            slice_range_start(&src),
736            slice_range_end(&src, old(slice)@.len()),
737            dest as int,
738        ),
739;
740
741// The `chunks` method of a `[T]` returns an iterator of type `Chunks<'_, T>`,
742// so we specify that type here.
743#[verifier::external_type_specification]
744#[verifier::external_body]
745#[verifier::accept_recursive_types(T)]
746pub struct ExChunks<'a, T: 'a>(Chunks<'a, T>);
747
748// To allow reasoning about the "chunks" of the slice iterator, without using
749// a prophecy, we need a function that gives us the the sequence of chunk slices
750// remaining in the iterator.
751pub uninterp spec fn after_chunks_elts<'a, T: 'a>(i: Chunks<'a, T>) -> Seq<&'a [T]>;
752
753impl<'a, T: 'a> super::iter::IteratorSpecImpl for Chunks<'a, T> {
754    open spec fn obeys_prophetic_iter_laws(&self) -> bool {
755        true
756    }
757
758    uninterp spec fn remaining(&self) -> Seq<Self::Item>;
759
760    #[verifier::prophetic]
761    open spec fn produces(&self) -> Seq<bool> {
762        Seq::new(IteratorSpec::remaining(self).len(), |i: int| true)
763    }
764
765    uninterp spec fn decrease(&self) -> Option<nat>;
766
767    open spec fn peek(&self, index: int) -> Option<Self::Item> {
768        if 0 <= index < after_chunks_elts(*self).len() {
769            Some(after_chunks_elts(*self)[index])
770        } else {
771            None
772        }
773    }
774}
775
776pub assume_specification<'a, T>[ <[T]>::chunks ](s: &'a [T], chunk_size: usize) -> (iter: Chunks<
777    'a,
778    T,
779>)
780    requires
781        chunk_size > 0,
782    ensures
783        IteratorSpec::remaining(&iter) == after_chunks_elts(iter),
784        IteratorSpec::remaining(&iter).len() == (s@.len() + chunk_size as int - 1) / (
785        chunk_size as int),
786        // Each chunk is non-empty, so there are at most `s.len()` of them.
787        // This lets callers learn that the length fits in a `usize`
788        // (needed, e.g., by `enumerate` and `position`)
789        IteratorSpec::remaining(&iter).len() <= s.len(),
790        forall|i: int|
791            #![trigger IteratorSpec::remaining(&iter)[i]]
792            0 <= i < IteratorSpec::remaining(&iter).len() ==> {
793                let start = i * chunk_size as int;
794                let end = if start + chunk_size as int <= s@.len() {
795                    start + chunk_size as int
796                } else {
797                    s@.len() as int
798                };
799
800                IteratorSpec::remaining(&iter)[i]@ == s@.subrange(start, end)
801            },
802        IteratorSpec::decrease(&iter) is Some,
803;
804
805
806// ------------------------------------------------------------------ sorting
807//
808// Since Rust 1.81, std's sorts may panic if the order is not total ("user-provided comparison
809// function does not correctly implement a total order"), so each sort requires one.
810
811/// `a` is not after `b` in `Ord`'s order
812pub open spec fn cmp_le<T: Ord>(a: T, b: T) -> bool {
813    OrdSpec::cmp_spec(&a, &b) != Ordering::Greater
814}
815
816/// `s` is sorted by `le` (as `relations::sorted_by`, with triggers on the elements, so that a
817/// fact about `s[i]` and `s[j]` is enough to learn their order)
818pub open spec fn sorted_by_le<T>(s: Seq<T>, le: spec_fn(T, T) -> bool) -> bool {
819    &&& forall|i: int, j: int| #![trigger s[i], s[j]] 0 <= i < j < s.len() ==> le(s[i], s[j])
820    &&& super::super::relations::sorted_by(s, le)
821}
822
823/// `a` is not after `b` in `compare`'s order (for an element pair `compare` was called on)
824pub open spec fn compare_le<T, F: FnMut(&T, &T) -> Ordering>(compare: F, a: T, b: T) -> bool {
825    forall|o: Ordering| #[trigger] call_ensures(compare, (&a, &b), o) ==> o != Ordering::Greater
826}
827
828/// `a`'s key is not after `b`'s in `K`'s order
829pub open spec fn key_le<T, K: Ord, F: FnMut(&T) -> K>(f: F, a: T, b: T) -> bool {
830    forall|ka: K, kb: K|
831        #[trigger] call_ensures(f, (&a,), ka) && #[trigger] call_ensures(f, (&b,), kb)
832            ==> OrdSpec::cmp_spec(&ka, &kb) != Ordering::Greater
833}
834
835/// `compare` is a total order on the elements of `s` (antisymmetric, transitive, and
836/// deterministic), which std's sorts require: since Rust 1.81 they may panic otherwise
837/// ("user-provided comparison function does not correctly implement a total order").
838pub open spec fn cmp_fn_total_on<T, F: FnMut(&T, &T) -> Ordering>(compare: F, s: Seq<T>) -> bool {
839    &&& forall |i: int, j: int, o1: Ordering, o2: Ordering|
840        #![trigger call_ensures(compare, (&s[i], &s[j]), o1), call_ensures(compare, (&s[j], &s[i]), o2)]
841        0 <= i < s.len() && 0 <= j < s.len()
842            && call_ensures(compare, (&s[i], &s[j]), o1) && call_ensures(compare, (&s[j], &s[i]), o2)
843            ==> o2 == match o1 { Ordering::Less => Ordering::Greater, Ordering::Equal => Ordering::Equal, Ordering::Greater => Ordering::Less }
844    &&& forall |i: int, j: int, o1: Ordering, o2: Ordering|
845        #![trigger call_ensures(compare, (&s[i], &s[j]), o1), call_ensures(compare, (&s[i], &s[j]), o2)]
846        0 <= i < s.len() && 0 <= j < s.len()
847            && call_ensures(compare, (&s[i], &s[j]), o1) && call_ensures(compare, (&s[i], &s[j]), o2)
848            ==> o1 == o2
849    &&& forall |i: int, j: int, k: int, o1: Ordering, o2: Ordering, o3: Ordering|
850        #![trigger call_ensures(compare, (&s[i], &s[j]), o1), call_ensures(compare, (&s[j], &s[k]), o2), call_ensures(compare, (&s[i], &s[k]), o3)]
851        0 <= i < s.len() && 0 <= j < s.len() && 0 <= k < s.len()
852            && call_ensures(compare, (&s[i], &s[j]), o1) && call_ensures(compare, (&s[j], &s[k]), o2)
853            && call_ensures(compare, (&s[i], &s[k]), o3)
854            && o1 != Ordering::Greater && o2 != Ordering::Greater
855            ==> o3 != Ordering::Greater && (o1 == Ordering::Less || o2 == Ordering::Less ==> o3 == Ordering::Less)
856}
857
858/// `f` returns the same key for the same element (std's `sort_by_key` calls it more than once)
859pub open spec fn key_fn_deterministic_on<T, K, F: FnMut(&T) -> K>(f: F, s: Seq<T>) -> bool {
860    forall |i: int, k1: K, k2: K| #![trigger call_ensures(f, (&s[i],), k1), call_ensures(f, (&s[i],), k2)]
861        0 <= i < s.len() && call_ensures(f, (&s[i],), k1) && call_ensures(f, (&s[i],), k2) ==> k1 == k2
862}
863
864#[cfg(feature = "alloc")]
865pub assume_specification<T: Ord>[ <[T]>::sort ](s: &mut [T])
866    requires
867        // std may panic if `Ord` is not a total order (Rust >= 1.81)
868        super::super::laws_cmp::obeys_cmp::<T>(),
869    ensures
870        final(s)@.len() == old(s)@.len(),
871        final(s)@.to_multiset() == old(s)@.to_multiset(),
872        <T as OrdSpec>::obeys_cmp_spec() ==> sorted_by_le(final(s)@, |a: T, b: T| cmp_le(a, b)),
873;
874
875pub assume_specification<T: Ord>[ <[T]>::sort_unstable ](s: &mut [T])
876    requires
877        // std may panic if `Ord` is not a total order (Rust >= 1.81)
878        super::super::laws_cmp::obeys_cmp::<T>(),
879    ensures
880        final(s)@.len() == old(s)@.len(),
881        final(s)@.to_multiset() == old(s)@.to_multiset(),
882        <T as OrdSpec>::obeys_cmp_spec() ==> sorted_by_le(final(s)@, |a: T, b: T| cmp_le(a, b)),
883;
884
885/// The comparator may be called on any two elements.
886#[cfg(feature = "alloc")]
887pub assume_specification<T, F: FnMut(&T, &T) -> Ordering>[ <[T]>::sort_by::<F> ](s: &mut [T], compare: F)
888    requires
889        forall |i: int, j: int| 0 <= i < old(s)@.len() && 0 <= j < old(s)@.len() ==>
890            call_requires(compare, (#[trigger] &old(s)@[i], #[trigger] &old(s)@[j])),
891        // std may panic if `compare` is not a total order (Rust >= 1.81)
892        cmp_fn_total_on(compare, old(s)@),
893    ensures
894        final(s)@.len() == old(s)@.len(),
895        final(s)@.to_multiset() == old(s)@.to_multiset(),
896        sorted_by_le(final(s)@, |a: T, b: T| compare_le(compare, a, b)),
897;
898
899pub assume_specification<T, F: FnMut(&T, &T) -> Ordering>[ <[T]>::sort_unstable_by::<F> ](s: &mut [T], compare: F)
900    requires
901        forall |i: int, j: int| 0 <= i < old(s)@.len() && 0 <= j < old(s)@.len() ==>
902            call_requires(compare, (#[trigger] &old(s)@[i], #[trigger] &old(s)@[j])),
903        // std may panic if `compare` is not a total order (Rust >= 1.81)
904        cmp_fn_total_on(compare, old(s)@),
905    ensures
906        final(s)@.len() == old(s)@.len(),
907        final(s)@.to_multiset() == old(s)@.to_multiset(),
908        sorted_by_le(final(s)@, |a: T, b: T| compare_le(compare, a, b)),
909;
910
911#[cfg(feature = "alloc")]
912pub assume_specification<T, K: Ord, F: FnMut(&T) -> K>[ <[T]>::sort_by_key::<K, F> ](s: &mut [T], f: F)
913    requires
914        forall |i: int| 0 <= i < old(s)@.len() ==> call_requires(f, (#[trigger] &old(s)@[i],)),
915        // std may panic if the keys' `Ord` is not a total order, or if `f` is not deterministic
916        super::super::laws_cmp::obeys_cmp::<K>(),
917        key_fn_deterministic_on(f, old(s)@),
918    ensures
919        final(s)@.len() == old(s)@.len(),
920        final(s)@.to_multiset() == old(s)@.to_multiset(),
921        <K as OrdSpec>::obeys_cmp_spec() ==> sorted_by_le(final(s)@, |a: T, b: T| key_le(f, a, b)),
922;
923
924pub assume_specification<T, K: Ord, F: FnMut(&T) -> K>[ <[T]>::sort_unstable_by_key::<K, F> ](s: &mut [T], f: F)
925    requires
926        forall |i: int| 0 <= i < old(s)@.len() ==> call_requires(f, (#[trigger] &old(s)@[i],)),
927        // std may panic if the keys' `Ord` is not a total order, or if `f` is not deterministic
928        super::super::laws_cmp::obeys_cmp::<K>(),
929        key_fn_deterministic_on(f, old(s)@),
930    ensures
931        final(s)@.len() == old(s)@.len(),
932        final(s)@.to_multiset() == old(s)@.to_multiset(),
933        <K as OrdSpec>::obeys_cmp_spec() ==> sorted_by_le(final(s)@, |a: T, b: T| key_le(f, a, b)),
934;
935
936} // verus!