Cow<'_, str>.CStr.Cow<'_, str>.CStr.Buf::remaining(). Note that this can return a shorter slice (this\nallows non-continuous internal representation). Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in the big-endian byte order. Read moreself in the little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself. Read moreself. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreRead methods, if empty. Read moreamount of additional bytes from the internal buffer as having been read.\nSubsequent calls to read only return bytes that have not been marked as read. Read morebuf_read_has_data_left)read. Read morebyte or EOF is reached. Read more0xA byte) is reached, and append\nthem to the provided String buffer. Read morecb with a piecewise list of byte slices that when concatenated\nproduce the memory pattern of the corresponding instance of T. Read moreVarULE] typeVarULE] type to the dst buffer. dst should\nbe the size of [Self::encode_var_ule_len()]cb with a piecewise list of byte slices that when concatenated\nproduce the memory pattern of the corresponding instance of T. Read moreVarULE] typeVarULE] type to the dst buffer. dst should\nbe the size of [Self::encode_var_ule_len()]alloc only.alloc only.Type in its binary format. Read moreType.mode version of split_at_position
\nmode version of split_at_position
\n&str, the position\ncorresponds to the byte index of the characterindex bytes. panics if index > lengthindex byte offset. panics if index > length&str, the position\ncorresponds to the byte index of the characterparse() succeeded Read moreThis is a shortcut for [literal][crate::token::literal].
\nfn parser<'s>(s: &mut &'s [u8]) -> ModalResult<&'s [u8]> {\n alt((&\"Hello\"[..], take(5usize))).parse_next(s)\n}\n\nassert_eq!(parser.parse_peek(&b\"Hello, World!\"[..]), Ok((&b\", World!\"[..], &b\"Hello\"[..])));\nassert_eq!(parser.parse_peek(&b\"Something\"[..]), Ok((&b\"hing\"[..], &b\"Somet\"[..])));\nassert!(parser.parse_peek(&b\"Some\"[..]).is_err());\nassert!(parser.parse_peek(&b\"\"[..]).is_err());Stream], turning it into the output Read moreinput, generating O from itStream], turning it into the output Read more&mut Self as a parser Read moreParser Read morestd::convert::From Read moreResult over the output of a parser. Read morestd::str::FromStr to the output of the parser Read moreIncomplete][crate::error::ErrMode::Incomplete] into [Backtrack][crate::error::ErrMode::Backtrack] Read morestd::convert::Fromself and other values to be equal, and is used by ==.Read is implemented for &[u8] by copying from the slice.
Note that reading updates the slice to point to the yet unread part.\nThe slice will be empty when EOF is reached.
\nread_buf)read, except that it reads into a slice of buffers. Read morecan_vector)buf. Read moreread_buf)cursor. Read morebuf. Read morebuf. Read moreRead. Read morelimit bytes from it. Read moreread_array)u8 slice at the given offset. Read moreu8 slice which starts at range.start. Read moreu8 slice at the given offset, and update the offset. Read morePod type at the given offset, and update the offset. Read morePod type at the given offset. Read moreScalar] type.tokens into the stream Read moreSelf::Checkpoint] Read moreReplaced with Stream::trace
Stream::trace]Stream] is can ever be incompleteStream] is currently incompleteself into the binary format of the specified\nPostgres Type, appending it to out. Read moreType.self into the binary format of the specified\nPostgres Type, appending it to out. Read moreType.Output type to be used as StreamCow<'_, str>.CStr.Cow<'_, str>.CStr.Buf::remaining(). Note that this can return a shorter slice (this\nallows non-continuous internal representation). Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in the big-endian byte order. Read moreself in the little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself. Read moreself. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreRead methods, if empty. Read moreamount of additional bytes from the internal buffer as having been read.\nSubsequent calls to read only return bytes that have not been marked as read. Read morebuf_read_has_data_left)read. Read morebyte or EOF is reached. Read more0xA byte) is reached, and append\nthem to the provided String buffer. Read moreImplement deserialize from &u8 for all types which implement BinarySerializable.
\nTryFrom would actually be preferable, but not possible because of the orphan\nrules (not completely sure if this could be resolved)
\ncb with a piecewise list of byte slices that when concatenated\nproduce the memory pattern of the corresponding instance of T. Read moreVarULE] typeVarULE] type to the dst buffer. dst should\nbe the size of [Self::encode_var_ule_len()]cb with a piecewise list of byte slices that when concatenated\nproduce the memory pattern of the corresponding instance of T. Read moreVarULE] typeVarULE] type to the dst buffer. dst should\nbe the size of [Self::encode_var_ule_len()]alloc only.alloc only.Type in its binary format. Read moreType.mode version of split_at_position
\nmode version of split_at_position
\n&str, the position\ncorresponds to the byte index of the characterindex bytes. panics if index > lengthindex byte offset. panics if index > length&str, the position\ncorresponds to the byte index of the characterparse() succeeded Read moreThis is a shortcut for [literal][crate::token::literal].
\nfn parser<'s>(s: &mut &'s [u8]) -> ModalResult<&'s [u8]> {\n alt((&\"Hello\"[..], take(5usize))).parse_next(s)\n}\n\nassert_eq!(parser.parse_peek(&b\"Hello, World!\"[..]), Ok((&b\", World!\"[..], &b\"Hello\"[..])));\nassert_eq!(parser.parse_peek(&b\"Something\"[..]), Ok((&b\"hing\"[..], &b\"Somet\"[..])));\nassert!(parser.parse_peek(&b\"Some\"[..]).is_err());\nassert!(parser.parse_peek(&b\"\"[..]).is_err());Stream], turning it into the output Read moreinput, generating O from itStream], turning it into the output Read more&mut Self as a parser Read moreParser Read morestd::convert::From Read moreResult over the output of a parser. Read morestd::str::FromStr to the output of the parser Read moreIncomplete][crate::error::ErrMode::Incomplete] into [Backtrack][crate::error::ErrMode::Backtrack] Read morestd::convert::Fromself and other values to be equal, and is used by ==.Read is implemented for &[u8] by copying from the slice.
Note that reading updates the slice to point to the yet unread part.\nThe slice will be empty when EOF is reached.
\nread_buf)read, except that it reads into a slice of buffers. Read morecan_vector)buf. Read moreread_buf)cursor. Read morebuf. Read morebuf. Read moreRead. Read morelimit bytes from it. Read moreread_array)u8 slice at the given offset. Read moreu8 slice which starts at range.start. Read moreu8 slice at the given offset, and update the offset. Read morePod type at the given offset, and update the offset. Read morePod type at the given offset. Read moreScalar] type.tokens into the stream Read moreSelf::Checkpoint] Read moreReplaced with Stream::trace
Stream::trace]Stream] is can ever be incompleteStream] is currently incompleteself into the binary format of the specified\nPostgres Type, appending it to out. Read moreType.self into the binary format of the specified\nPostgres Type, appending it to out. Read moreType.Output type to be used as StreamSorts the slice in ascending order, preserving initial order of equal elements.
\nThis sort is stable (i.e., does not reorder equal elements) and O(n * log(n))\nworst-case.
\nIf the implementation of Ord for T does not implement a total order, the function\nmay panic; even if the function exits normally, the resulting order of elements in the slice\nis unspecified. See also the note on panicking below.
When applicable, unstable sorting is preferred because it is generally faster than stable\nsorting and it doesn’t allocate auxiliary memory. See\nsort_unstable. The exception are partially sorted slices, which\nmay be better served with slice::sort.
Sorting types that only implement PartialOrd such as f32 and f64 require\nadditional precautions. For example, f32::NAN != f32::NAN, which doesn’t fulfill the\nreflexivity requirement of Ord. By using an alternative comparison function with\nslice::sort_by such as f32::total_cmp or f64::total_cmp that defines a total\norder users can sort slices containing floating-point values. Alternatively, if all values\nin the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp forms a\ntotal order, it’s possible to sort the slice with sort_by(|a, b| a.partial_cmp(b).unwrap()).
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which\ncombines the fast average case of quicksort with the fast worst case and partial run\ndetection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs\nwith k distinct elements, the expected time to sort the data is O(n * log(k)).
\nThe auxiliary memory allocation behavior depends on the input length. Short slices are\nhandled without allocation, medium sized slices allocate self.len() and beyond that it\nclamps at self.len() / 2.
May panic if the implementation of Ord for T does not implement a total order, or if\nthe Ord implementation itself panics.
All safe functions on slices preserve the invariant that even if the function panics, all\noriginal elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. This ensures that recovery code (for instance inside\nof a Drop or following a catch_unwind) will still have access to all the original\nelements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able\nto dispose of all contained elements.
let mut v = [4, -5, 1, -3, 2];\n\nv.sort();\nassert_eq!(v, [-5, -3, 1, 2, 4]);Sorts the slice in ascending order with a comparison function, preserving initial order of\nequal elements.
\nThis sort is stable (i.e., does not reorder equal elements) and O(n * log(n))\nworst-case.
\nIf the comparison function compare does not implement a total order, the function may\npanic; even if the function exits normally, the resulting order of elements in the slice is\nunspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a) is a comparison function that is neither transitive nor\nreflexive nor total, a < b < c < a with a = 1, b = 2, c = 3. For more information and\nexamples see the Ord documentation.
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which\ncombines the fast average case of quicksort with the fast worst case and partial run\ndetection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs\nwith k distinct elements, the expected time to sort the data is O(n * log(k)).
\nThe auxiliary memory allocation behavior depends on the input length. Short slices are\nhandled without allocation, medium sized slices allocate self.len() and beyond that it\nclamps at self.len() / 2.
May panic if compare does not implement a total order, or if compare itself panics.
All safe functions on slices preserve the invariant that even if the function panics, all\noriginal elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. This ensures that recovery code (for instance inside\nof a Drop or following a catch_unwind) will still have access to all the original\nelements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able\nto dispose of all contained elements.
let mut v = [4, -5, 1, -3, 2];\nv.sort_by(|a, b| a.cmp(b));\nassert_eq!(v, [-5, -3, 1, 2, 4]);\n\n// reverse sorting\nv.sort_by(|a, b| b.cmp(a));\nassert_eq!(v, [4, 2, 1, -3, -5]);Sorts the slice in ascending order with a key extraction function, preserving initial order\nof equal elements.
\nThis sort is stable (i.e., does not reorder equal elements) and O(m * n * log(n))\nworst-case, where the key function is O(m).
\nIf the implementation of Ord for K does not implement a total order, the function\nmay panic; even if the function exits normally, the resulting order of elements in the slice\nis unspecified. See also the note on panicking below.
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which\ncombines the fast average case of quicksort with the fast worst case and partial run\ndetection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs\nwith k distinct elements, the expected time to sort the data is O(n * log(k)).
\nThe auxiliary memory allocation behavior depends on the input length. Short slices are\nhandled without allocation, medium sized slices allocate self.len() and beyond that it\nclamps at self.len() / 2.
May panic if the implementation of Ord for K does not implement a total order, or if\nthe Ord implementation or the key-function f panics.
All safe functions on slices preserve the invariant that even if the function panics, all\noriginal elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. This ensures that recovery code (for instance inside\nof a Drop or following a catch_unwind) will still have access to all the original\nelements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able\nto dispose of all contained elements.
let mut v = [4i32, -5, 1, -3, 2];\n\nv.sort_by_key(|k| k.abs());\nassert_eq!(v, [1, 2, -3, 4, -5]);Sorts the slice in ascending order with a key extraction function, preserving initial order\nof equal elements.
\nThis sort is stable (i.e., does not reorder equal elements) and O(m * n + n *\nlog(n)) worst-case, where the key function is O(m).
\nDuring sorting, the key function is called at most once per element, by using temporary\nstorage to remember the results of key evaluation. The order of calls to the key function is\nunspecified and may change in future versions of the standard library.
\nIf the implementation of Ord for K does not implement a total order, the function\nmay panic; even if the function exits normally, the resulting order of elements in the slice\nis unspecified. See also the note on panicking below.
For simple key functions (e.g., functions that are property accesses or basic operations),\nsort_by_key is likely to be faster.
The current implementation is based on instruction-parallel-network sort by Lukas\nBergdoll, which combines the fast average case of randomized quicksort with the fast worst\ncase of heapsort, while achieving linear time on fully sorted and reversed inputs. And\nO(k * log(n)) where k is the number of distinct elements in the input. It leverages\nsuperscalar out-of-order execution capabilities commonly found in CPUs, to efficiently\nperform the operation.
\nIn the worst case, the algorithm allocates temporary storage in a Vec<(K, usize)> the\nlength of the slice.
May panic if the implementation of Ord for K does not implement a total order, or if\nthe Ord implementation panics.
All safe functions on slices preserve the invariant that even if the function panics, all\noriginal elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. This ensures that recovery code (for instance inside\nof a Drop or following a catch_unwind) will still have access to all the original\nelements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able\nto dispose of all contained elements.
let mut v = [4i32, -5, 1, -3, 2, 10];\n\n// Strings are sorted by lexicographical order.\nv.sort_by_cached_key(|k| k.to_string());\nassert_eq!(v, [-3, -5, 1, 10, 2, 4]);Copies self into a new Vec.
let s = [10, 40, 30];\nlet x = s.to_vec();\n// Here, `s` and `x` can be modified independently.allocator_api)Copies self into a new Vec with an allocator.
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet s = [10, 40, 30];\nlet x = s.to_vec_in(System);\n// Here, `s` and `x` can be modified independently.Converts self into a vector without clones or allocation.
The resulting vector can be converted back into a box via\nVec<T>’s into_boxed_slice method.
let s: Box<[i32]> = Box::new([10, 40, 30]);\nlet x = s.into_vec();\n// `s` cannot be used anymore because it has been converted into `x`.\n\nassert_eq!(x, vec![10, 40, 30]);Flattens a slice of T into a single value Self::Output.
assert_eq!([\"hello\", \"world\"].concat(), \"helloworld\");\nassert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);Flattens a slice of T into a single value Self::Output, placing a\ngiven separator between each.
assert_eq!([\"hello\", \"world\"].join(\" \"), \"hello world\");\nassert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);\nassert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);renamed to join
\nFlattens a slice of T into a single value Self::Output, placing a\ngiven separator between each.
assert_eq!([\"hello\", \"world\"].connect(\" \"), \"hello world\");\nassert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);Returns the number of elements in the slice.
\nlet a = [1, 2, 3];\nassert_eq!(a.len(), 3);Returns true if the slice has a length of 0.
let a = [1, 2, 3];\nassert!(!a.is_empty());\n\nlet b: &[i32] = &[];\nassert!(b.is_empty());Returns the first element of the slice, or None if it is empty.
let v = [10, 40, 30];\nassert_eq!(Some(&10), v.first());\n\nlet w: &[i32] = &[];\nassert_eq!(None, w.first());Returns a mutable reference to the first element of the slice, or None if it is empty.
let x = &mut [0, 1, 2];\n\nif let Some(first) = x.first_mut() {\n *first = 5;\n}\nassert_eq!(x, &[5, 1, 2]);\n\nlet y: &mut [i32] = &mut [];\nassert_eq!(None, y.first_mut());Returns the first and all the rest of the elements of the slice, or None if it is empty.
let x = &[0, 1, 2];\n\nif let Some((first, elements)) = x.split_first() {\n assert_eq!(first, &0);\n assert_eq!(elements, &[1, 2]);\n}Returns the first and all the rest of the elements of the slice, or None if it is empty.
let x = &mut [0, 1, 2];\n\nif let Some((first, elements)) = x.split_first_mut() {\n *first = 3;\n elements[0] = 4;\n elements[1] = 5;\n}\nassert_eq!(x, &[3, 4, 5]);Returns the last and all the rest of the elements of the slice, or None if it is empty.
let x = &[0, 1, 2];\n\nif let Some((last, elements)) = x.split_last() {\n assert_eq!(last, &2);\n assert_eq!(elements, &[0, 1]);\n}Returns the last and all the rest of the elements of the slice, or None if it is empty.
let x = &mut [0, 1, 2];\n\nif let Some((last, elements)) = x.split_last_mut() {\n *last = 3;\n elements[0] = 4;\n elements[1] = 5;\n}\nassert_eq!(x, &[4, 5, 3]);Returns the last element of the slice, or None if it is empty.
let v = [10, 40, 30];\nassert_eq!(Some(&30), v.last());\n\nlet w: &[i32] = &[];\nassert_eq!(None, w.last());Returns a mutable reference to the last item in the slice, or None if it is empty.
let x = &mut [0, 1, 2];\n\nif let Some(last) = x.last_mut() {\n *last = 10;\n}\nassert_eq!(x, &[0, 1, 10]);\n\nlet y: &mut [i32] = &mut [];\nassert_eq!(None, y.last_mut());Returns an array reference to the first N items in the slice.
If the slice is not at least N in length, this will return None.
let u = [10, 40, 30];\nassert_eq!(Some(&[10, 40]), u.first_chunk::<2>());\n\nlet v: &[i32] = &[10];\nassert_eq!(None, v.first_chunk::<2>());\n\nlet w: &[i32] = &[];\nassert_eq!(Some(&[]), w.first_chunk::<0>());Returns a mutable array reference to the first N items in the slice.
If the slice is not at least N in length, this will return None.
let x = &mut [0, 1, 2];\n\nif let Some(first) = x.first_chunk_mut::<2>() {\n first[0] = 5;\n first[1] = 4;\n}\nassert_eq!(x, &[5, 4, 2]);\n\nassert_eq!(None, x.first_chunk_mut::<4>());Returns an array reference to the first N items in the slice and the remaining slice.
If the slice is not at least N in length, this will return None.
let x = &[0, 1, 2];\n\nif let Some((first, elements)) = x.split_first_chunk::<2>() {\n assert_eq!(first, &[0, 1]);\n assert_eq!(elements, &[2]);\n}\n\nassert_eq!(None, x.split_first_chunk::<4>());Returns a mutable array reference to the first N items in the slice and the remaining\nslice.
If the slice is not at least N in length, this will return None.
let x = &mut [0, 1, 2];\n\nif let Some((first, elements)) = x.split_first_chunk_mut::<2>() {\n first[0] = 3;\n first[1] = 4;\n elements[0] = 5;\n}\nassert_eq!(x, &[3, 4, 5]);\n\nassert_eq!(None, x.split_first_chunk_mut::<4>());Returns an array reference to the last N items in the slice and the remaining slice.
If the slice is not at least N in length, this will return None.
let x = &[0, 1, 2];\n\nif let Some((elements, last)) = x.split_last_chunk::<2>() {\n assert_eq!(elements, &[0]);\n assert_eq!(last, &[1, 2]);\n}\n\nassert_eq!(None, x.split_last_chunk::<4>());Returns a mutable array reference to the last N items in the slice and the remaining\nslice.
If the slice is not at least N in length, this will return None.
let x = &mut [0, 1, 2];\n\nif let Some((elements, last)) = x.split_last_chunk_mut::<2>() {\n last[0] = 3;\n last[1] = 4;\n elements[0] = 5;\n}\nassert_eq!(x, &[5, 3, 4]);\n\nassert_eq!(None, x.split_last_chunk_mut::<4>());Returns an array reference to the last N items in the slice.
If the slice is not at least N in length, this will return None.
let u = [10, 40, 30];\nassert_eq!(Some(&[40, 30]), u.last_chunk::<2>());\n\nlet v: &[i32] = &[10];\nassert_eq!(None, v.last_chunk::<2>());\n\nlet w: &[i32] = &[];\nassert_eq!(Some(&[]), w.last_chunk::<0>());Returns a mutable array reference to the last N items in the slice.
If the slice is not at least N in length, this will return None.
let x = &mut [0, 1, 2];\n\nif let Some(last) = x.last_chunk_mut::<2>() {\n last[0] = 10;\n last[1] = 20;\n}\nassert_eq!(x, &[0, 10, 20]);\n\nassert_eq!(None, x.last_chunk_mut::<4>());Returns a reference to an element or subslice depending on the type of\nindex.
\nNone if out of bounds.None if out of bounds.let v = [10, 40, 30];\nassert_eq!(Some(&40), v.get(1));\nassert_eq!(Some(&[10, 40][..]), v.get(0..2));\nassert_eq!(None, v.get(3));\nassert_eq!(None, v.get(0..4));Returns a reference to an element or subslice, without doing bounds\nchecking.
\nFor a safe alternative see get.
Calling this method with an out-of-bounds index is undefined behavior\neven if the resulting reference is not used.
\nYou can think of this like .get(index).unwrap_unchecked(). It’s UB\nto call .get_unchecked(len), even if you immediately convert to a\npointer. And it’s UB to call .get_unchecked(..len + 1),\n.get_unchecked(..=len), or similar.
let x = &[1, 2, 4];\n\nunsafe {\n assert_eq!(x.get_unchecked(1), &2);\n}Returns a mutable reference to an element or subslice, without doing\nbounds checking.
\nFor a safe alternative see get_mut.
Calling this method with an out-of-bounds index is undefined behavior\neven if the resulting reference is not used.
\nYou can think of this like .get_mut(index).unwrap_unchecked(). It’s\nUB to call .get_unchecked_mut(len), even if you immediately convert\nto a pointer. And it’s UB to call .get_unchecked_mut(..len + 1),\n.get_unchecked_mut(..=len), or similar.
let x = &mut [1, 2, 4];\n\nunsafe {\n let elem = x.get_unchecked_mut(1);\n *elem = 13;\n}\nassert_eq!(x, &[1, 13, 4]);Returns a raw pointer to the slice’s buffer.
\nThe caller must ensure that the slice outlives the pointer this\nfunction returns, or else it will end up dangling.
\nThe caller must also ensure that the memory the pointer (non-transitively) points to\nis never written to (except inside an UnsafeCell) using this pointer or any pointer\nderived from it. If you need to mutate the contents of the slice, use as_mut_ptr.
Modifying the container referenced by this slice may cause its buffer\nto be reallocated, which would also make any pointers to it invalid.
\nlet x = &[1, 2, 4];\nlet x_ptr = x.as_ptr();\n\nunsafe {\n for i in 0..x.len() {\n assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));\n }\n}Returns an unsafe mutable pointer to the slice’s buffer.
\nThe caller must ensure that the slice outlives the pointer this\nfunction returns, or else it will end up dangling.
\nModifying the container referenced by this slice may cause its buffer\nto be reallocated, which would also make any pointers to it invalid.
\nlet x = &mut [1, 2, 4];\nlet x_ptr = x.as_mut_ptr();\n\nunsafe {\n for i in 0..x.len() {\n *x_ptr.add(i) += 2;\n }\n}\nassert_eq!(x, &[3, 4, 6]);Returns the two raw pointers spanning the slice.
\nThe returned range is half-open, which means that the end pointer\npoints one past the last element of the slice. This way, an empty\nslice is represented by two equal pointers, and the difference between\nthe two pointers represents the size of the slice.
\nSee as_ptr for warnings on using these pointers. The end pointer\nrequires extra caution, as it does not point to a valid element in the\nslice.
This function is useful for interacting with foreign interfaces which\nuse two pointers to refer to a range of elements in memory, as is\ncommon in C++.
\nIt can also be useful to check if a pointer to an element refers to an\nelement of this slice:
\n\nlet a = [1, 2, 3];\nlet x = &a[1] as *const _;\nlet y = &5 as *const _;\n\nassert!(a.as_ptr_range().contains(&x));\nassert!(!a.as_ptr_range().contains(&y));Returns the two unsafe mutable pointers spanning the slice.
\nThe returned range is half-open, which means that the end pointer\npoints one past the last element of the slice. This way, an empty\nslice is represented by two equal pointers, and the difference between\nthe two pointers represents the size of the slice.
\nSee as_mut_ptr for warnings on using these pointers. The end\npointer requires extra caution, as it does not point to a valid element\nin the slice.
This function is useful for interacting with foreign interfaces which\nuse two pointers to refer to a range of elements in memory, as is\ncommon in C++.
\nGets a reference to the underlying array.
\nIf N is not exactly equal to the length of self, then this method returns None.
Gets a mutable reference to the slice’s underlying array.
\nIf N is not exactly equal to the length of self, then this method returns None.
Swaps two elements in the slice.
\nIf a equals to b, it’s guaranteed that elements won’t change value.
Panics if a or b are out of bounds.
let mut v = [\"a\", \"b\", \"c\", \"d\", \"e\"];\nv.swap(2, 4);\nassert!(v == [\"a\", \"b\", \"e\", \"d\", \"c\"]);slice_swap_unchecked)Swaps two elements in the slice, without doing bounds checking.
\nFor a safe alternative see swap.
Calling this method with an out-of-bounds index is undefined behavior.\nThe caller has to ensure that a < self.len() and b < self.len().
#![feature(slice_swap_unchecked)]\n\nlet mut v = [\"a\", \"b\", \"c\", \"d\"];\n// SAFETY: we know that 1 and 3 are both indices of the slice\nunsafe { v.swap_unchecked(1, 3) };\nassert!(v == [\"a\", \"d\", \"c\", \"b\"]);Reverses the order of elements in the slice, in place.
\nlet mut v = [1, 2, 3];\nv.reverse();\nassert!(v == [3, 2, 1]);Returns an iterator over the slice.
\nThe iterator yields all items from start to end.
\nlet x = &[1, 2, 4];\nlet mut iterator = x.iter();\n\nassert_eq!(iterator.next(), Some(&1));\nassert_eq!(iterator.next(), Some(&2));\nassert_eq!(iterator.next(), Some(&4));\nassert_eq!(iterator.next(), None);Returns an iterator that allows modifying each value.
\nThe iterator yields all items from start to end.
\nlet x = &mut [1, 2, 4];\nfor elem in x.iter_mut() {\n *elem += 2;\n}\nassert_eq!(x, &[3, 4, 6]);Returns an iterator over all contiguous windows of length\nsize. The windows overlap. If the slice is shorter than\nsize, the iterator returns no values.
Panics if size is zero.
let slice = ['l', 'o', 'r', 'e', 'm'];\nlet mut iter = slice.windows(3);\nassert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);\nassert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);\nassert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);\nassert!(iter.next().is_none());If the slice is shorter than size:
let slice = ['f', 'o', 'o'];\nlet mut iter = slice.windows(4);\nassert!(iter.next().is_none());Because the Iterator trait cannot represent the required lifetimes,\nthere is no windows_mut analog to windows;\n[0,1,2].windows_mut(2).collect() would violate the rules of references\n(though a LendingIterator analog is possible). You can sometimes use\nCell::as_slice_of_cells in\nconjunction with windows instead:
use std::cell::Cell;\n\nlet mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];\nlet slice = &mut array[..];\nlet slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();\nfor w in slice_of_cells.windows(3) {\n Cell::swap(&w[0], &w[2]);\n}\nassert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);Returns an iterator over chunk_size elements of the slice at a time, starting at the\nbeginning of the slice.
The chunks are slices and do not overlap. If chunk_size does not divide the length of the\nslice, then the last chunk will not have length chunk_size.
See chunks_exact for a variant of this iterator that returns chunks of always exactly\nchunk_size elements, and rchunks for the same iterator but starting at the end of the\nslice.
If your chunk_size is a constant, consider using as_chunks instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let slice = ['l', 'o', 'r', 'e', 'm'];\nlet mut iter = slice.chunks(2);\nassert_eq!(iter.next().unwrap(), &['l', 'o']);\nassert_eq!(iter.next().unwrap(), &['r', 'e']);\nassert_eq!(iter.next().unwrap(), &['m']);\nassert!(iter.next().is_none());Returns an iterator over chunk_size elements of the slice at a time, starting at the\nbeginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size does not divide the\nlength of the slice, then the last chunk will not have length chunk_size.
See chunks_exact_mut for a variant of this iterator that returns chunks of always\nexactly chunk_size elements, and rchunks_mut for the same iterator but starting at\nthe end of the slice.
If your chunk_size is a constant, consider using as_chunks_mut instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let v = &mut [0, 0, 0, 0, 0];\nlet mut count = 1;\n\nfor chunk in v.chunks_mut(2) {\n for elem in chunk.iter_mut() {\n *elem += count;\n }\n count += 1;\n}\nassert_eq!(v, &[1, 1, 2, 2, 3]);Returns an iterator over chunk_size elements of the slice at a time, starting at the\nbeginning of the slice.
The chunks are slices and do not overlap. If chunk_size does not divide the length of the\nslice, then the last up to chunk_size-1 elements will be omitted and can be retrieved\nfrom the remainder function of the iterator.
Due to each chunk having exactly chunk_size elements, the compiler can often optimize the\nresulting code better than in the case of chunks.
See chunks for a variant of this iterator that also returns the remainder as a smaller\nchunk, and rchunks_exact for the same iterator but starting at the end of the slice.
If your chunk_size is a constant, consider using as_chunks instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let slice = ['l', 'o', 'r', 'e', 'm'];\nlet mut iter = slice.chunks_exact(2);\nassert_eq!(iter.next().unwrap(), &['l', 'o']);\nassert_eq!(iter.next().unwrap(), &['r', 'e']);\nassert!(iter.next().is_none());\nassert_eq!(iter.remainder(), &['m']);Returns an iterator over chunk_size elements of the slice at a time, starting at the\nbeginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size does not divide the\nlength of the slice, then the last up to chunk_size-1 elements will be omitted and can be\nretrieved from the into_remainder function of the iterator.
Due to each chunk having exactly chunk_size elements, the compiler can often optimize the\nresulting code better than in the case of chunks_mut.
See chunks_mut for a variant of this iterator that also returns the remainder as a\nsmaller chunk, and rchunks_exact_mut for the same iterator but starting at the end of\nthe slice.
If your chunk_size is a constant, consider using as_chunks_mut instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let v = &mut [0, 0, 0, 0, 0];\nlet mut count = 1;\n\nfor chunk in v.chunks_exact_mut(2) {\n for elem in chunk.iter_mut() {\n *elem += count;\n }\n count += 1;\n}\nassert_eq!(v, &[1, 1, 2, 2, 0]);Splits the slice into a slice of N-element arrays,\nassuming that there’s no remainder.
This is the inverse operation to as_flattened.
As this is unsafe, consider whether you could use as_chunks or\nas_rchunks instead, perhaps via something like\nif let (chunks, []) = slice.as_chunks() or\nlet (chunks, []) = slice.as_chunks() else { unreachable!() };.
This may only be called when
\nN-element chunks (aka self.len() % N == 0).N != 0.let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];\nlet chunks: &[[char; 1]] =\n // SAFETY: 1-element chunks never have remainder\n unsafe { slice.as_chunks_unchecked() };\nassert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);\nlet chunks: &[[char; 3]] =\n // SAFETY: The slice length (6) is a multiple of 3\n unsafe { slice.as_chunks_unchecked() };\nassert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);\n\n// These would be unsound:\n// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5\n// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowedSplits the slice into a slice of N-element arrays,\nstarting at the beginning of the slice,\nand a remainder slice with length strictly less than N.
The remainder is meaningful in the division sense. Given\nlet (chunks, remainder) = slice.as_chunks(), then:
chunks.len() equals slice.len() / N,remainder.len() equals slice.len() % N, andslice.len() equals chunks.len() * N + remainder.len().You can flatten the chunks back into a slice-of-T with as_flattened.
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime\nvalue, and thus a particular monomorphization will either always panic\nor it will never panic.
\nlet slice = ['l', 'o', 'r', 'e', 'm'];\nlet (chunks, remainder) = slice.as_chunks();\nassert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);\nassert_eq!(remainder, &['m']);If you expect the slice to be an exact multiple, you can combine\nlet-else with an empty slice pattern:
let slice = ['R', 'u', 's', 't'];\nlet (chunks, []) = slice.as_chunks::<2>() else {\n panic!(\"slice didn't have even length\")\n};\nassert_eq!(chunks, &[['R', 'u'], ['s', 't']]);Splits the slice into a slice of N-element arrays,\nstarting at the end of the slice,\nand a remainder slice with length strictly less than N.
The remainder is meaningful in the division sense. Given\nlet (remainder, chunks) = slice.as_rchunks(), then:
remainder.len() equals slice.len() % N,chunks.len() equals slice.len() / N, andslice.len() equals chunks.len() * N + remainder.len().You can flatten the chunks back into a slice-of-T with as_flattened.
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime\nvalue, and thus a particular monomorphization will either always panic\nor it will never panic.
\nlet slice = ['l', 'o', 'r', 'e', 'm'];\nlet (remainder, chunks) = slice.as_rchunks();\nassert_eq!(remainder, &['l']);\nassert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);Splits the slice into a slice of N-element arrays,\nassuming that there’s no remainder.
This is the inverse operation to as_flattened_mut.
As this is unsafe, consider whether you could use as_chunks_mut or\nas_rchunks_mut instead, perhaps via something like\nif let (chunks, []) = slice.as_chunks_mut() or\nlet (chunks, []) = slice.as_chunks_mut() else { unreachable!() };.
This may only be called when
\nN-element chunks (aka self.len() % N == 0).N != 0.let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];\nlet chunks: &mut [[char; 1]] =\n // SAFETY: 1-element chunks never have remainder\n unsafe { slice.as_chunks_unchecked_mut() };\nchunks[0] = ['L'];\nassert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);\nlet chunks: &mut [[char; 3]] =\n // SAFETY: The slice length (6) is a multiple of 3\n unsafe { slice.as_chunks_unchecked_mut() };\nchunks[1] = ['a', 'x', '?'];\nassert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);\n\n// These would be unsound:\n// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5\n// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowedSplits the slice into a slice of N-element arrays,\nstarting at the beginning of the slice,\nand a remainder slice with length strictly less than N.
The remainder is meaningful in the division sense. Given\nlet (chunks, remainder) = slice.as_chunks_mut(), then:
chunks.len() equals slice.len() / N,remainder.len() equals slice.len() % N, andslice.len() equals chunks.len() * N + remainder.len().You can flatten the chunks back into a slice-of-T with as_flattened_mut.
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime\nvalue, and thus a particular monomorphization will either always panic\nor it will never panic.
\nlet v = &mut [0, 0, 0, 0, 0];\nlet mut count = 1;\n\nlet (chunks, remainder) = v.as_chunks_mut();\nremainder[0] = 9;\nfor chunk in chunks {\n *chunk = [count; 2];\n count += 1;\n}\nassert_eq!(v, &[1, 1, 2, 2, 9]);Splits the slice into a slice of N-element arrays,\nstarting at the end of the slice,\nand a remainder slice with length strictly less than N.
The remainder is meaningful in the division sense. Given\nlet (remainder, chunks) = slice.as_rchunks_mut(), then:
remainder.len() equals slice.len() % N,chunks.len() equals slice.len() / N, andslice.len() equals chunks.len() * N + remainder.len().You can flatten the chunks back into a slice-of-T with as_flattened_mut.
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime\nvalue, and thus a particular monomorphization will either always panic\nor it will never panic.
\nlet v = &mut [0, 0, 0, 0, 0];\nlet mut count = 1;\n\nlet (remainder, chunks) = v.as_rchunks_mut();\nremainder[0] = 9;\nfor chunk in chunks {\n *chunk = [count; 2];\n count += 1;\n}\nassert_eq!(v, &[9, 1, 1, 2, 2]);Returns an iterator over overlapping windows of N elements of a slice,\nstarting at the beginning of the slice.
This is the const generic equivalent of windows.
If N is greater than the size of the slice, it will return no windows.
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime\nvalue, and thus a particular monomorphization will either always panic\nor it will never panic.
\nlet slice = [0, 1, 2, 3];\nlet mut iter = slice.array_windows();\nassert_eq!(iter.next().unwrap(), &[0, 1]);\nassert_eq!(iter.next().unwrap(), &[1, 2]);\nassert_eq!(iter.next().unwrap(), &[2, 3]);\nassert!(iter.next().is_none());Returns an iterator over chunk_size elements of the slice at a time, starting at the end\nof the slice.
The chunks are slices and do not overlap. If chunk_size does not divide the length of the\nslice, then the last chunk will not have length chunk_size.
See rchunks_exact for a variant of this iterator that returns chunks of always exactly\nchunk_size elements, and chunks for the same iterator but starting at the beginning\nof the slice.
If your chunk_size is a constant, consider using as_rchunks instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let slice = ['l', 'o', 'r', 'e', 'm'];\nlet mut iter = slice.rchunks(2);\nassert_eq!(iter.next().unwrap(), &['e', 'm']);\nassert_eq!(iter.next().unwrap(), &['o', 'r']);\nassert_eq!(iter.next().unwrap(), &['l']);\nassert!(iter.next().is_none());Returns an iterator over chunk_size elements of the slice at a time, starting at the end\nof the slice.
The chunks are mutable slices, and do not overlap. If chunk_size does not divide the\nlength of the slice, then the last chunk will not have length chunk_size.
See rchunks_exact_mut for a variant of this iterator that returns chunks of always\nexactly chunk_size elements, and chunks_mut for the same iterator but starting at the\nbeginning of the slice.
If your chunk_size is a constant, consider using as_rchunks_mut instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let v = &mut [0, 0, 0, 0, 0];\nlet mut count = 1;\n\nfor chunk in v.rchunks_mut(2) {\n for elem in chunk.iter_mut() {\n *elem += count;\n }\n count += 1;\n}\nassert_eq!(v, &[3, 2, 2, 1, 1]);Returns an iterator over chunk_size elements of the slice at a time, starting at the\nend of the slice.
The chunks are slices and do not overlap. If chunk_size does not divide the length of the\nslice, then the last up to chunk_size-1 elements will be omitted and can be retrieved\nfrom the remainder function of the iterator.
Due to each chunk having exactly chunk_size elements, the compiler can often optimize the\nresulting code better than in the case of rchunks.
See rchunks for a variant of this iterator that also returns the remainder as a smaller\nchunk, and chunks_exact for the same iterator but starting at the beginning of the\nslice.
If your chunk_size is a constant, consider using as_rchunks instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let slice = ['l', 'o', 'r', 'e', 'm'];\nlet mut iter = slice.rchunks_exact(2);\nassert_eq!(iter.next().unwrap(), &['e', 'm']);\nassert_eq!(iter.next().unwrap(), &['o', 'r']);\nassert!(iter.next().is_none());\nassert_eq!(iter.remainder(), &['l']);Returns an iterator over chunk_size elements of the slice at a time, starting at the end\nof the slice.
The chunks are mutable slices, and do not overlap. If chunk_size does not divide the\nlength of the slice, then the last up to chunk_size-1 elements will be omitted and can be\nretrieved from the into_remainder function of the iterator.
Due to each chunk having exactly chunk_size elements, the compiler can often optimize the\nresulting code better than in the case of chunks_mut.
See rchunks_mut for a variant of this iterator that also returns the remainder as a\nsmaller chunk, and chunks_exact_mut for the same iterator but starting at the beginning\nof the slice.
If your chunk_size is a constant, consider using as_rchunks_mut instead, which will\ngive references to arrays of exactly that length, rather than slices.
Panics if chunk_size is zero.
let v = &mut [0, 0, 0, 0, 0];\nlet mut count = 1;\n\nfor chunk in v.rchunks_exact_mut(2) {\n for elem in chunk.iter_mut() {\n *elem += count;\n }\n count += 1;\n}\nassert_eq!(v, &[0, 2, 2, 1, 1]);Returns an iterator over the slice producing non-overlapping runs\nof elements using the predicate to separate them.
\nThe predicate is called for every pair of consecutive elements,\nmeaning that it is called on slice[0] and slice[1],\nfollowed by slice[1] and slice[2], and so on.
let slice = &[1, 1, 1, 3, 3, 2, 2, 2];\n\nlet mut iter = slice.chunk_by(|a, b| a == b);\n\nassert_eq!(iter.next(), Some(&[1, 1, 1][..]));\nassert_eq!(iter.next(), Some(&[3, 3][..]));\nassert_eq!(iter.next(), Some(&[2, 2, 2][..]));\nassert_eq!(iter.next(), None);This method can be used to extract the sorted subslices:
\n\nlet slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];\n\nlet mut iter = slice.chunk_by(|a, b| a <= b);\n\nassert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));\nassert_eq!(iter.next(), Some(&[2, 3][..]));\nassert_eq!(iter.next(), Some(&[2, 3, 4][..]));\nassert_eq!(iter.next(), None);Returns an iterator over the slice producing non-overlapping mutable\nruns of elements using the predicate to separate them.
\nThe predicate is called for every pair of consecutive elements,\nmeaning that it is called on slice[0] and slice[1],\nfollowed by slice[1] and slice[2], and so on.
let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];\n\nlet mut iter = slice.chunk_by_mut(|a, b| a == b);\n\nassert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));\nassert_eq!(iter.next(), Some(&mut [3, 3][..]));\nassert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));\nassert_eq!(iter.next(), None);This method can be used to extract the sorted subslices:
\n\nlet slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];\n\nlet mut iter = slice.chunk_by_mut(|a, b| a <= b);\n\nassert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));\nassert_eq!(iter.next(), Some(&mut [2, 3][..]));\nassert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));\nassert_eq!(iter.next(), None);Divides one slice into two at an index.
\nThe first will contain all indices from [0, mid) (excluding\nthe index mid itself) and the second will contain all\nindices from [mid, len) (excluding the index len itself).
Panics if mid > len. For a non-panicking alternative see\nsplit_at_checked.
let v = ['a', 'b', 'c'];\n\n{\n let (left, right) = v.split_at(0);\n assert_eq!(left, []);\n assert_eq!(right, ['a', 'b', 'c']);\n}\n\n{\n let (left, right) = v.split_at(2);\n assert_eq!(left, ['a', 'b']);\n assert_eq!(right, ['c']);\n}\n\n{\n let (left, right) = v.split_at(3);\n assert_eq!(left, ['a', 'b', 'c']);\n assert_eq!(right, []);\n}Divides one mutable slice into two at an index.
\nThe first will contain all indices from [0, mid) (excluding\nthe index mid itself) and the second will contain all\nindices from [mid, len) (excluding the index len itself).
Panics if mid > len. For a non-panicking alternative see\nsplit_at_mut_checked.
let mut v = [1, 0, 3, 0, 5, 6];\nlet (left, right) = v.split_at_mut(2);\nassert_eq!(left, [1, 0]);\nassert_eq!(right, [3, 0, 5, 6]);\nleft[1] = 2;\nright[1] = 4;\nassert_eq!(v, [1, 2, 3, 4, 5, 6]);Divides one slice into two at an index, without doing bounds checking.
\nThe first will contain all indices from [0, mid) (excluding\nthe index mid itself) and the second will contain all\nindices from [mid, len) (excluding the index len itself).
For a safe alternative see split_at.
Calling this method with an out-of-bounds index is undefined behavior\neven if the resulting reference is not used. The caller has to ensure that\n0 <= mid <= self.len().
let v = ['a', 'b', 'c'];\n\nunsafe {\n let (left, right) = v.split_at_unchecked(0);\n assert_eq!(left, []);\n assert_eq!(right, ['a', 'b', 'c']);\n}\n\nunsafe {\n let (left, right) = v.split_at_unchecked(2);\n assert_eq!(left, ['a', 'b']);\n assert_eq!(right, ['c']);\n}\n\nunsafe {\n let (left, right) = v.split_at_unchecked(3);\n assert_eq!(left, ['a', 'b', 'c']);\n assert_eq!(right, []);\n}Divides one mutable slice into two at an index, without doing bounds checking.
\nThe first will contain all indices from [0, mid) (excluding\nthe index mid itself) and the second will contain all\nindices from [mid, len) (excluding the index len itself).
For a safe alternative see split_at_mut.
Calling this method with an out-of-bounds index is undefined behavior\neven if the resulting reference is not used. The caller has to ensure that\n0 <= mid <= self.len().
let mut v = [1, 0, 3, 0, 5, 6];\n// scoped to restrict the lifetime of the borrows\nunsafe {\n let (left, right) = v.split_at_mut_unchecked(2);\n assert_eq!(left, [1, 0]);\n assert_eq!(right, [3, 0, 5, 6]);\n left[1] = 2;\n right[1] = 4;\n}\nassert_eq!(v, [1, 2, 3, 4, 5, 6]);Divides one slice into two at an index, returning None if the slice is\ntoo short.
If mid ≤ len returns a pair of slices where the first will contain all\nindices from [0, mid) (excluding the index mid itself) and the\nsecond will contain all indices from [mid, len) (excluding the index\nlen itself).
Otherwise, if mid > len, returns None.
let v = [1, -2, 3, -4, 5, -6];\n\n{\n let (left, right) = v.split_at_checked(0).unwrap();\n assert_eq!(left, []);\n assert_eq!(right, [1, -2, 3, -4, 5, -6]);\n}\n\n{\n let (left, right) = v.split_at_checked(2).unwrap();\n assert_eq!(left, [1, -2]);\n assert_eq!(right, [3, -4, 5, -6]);\n}\n\n{\n let (left, right) = v.split_at_checked(6).unwrap();\n assert_eq!(left, [1, -2, 3, -4, 5, -6]);\n assert_eq!(right, []);\n}\n\nassert_eq!(None, v.split_at_checked(7));Divides one mutable slice into two at an index, returning None if the\nslice is too short.
If mid ≤ len returns a pair of slices where the first will contain all\nindices from [0, mid) (excluding the index mid itself) and the\nsecond will contain all indices from [mid, len) (excluding the index\nlen itself).
Otherwise, if mid > len, returns None.
let mut v = [1, 0, 3, 0, 5, 6];\n\nif let Some((left, right)) = v.split_at_mut_checked(2) {\n assert_eq!(left, [1, 0]);\n assert_eq!(right, [3, 0, 5, 6]);\n left[1] = 2;\n right[1] = 4;\n}\nassert_eq!(v, [1, 2, 3, 4, 5, 6]);\n\nassert_eq!(None, v.split_at_mut_checked(7));Returns an iterator over subslices separated by elements that match\npred. The matched element is not contained in the subslices.
let slice = [10, 40, 33, 20];\nlet mut iter = slice.split(|num| num % 3 == 0);\n\nassert_eq!(iter.next().unwrap(), &[10, 40]);\nassert_eq!(iter.next().unwrap(), &[20]);\nassert!(iter.next().is_none());If the first element is matched, an empty slice will be the first item\nreturned by the iterator. Similarly, if the last element in the slice\nis matched, an empty slice will be the last item returned by the\niterator:
\n\nlet slice = [10, 40, 33];\nlet mut iter = slice.split(|num| num % 3 == 0);\n\nassert_eq!(iter.next().unwrap(), &[10, 40]);\nassert_eq!(iter.next().unwrap(), &[]);\nassert!(iter.next().is_none());If two matched elements are directly adjacent, an empty slice will be\npresent between them:
\n\nlet slice = [10, 6, 33, 20];\nlet mut iter = slice.split(|num| num % 3 == 0);\n\nassert_eq!(iter.next().unwrap(), &[10]);\nassert_eq!(iter.next().unwrap(), &[]);\nassert_eq!(iter.next().unwrap(), &[20]);\nassert!(iter.next().is_none());Returns an iterator over mutable subslices separated by elements that\nmatch pred. The matched element is not contained in the subslices.
let mut v = [10, 40, 30, 20, 60, 50];\n\nfor group in v.split_mut(|num| *num % 3 == 0) {\n group[0] = 1;\n}\nassert_eq!(v, [1, 40, 30, 1, 60, 1]);Returns an iterator over subslices separated by elements that match\npred. The matched element is contained in the end of the previous\nsubslice as a terminator.
let slice = [10, 40, 33, 20];\nlet mut iter = slice.split_inclusive(|num| num % 3 == 0);\n\nassert_eq!(iter.next().unwrap(), &[10, 40, 33]);\nassert_eq!(iter.next().unwrap(), &[20]);\nassert!(iter.next().is_none());If the last element of the slice is matched,\nthat element will be considered the terminator of the preceding slice.\nThat slice will be the last item returned by the iterator.
\n\nlet slice = [3, 10, 40, 33];\nlet mut iter = slice.split_inclusive(|num| num % 3 == 0);\n\nassert_eq!(iter.next().unwrap(), &[3]);\nassert_eq!(iter.next().unwrap(), &[10, 40, 33]);\nassert!(iter.next().is_none());Returns an iterator over mutable subslices separated by elements that\nmatch pred. The matched element is contained in the previous\nsubslice as a terminator.
let mut v = [10, 40, 30, 20, 60, 50];\n\nfor group in v.split_inclusive_mut(|num| *num % 3 == 0) {\n let terminator_idx = group.len()-1;\n group[terminator_idx] = 1;\n}\nassert_eq!(v, [10, 40, 1, 20, 1, 1]);Returns an iterator over subslices separated by elements that match\npred, starting at the end of the slice and working backwards.\nThe matched element is not contained in the subslices.
let slice = [11, 22, 33, 0, 44, 55];\nlet mut iter = slice.rsplit(|num| *num == 0);\n\nassert_eq!(iter.next().unwrap(), &[44, 55]);\nassert_eq!(iter.next().unwrap(), &[11, 22, 33]);\nassert_eq!(iter.next(), None);As with split(), if the first or last element is matched, an empty\nslice will be the first (or last) item returned by the iterator.
let v = &[0, 1, 1, 2, 3, 5, 8];\nlet mut it = v.rsplit(|n| *n % 2 == 0);\nassert_eq!(it.next().unwrap(), &[]);\nassert_eq!(it.next().unwrap(), &[3, 5]);\nassert_eq!(it.next().unwrap(), &[1, 1]);\nassert_eq!(it.next().unwrap(), &[]);\nassert_eq!(it.next(), None);Returns an iterator over mutable subslices separated by elements that\nmatch pred, starting at the end of the slice and working\nbackwards. The matched element is not contained in the subslices.
let mut v = [100, 400, 300, 200, 600, 500];\n\nlet mut count = 0;\nfor group in v.rsplit_mut(|num| *num % 3 == 0) {\n count += 1;\n group[0] = count;\n}\nassert_eq!(v, [3, 400, 300, 2, 600, 1]);Returns an iterator over subslices separated by elements that match\npred, limited to returning at most n items. The matched element is\nnot contained in the subslices.
The last element returned, if any, will contain the remainder of the\nslice.
\nPrint the slice split once by numbers divisible by 3 (i.e., [10, 40],\n[20, 60, 50]):
let v = [10, 40, 30, 20, 60, 50];\n\nfor group in v.splitn(2, |num| *num % 3 == 0) {\n println!(\"{group:?}\");\n}Returns an iterator over mutable subslices separated by elements that match\npred, limited to returning at most n items. The matched element is\nnot contained in the subslices.
The last element returned, if any, will contain the remainder of the\nslice.
\nlet mut v = [10, 40, 30, 20, 60, 50];\n\nfor group in v.splitn_mut(2, |num| *num % 3 == 0) {\n group[0] = 1;\n}\nassert_eq!(v, [1, 40, 30, 1, 60, 50]);Returns an iterator over subslices separated by elements that match\npred limited to returning at most n items. This starts at the end of\nthe slice and works backwards. The matched element is not contained in\nthe subslices.
The last element returned, if any, will contain the remainder of the\nslice.
\nPrint the slice split once, starting from the end, by numbers divisible\nby 3 (i.e., [50], [10, 40, 30, 20]):
let v = [10, 40, 30, 20, 60, 50];\n\nfor group in v.rsplitn(2, |num| *num % 3 == 0) {\n println!(\"{group:?}\");\n}Returns an iterator over subslices separated by elements that match\npred limited to returning at most n items. This starts at the end of\nthe slice and works backwards. The matched element is not contained in\nthe subslices.
The last element returned, if any, will contain the remainder of the\nslice.
\nlet mut s = [10, 40, 30, 20, 60, 50];\n\nfor group in s.rsplitn_mut(2, |num| *num % 3 == 0) {\n group[0] = 1;\n}\nassert_eq!(s, [1, 40, 30, 20, 60, 1]);slice_split_once)Splits the slice on the first element that matches the specified\npredicate.
\nIf any matching elements are present in the slice, returns the prefix\nbefore the match and suffix after. The matching element itself is not\nincluded. If no elements match, returns None.
#![feature(slice_split_once)]\nlet s = [1, 2, 3, 2, 4];\nassert_eq!(s.split_once(|&x| x == 2), Some((\n &[1][..],\n &[3, 2, 4][..]\n)));\nassert_eq!(s.split_once(|&x| x == 0), None);slice_split_once)Splits the slice on the last element that matches the specified\npredicate.
\nIf any matching elements are present in the slice, returns the prefix\nbefore the match and suffix after. The matching element itself is not\nincluded. If no elements match, returns None.
#![feature(slice_split_once)]\nlet s = [1, 2, 3, 2, 4];\nassert_eq!(s.rsplit_once(|&x| x == 2), Some((\n &[1, 2, 3][..],\n &[4][..]\n)));\nassert_eq!(s.rsplit_once(|&x| x == 0), None);Returns true if the slice contains an element with the given value.
This operation is O(n).
\nNote that if you have a sorted slice, binary_search may be faster.
let v = [10, 40, 30];\nassert!(v.contains(&30));\nassert!(!v.contains(&50));If you do not have a &T, but some other value that you can compare\nwith one (for example, String implements PartialEq<str>), you can\nuse iter().any:
let v = [String::from(\"hello\"), String::from(\"world\")]; // slice of `String`\nassert!(v.iter().any(|e| e == \"hello\")); // search with `&str`\nassert!(!v.iter().any(|e| e == \"hi\"));Returns true if needle is a prefix of the slice or equal to the slice.
let v = [10, 40, 30];\nassert!(v.starts_with(&[10]));\nassert!(v.starts_with(&[10, 40]));\nassert!(v.starts_with(&v));\nassert!(!v.starts_with(&[50]));\nassert!(!v.starts_with(&[10, 50]));Always returns true if needle is an empty slice:
let v = &[10, 40, 30];\nassert!(v.starts_with(&[]));\nlet v: &[u8] = &[];\nassert!(v.starts_with(&[]));Returns true if needle is a suffix of the slice or equal to the slice.
let v = [10, 40, 30];\nassert!(v.ends_with(&[30]));\nassert!(v.ends_with(&[40, 30]));\nassert!(v.ends_with(&v));\nassert!(!v.ends_with(&[50]));\nassert!(!v.ends_with(&[50, 30]));Always returns true if needle is an empty slice:
let v = &[10, 40, 30];\nassert!(v.ends_with(&[]));\nlet v: &[u8] = &[];\nassert!(v.ends_with(&[]));Returns a subslice with the prefix removed.
\nIf the slice starts with prefix, returns the subslice after the prefix, wrapped in Some.\nIf prefix is empty, simply returns the original slice. If prefix is equal to the\noriginal slice, returns an empty slice.
If the slice does not start with prefix, returns None.
let v = &[10, 40, 30];\nassert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));\nassert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));\nassert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));\nassert_eq!(v.strip_prefix(&[50]), None);\nassert_eq!(v.strip_prefix(&[10, 50]), None);\n\nlet prefix : &str = \"he\";\nassert_eq!(b\"hello\".strip_prefix(prefix.as_bytes()),\n Some(b\"llo\".as_ref()));Returns a subslice with the suffix removed.
\nIf the slice ends with suffix, returns the subslice before the suffix, wrapped in Some.\nIf suffix is empty, simply returns the original slice. If suffix is equal to the\noriginal slice, returns an empty slice.
If the slice does not end with suffix, returns None.
let v = &[10, 40, 30];\nassert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));\nassert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));\nassert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));\nassert_eq!(v.strip_suffix(&[50]), None);\nassert_eq!(v.strip_suffix(&[50, 30]), None);Returns a subslice with the prefix and suffix removed.
\nIf the slice starts with prefix, ends with suffix, and\nthe prefix and suffix don’t overlap, returns the subslice after\nthe prefix and before the suffix, wrapped in Some.
If the slice does not start with prefix, does not end with suffix,\nor the prefix and suffix overlap in the slice, returns None.
let v = &[10, 50, 40, 30];\nassert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..]));\nassert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..]));\nassert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..]));\nassert_eq!(v.strip_circumfix(&[50], &[30]), None);\nassert_eq!(v.strip_circumfix(&[10], &[40]), None);\nassert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..]));\nassert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..]));\nassert_eq!(v.strip_circumfix(&[10, 50, 40], &[50, 40, 30]), None);trim_prefix_suffix)Returns a subslice with the optional prefix removed.
\nIf the slice starts with prefix, returns the subslice after the prefix. If prefix\nis empty or the slice does not start with prefix, simply returns the original slice.\nIf prefix is equal to the original slice, returns an empty slice.
#![feature(trim_prefix_suffix)]\n\nlet v = &[10, 40, 30];\n\n// Prefix present - removes it\nassert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);\nassert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);\nassert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);\n\n// Prefix absent - returns original slice\nassert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);\nassert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);\n\nlet prefix : &str = \"he\";\nassert_eq!(b\"hello\".trim_prefix(prefix.as_bytes()), b\"llo\".as_ref());trim_prefix_suffix)Returns a subslice with the optional suffix removed.
\nIf the slice ends with suffix, returns the subslice before the suffix. If suffix\nis empty or the slice does not end with suffix, simply returns the original slice.\nIf suffix is equal to the original slice, returns an empty slice.
#![feature(trim_prefix_suffix)]\n\nlet v = &[10, 40, 30];\n\n// Suffix present - removes it\nassert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);\nassert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);\nassert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);\n\n// Suffix absent - returns original slice\nassert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);\nassert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);Binary searches this slice for a given element.\nIf the slice is not sorted, the returned result is unspecified and\nmeaningless.
\nIf the value is found then Result::Ok is returned, containing the\nindex of the matching element. If there are multiple matches, then any\none of the matches could be returned. The index is chosen\ndeterministically, but is subject to change in future versions of Rust.\nIf the value is not found then Result::Err is returned, containing\nthe index where a matching element could be inserted while maintaining\nsorted order.
See also binary_search_by, binary_search_by_key, and partition_point.
Looks up a series of four elements. The first is found, with a\nuniquely determined position; the second and third are not\nfound; the fourth could match any position in [1, 4].
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];\n\nassert_eq!(s.binary_search(&13), Ok(9));\nassert_eq!(s.binary_search(&4), Err(7));\nassert_eq!(s.binary_search(&100), Err(13));\nlet r = s.binary_search(&1);\nassert!(match r { Ok(1..=4) => true, _ => false, });If you want to find that whole range of matching items, rather than\nan arbitrary matching one, that can be done using partition_point:
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];\n\nlet low = s.partition_point(|x| x < &1);\nassert_eq!(low, 1);\nlet high = s.partition_point(|x| x <= &1);\nassert_eq!(high, 5);\nlet r = s.binary_search(&1);\nassert!((low..high).contains(&r.unwrap()));\n\nassert!(s[..low].iter().all(|&x| x < 1));\nassert!(s[low..high].iter().all(|&x| x == 1));\nassert!(s[high..].iter().all(|&x| x > 1));\n\n// For something not found, the \"range\" of equal items is empty\nassert_eq!(s.partition_point(|x| x < &11), 9);\nassert_eq!(s.partition_point(|x| x <= &11), 9);\nassert_eq!(s.binary_search(&11), Err(9));If you want to insert an item to a sorted vector, while maintaining\nsort order, consider using partition_point:
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];\nlet num = 42;\nlet idx = s.partition_point(|&x| x <= num);\n// If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to\n// `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`\n// to shift less elements.\ns.insert(idx, num);\nassert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);Binary searches this slice with a comparator function.
\nThe comparator function should return an order code that indicates\nwhether its argument is Less, Equal or Greater the desired\ntarget.\nIf the slice is not sorted or if the comparator function does not\nimplement an order consistent with the sort order of the underlying\nslice, the returned result is unspecified and meaningless.
If the value is found then Result::Ok is returned, containing the\nindex of the matching element. If there are multiple matches, then any\none of the matches could be returned. The index is chosen\ndeterministically, but is subject to change in future versions of Rust.\nIf the value is not found then Result::Err is returned, containing\nthe index where a matching element could be inserted while maintaining\nsorted order.
See also binary_search, binary_search_by_key, and partition_point.
Looks up a series of four elements. The first is found, with a\nuniquely determined position; the second and third are not\nfound; the fourth could match any position in [1, 4].
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];\n\nlet seek = 13;\nassert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));\nlet seek = 4;\nassert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));\nlet seek = 100;\nassert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));\nlet seek = 1;\nlet r = s.binary_search_by(|probe| probe.cmp(&seek));\nassert!(match r { Ok(1..=4) => true, _ => false, });Binary searches this slice with a key extraction function.
\nAssumes that the slice is sorted by the key, for instance with\nsort_by_key using the same key extraction function.\nIf the slice is not sorted by the key, the returned result is\nunspecified and meaningless.
If the value is found then Result::Ok is returned, containing the\nindex of the matching element. If there are multiple matches, then any\none of the matches could be returned. The index is chosen\ndeterministically, but is subject to change in future versions of Rust.\nIf the value is not found then Result::Err is returned, containing\nthe index where a matching element could be inserted while maintaining\nsorted order.
See also binary_search, binary_search_by, and partition_point.
Looks up a series of four elements in a slice of pairs sorted by\ntheir second elements. The first is found, with a uniquely\ndetermined position; the second and third are not found; the\nfourth could match any position in [1, 4].
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),\n (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),\n (1, 21), (2, 34), (4, 55)];\n\nassert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));\nassert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));\nassert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));\nlet r = s.binary_search_by_key(&1, |&(a, b)| b);\nassert!(match r { Ok(1..=4) => true, _ => false, });Sorts the slice in ascending order without preserving the initial order of equal elements.
\nThis sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not\nallocate), and O(n * log(n)) worst-case.
\nIf the implementation of Ord for T does not implement a total order, the function\nmay panic; even if the function exits normally, the resulting order of elements in the slice\nis unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a) is a comparison function that is neither transitive nor\nreflexive nor total, a < b < c < a with a = 1, b = 2, c = 3. For more information and\nexamples see the Ord documentation.
All original elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. Same is true if the implementation of Ord for T panics.
Sorting types that only implement PartialOrd such as f32 and f64 require\nadditional precautions. For example, f32::NAN != f32::NAN, which doesn’t fulfill the\nreflexivity requirement of Ord. By using an alternative comparison function with\nslice::sort_unstable_by such as f32::total_cmp or f64::total_cmp that defines a\ntotal order users can sort slices containing floating-point values. Alternatively, if all\nvalues in the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp\nforms a total order, it’s possible to sort the slice with sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()).
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which\ncombines the fast average case of quicksort with the fast worst case of heapsort, achieving\nlinear time on fully sorted and reversed inputs. On inputs with k distinct elements, the\nexpected time to sort the data is O(n * log(k)).
\nIt is typically faster than stable sorting, except in a few special cases, e.g., when the\nslice is partially sorted.
\nMay panic if the implementation of Ord for T does not implement a total order, or if\nthe Ord implementation panics.
let mut v = [4, -5, 1, -3, 2];\n\nv.sort_unstable();\nassert_eq!(v, [-5, -3, 1, 2, 4]);Sorts the slice in ascending order with a comparison function, without preserving the\ninitial order of equal elements.
\nThis sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not\nallocate), and O(n * log(n)) worst-case.
\nIf the comparison function compare does not implement a total order, the function\nmay panic; even if the function exits normally, the resulting order of elements in the slice\nis unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a) is a comparison function that is neither transitive nor\nreflexive nor total, a < b < c < a with a = 1, b = 2, c = 3. For more information and\nexamples see the Ord documentation.
All original elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. Same is true if compare panics.
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which\ncombines the fast average case of quicksort with the fast worst case of heapsort, achieving\nlinear time on fully sorted and reversed inputs. On inputs with k distinct elements, the\nexpected time to sort the data is O(n * log(k)).
\nIt is typically faster than stable sorting, except in a few special cases, e.g., when the\nslice is partially sorted.
\nMay panic if the compare does not implement a total order, or if\nthe compare itself panics.
let mut v = [4, -5, 1, -3, 2];\nv.sort_unstable_by(|a, b| a.cmp(b));\nassert_eq!(v, [-5, -3, 1, 2, 4]);\n\n// reverse sorting\nv.sort_unstable_by(|a, b| b.cmp(a));\nassert_eq!(v, [4, 2, 1, -3, -5]);Sorts the slice in ascending order with a key extraction function, without preserving\nthe initial order of equal elements.
\nThis sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not\nallocate), and O(n * log(n)) worst-case.
\nIf the implementation of Ord for K does not implement a total order, the function\nmay panic; even if the function exits normally, the resulting order of elements in the slice\nis unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a) is a comparison function that is neither transitive nor\nreflexive nor total, a < b < c < a with a = 1, b = 2, c = 3. For more information and\nexamples see the Ord documentation.
All original elements will remain in the slice and any possible modifications via interior\nmutability are observed in the input. Same is true if the implementation of Ord for K panics.
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which\ncombines the fast average case of quicksort with the fast worst case of heapsort, achieving\nlinear time on fully sorted and reversed inputs. On inputs with k distinct elements, the\nexpected time to sort the data is O(n * log(k)).
\nIt is typically faster than stable sorting, except in a few special cases, e.g., when the\nslice is partially sorted.
\nMay panic if the implementation of Ord for K does not implement a total order, or if\nthe Ord implementation panics.
let mut v = [4i32, -5, 1, -3, 2];\n\nv.sort_unstable_by_key(|k| k.abs());\nassert_eq!(v, [1, 2, -3, 4, -5]);slice_partial_sort_unstable)Partially sorts the slice in ascending order without preserving the initial order of equal elements.
\nUpon completion, for the specified range start..end, it’s guaranteed that:
self[..start] is smaller than or equal toself[start..end], which is sorted, and smaller than or equal toself[end..].This partial sort is unstable, meaning it may reorder equal elements in the specified range.\nIt may reorder elements outside the specified range as well, but the guarantees above still hold.
\nThis partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case,\nwhere n is the length of the slice and k is the length of the specified range.
\nSee the documentation of sort_unstable for implementation notes.
May panic if the implementation of Ord for T does not implement a total order, or if\nthe Ord implementation panics, or if the specified range is out of bounds.
#![feature(slice_partial_sort_unstable)]\n\nlet mut v = [4, -5, 1, -3, 2];\n\n// empty range at the beginning, nothing changed\nv.partial_sort_unstable(0..0);\nassert_eq!(v, [4, -5, 1, -3, 2]);\n\n// empty range in the middle, partitioning the slice\nv.partial_sort_unstable(2..2);\nfor i in 0..2 {\n assert!(v[i] <= v[2]);\n}\nfor i in 3..v.len() {\n assert!(v[2] <= v[i]);\n}\n\n// single element range, same as select_nth_unstable\nv.partial_sort_unstable(2..3);\nfor i in 0..2 {\n assert!(v[i] <= v[2]);\n}\nfor i in 3..v.len() {\n assert!(v[2] <= v[i]);\n}\n\n// partial sort a subrange\nv.partial_sort_unstable(1..4);\nassert_eq!(&v[1..4], [-3, 1, 2]);\n\n// partial sort the whole range, same as sort_unstable\nv.partial_sort_unstable(..);\nassert_eq!(v, [-5, -3, 1, 2, 4]);slice_partial_sort_unstable)Partially sorts the slice in ascending order with a comparison function, without\npreserving the initial order of equal elements.
\nUpon completion, for the specified range start..end, it’s guaranteed that:
self[..start] is smaller than or equal toself[start..end], which is sorted, and smaller than or equal toself[end..].This partial sort is unstable, meaning it may reorder equal elements in the specified range.\nIt may reorder elements outside the specified range as well, but the guarantees above still hold.
\nThis partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case,\nwhere n is the length of the slice and k is the length of the specified range.
\nSee the documentation of sort_unstable_by for implementation notes.
May panic if the compare does not implement a total order, or if\nthe compare itself panics, or if the specified range is out of bounds.
#![feature(slice_partial_sort_unstable)]\n\nlet mut v = [4, -5, 1, -3, 2];\n\n// empty range at the beginning, nothing changed\nv.partial_sort_unstable_by(0..0, |a, b| b.cmp(a));\nassert_eq!(v, [4, -5, 1, -3, 2]);\n\n// empty range in the middle, partitioning the slice\nv.partial_sort_unstable_by(2..2, |a, b| b.cmp(a));\nfor i in 0..2 {\n assert!(v[i] >= v[2]);\n}\nfor i in 3..v.len() {\n assert!(v[2] >= v[i]);\n}\n\n// single element range, same as select_nth_unstable\nv.partial_sort_unstable_by(2..3, |a, b| b.cmp(a));\nfor i in 0..2 {\n assert!(v[i] >= v[2]);\n}\nfor i in 3..v.len() {\n assert!(v[2] >= v[i]);\n}\n\n// partial sort a subrange\nv.partial_sort_unstable_by(1..4, |a, b| b.cmp(a));\nassert_eq!(&v[1..4], [2, 1, -3]);\n\n// partial sort the whole range, same as sort_unstable\nv.partial_sort_unstable_by(.., |a, b| b.cmp(a));\nassert_eq!(v, [4, 2, 1, -3, -5]);slice_partial_sort_unstable)Partially sorts the slice in ascending order with a key extraction function, without\npreserving the initial order of equal elements.
\nUpon completion, for the specified range start..end, it’s guaranteed that:
self[..start] is smaller than or equal toself[start..end], which is sorted, and smaller than or equal toself[end..].This partial sort is unstable, meaning it may reorder equal elements in the specified range.\nIt may reorder elements outside the specified range as well, but the guarantees above still hold.
\nThis partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case,\nwhere n is the length of the slice and k is the length of the specified range.
\nSee the documentation of sort_unstable_by_key for implementation notes.
May panic if the implementation of Ord for K does not implement a total order, or if\nthe Ord implementation panics, or if the specified range is out of bounds.
#![feature(slice_partial_sort_unstable)]\n\nlet mut v = [4i32, -5, 1, -3, 2];\n\n// empty range at the beginning, nothing changed\nv.partial_sort_unstable_by_key(0..0, |k| k.abs());\nassert_eq!(v, [4, -5, 1, -3, 2]);\n\n// empty range in the middle, partitioning the slice\nv.partial_sort_unstable_by_key(2..2, |k| k.abs());\nfor i in 0..2 {\n assert!(v[i].abs() <= v[2].abs());\n}\nfor i in 3..v.len() {\n assert!(v[2].abs() <= v[i].abs());\n}\n\n// single element range, same as select_nth_unstable\nv.partial_sort_unstable_by_key(2..3, |k| k.abs());\nfor i in 0..2 {\n assert!(v[i].abs() <= v[2].abs());\n}\nfor i in 3..v.len() {\n assert!(v[2].abs() <= v[i].abs());\n}\n\n// partial sort a subrange\nv.partial_sort_unstable_by_key(1..4, |k| k.abs());\nassert_eq!(&v[1..4], [2, -3, 4]);\n\n// partial sort the whole range, same as sort_unstable\nv.partial_sort_unstable_by_key(.., |k| k.abs());\nassert_eq!(v, [1, 2, -3, 4, -5]);Reorders the slice such that the element at index is at a sort-order position. All\nelements before index will be <= to this value, and all elements after will be >= to\nit.
This reordering is unstable (i.e. any element that compares equal to the nth element may end\nup at that position), in-place (i.e. does not allocate), and runs in O(n) time. This\nfunction is also known as “kth element” in other libraries.
\nReturns a triple that partitions the reordered slice:
\nThe unsorted subslice before index, whose elements all satisfy x <= self[index].
The element at index.
The unsorted subslice after index, whose elements all satisfy x >= self[index].
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll\nand Orson Peters, which is also the basis for sort_unstable. The fallback algorithm is\nMedian of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime\nfor all inputs.
Panics when index >= len(), and so always panics on empty slices.
May panic if the implementation of Ord for T does not implement a total order.
let mut v = [-5i32, 4, 2, -3, 1];\n\n// Find the items `<=` to the median, the median itself, and the items `>=` to it.\nlet (lesser, median, greater) = v.select_nth_unstable(2);\n\nassert!(lesser == [-3, -5] || lesser == [-5, -3]);\nassert_eq!(median, &mut 1);\nassert!(greater == [4, 2] || greater == [2, 4]);\n\n// We are only guaranteed the slice will be one of the following, based on the way we sort\n// about the specified index.\nassert!(v == [-3, -5, 1, 2, 4] ||\n v == [-5, -3, 1, 2, 4] ||\n v == [-3, -5, 1, 4, 2] ||\n v == [-5, -3, 1, 4, 2]);Reorders the slice with a comparator function such that the element at index is at a\nsort-order position. All elements before index will be <= to this value, and all\nelements after will be >= to it, according to the comparator function.
This reordering is unstable (i.e. any element that compares equal to the nth element may end\nup at that position), in-place (i.e. does not allocate), and runs in O(n) time. This\nfunction is also known as “kth element” in other libraries.
\nReturns a triple partitioning the reordered slice:
\nThe unsorted subslice before index, whose elements all satisfy\ncompare(x, self[index]).is_le().
The element at index.
The unsorted subslice after index, whose elements all satisfy\ncompare(x, self[index]).is_ge().
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll\nand Orson Peters, which is also the basis for sort_unstable. The fallback algorithm is\nMedian of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime\nfor all inputs.
Panics when index >= len(), and so always panics on empty slices.
May panic if compare does not implement a total order.
let mut v = [-5i32, 4, 2, -3, 1];\n\n// Find the items `>=` to the median, the median itself, and the items `<=` to it, by using\n// a reversed comparator.\nlet (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));\n\nassert!(before == [4, 2] || before == [2, 4]);\nassert_eq!(median, &mut 1);\nassert!(after == [-3, -5] || after == [-5, -3]);\n\n// We are only guaranteed the slice will be one of the following, based on the way we sort\n// about the specified index.\nassert!(v == [2, 4, 1, -5, -3] ||\n v == [2, 4, 1, -3, -5] ||\n v == [4, 2, 1, -5, -3] ||\n v == [4, 2, 1, -3, -5]);Reorders the slice with a key extraction function such that the element at index is at a\nsort-order position. All elements before index will have keys <= to the key at index,\nand all elements after will have keys >= to it.
This reordering is unstable (i.e. any element that compares equal to the nth element may end\nup at that position), in-place (i.e. does not allocate), and runs in O(n) time. This\nfunction is also known as “kth element” in other libraries.
\nReturns a triple partitioning the reordered slice:
\nThe unsorted subslice before index, whose elements all satisfy f(x) <= f(self[index]).
The element at index.
The unsorted subslice after index, whose elements all satisfy f(x) >= f(self[index]).
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll\nand Orson Peters, which is also the basis for sort_unstable. The fallback algorithm is\nMedian of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime\nfor all inputs.
Panics when index >= len(), meaning it always panics on empty slices.
May panic if K: Ord does not implement a total order.
let mut v = [-5i32, 4, 1, -3, 2];\n\n// Find the items `<=` to the absolute median, the absolute median itself, and the items\n// `>=` to it.\nlet (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());\n\nassert!(lesser == [1, 2] || lesser == [2, 1]);\nassert_eq!(median, &mut -3);\nassert!(greater == [4, -5] || greater == [-5, 4]);\n\n// We are only guaranteed the slice will be one of the following, based on the way we sort\n// about the specified index.\nassert!(v == [1, 2, -3, 4, -5] ||\n v == [1, 2, -3, -5, 4] ||\n v == [2, 1, -3, 4, -5] ||\n v == [2, 1, -3, -5, 4]);slice_partition_dedup)Moves all consecutive repeated elements to the end of the slice according to the\nPartialEq trait implementation.
Returns two slices. The first contains no consecutive repeated elements.\nThe second contains all the duplicates in no specified order.
\nIf the slice is sorted, the first returned slice contains no duplicates.
\n#![feature(slice_partition_dedup)]\n\nlet mut slice = [1, 2, 2, 3, 3, 2, 1, 1];\n\nlet (dedup, duplicates) = slice.partition_dedup();\n\nassert_eq!(dedup, [1, 2, 3, 2, 1]);\nassert_eq!(duplicates, [2, 3, 1]);slice_partition_dedup)Moves all but the first of consecutive elements to the end of the slice satisfying\na given equality relation.
\nReturns two slices. The first contains no consecutive repeated elements.\nThe second contains all the duplicates in no specified order.
\nThe same_bucket function is passed references to two elements from the slice and\nmust determine if the elements compare equal. The elements are passed in opposite order\nfrom their order in the slice, so if same_bucket(a, b) returns true, a is moved\nat the end of the slice.
If the slice is sorted, the first returned slice contains no duplicates.
\n#![feature(slice_partition_dedup)]\n\nlet mut slice = [\"foo\", \"Foo\", \"BAZ\", \"Bar\", \"bar\", \"baz\", \"BAZ\"];\n\nlet (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));\n\nassert_eq!(dedup, [\"foo\", \"BAZ\", \"Bar\", \"baz\"]);\nassert_eq!(duplicates, [\"bar\", \"Foo\", \"BAZ\"]);slice_partition_dedup)Moves all but the first of consecutive elements to the end of the slice that resolve\nto the same key.
\nReturns two slices. The first contains no consecutive repeated elements.\nThe second contains all the duplicates in no specified order.
\nIf the slice is sorted, the first returned slice contains no duplicates.
\n#![feature(slice_partition_dedup)]\n\nlet mut slice = [10, 20, 21, 30, 30, 20, 11, 13];\n\nlet (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);\n\nassert_eq!(dedup, [10, 20, 30, 20, 11]);\nassert_eq!(duplicates, [21, 30, 13]);Rotates the slice in-place such that the first mid elements of the\nslice move to the end while the last self.len() - mid elements move to\nthe front.
After calling rotate_left, the element previously at index mid will\nbecome the first element in the slice.
This function will panic if mid is greater than the length of the\nslice. Note that mid == self.len() does not panic and is a no-op\nrotation.
Takes linear (in self.len()) time.
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];\na.rotate_left(2);\nassert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);Rotating a subslice:
\n\nlet mut a = ['a', 'b', 'c', 'd', 'e', 'f'];\na[1..5].rotate_left(1);\nassert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);Rotates the slice in-place such that the first self.len() - k\nelements of the slice move to the end while the last k elements move\nto the front.
After calling rotate_right, the element previously at index\nself.len() - k will become the first element in the slice.
This function will panic if k is greater than the length of the\nslice. Note that k == self.len() does not panic and is a no-op\nrotation.
Takes linear (in self.len()) time.
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];\na.rotate_right(2);\nassert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);Rotating a subslice:
\n\nlet mut a = ['a', 'b', 'c', 'd', 'e', 'f'];\na[1..5].rotate_right(1);\nassert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);slice_shift)Moves the elements of this slice N places to the left, returning the ones\nthat “fall off” the front, and putting inserted at the end.
Equivalently, you can think of concatenating self and inserted into one\nlong sequence, then returning the left-most N items and the rest into self:
self (before) inserted\n vvvvvvvvvvvvvvv vvv\n [1, 2, 3, 4, 5] [9]\n ↙ ↙ ↙ ↙ ↙ ↙\n [1] [2, 3, 4, 5, 9]\n ^^^ ^^^^^^^^^^^^^^^\nreturned self (after)See also Self::shift_right and compare Self::rotate_left.
#![feature(slice_shift)]\n\n// Same as the diagram above\nlet mut a = [1, 2, 3, 4, 5];\nlet inserted = [9];\nlet returned = a.shift_left(inserted);\nassert_eq!(returned, [1]);\nassert_eq!(a, [2, 3, 4, 5, 9]);\n\n// You can shift multiple items at a time\nlet mut a = *b\"Hello world\";\nassert_eq!(a.shift_left(*b\" peace\"), *b\"Hello \");\nassert_eq!(a, *b\"world peace\");\n\n// The name comes from this operation's similarity to bitshifts\nlet mut a: u8 = 0b10010110;\na <<= 3;\nassert_eq!(a, 0b10110000_u8);\nlet mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];\na.shift_left([0; 3]);\nassert_eq!(a, [1, 0, 1, 1, 0, 0, 0, 0]);\n\n// Remember you can sub-slice to affect less that the whole slice.\n// For example, this is similar to `.remove(1)` + `.insert(4, 'Z')`\nlet mut a = ['a', 'b', 'c', 'd', 'e', 'f'];\nassert_eq!(a[1..=4].shift_left(['Z']), ['b']);\nassert_eq!(a, ['a', 'c', 'd', 'e', 'Z', 'f']);\n\n// If the size matches it's equivalent to `mem::replace`\nlet mut a = [1, 2, 3];\nassert_eq!(a.shift_left([7, 8, 9]), [1, 2, 3]);\nassert_eq!(a, [7, 8, 9]);\n\n// Some of the \"inserted\" elements end up returned if the slice is too short\nlet mut a = [];\nassert_eq!(a.shift_left([1, 2, 3]), [1, 2, 3]);\nlet mut a = [9];\nassert_eq!(a.shift_left([1, 2, 3]), [9, 1, 2]);\nassert_eq!(a, [3]);slice_shift)Moves the elements of this slice N places to the right, returning the ones\nthat “fall off” the back, and putting inserted at the beginning.
Equivalently, you can think of concatenating inserted and self into one\nlong sequence, then returning the right-most N items and the rest into self:
inserted self (before)\n vvv vvvvvvvvvvvvvvv\n [0] [5, 6, 7, 8, 9]\n ↘ ↘ ↘ ↘ ↘ ↘\n [0, 5, 6, 7, 8] [9]\n ^^^^^^^^^^^^^^^ ^^^\n self (after) returnedSee also Self::shift_left and compare Self::rotate_right.
#![feature(slice_shift)]\n\n// Same as the diagram above\nlet mut a = [5, 6, 7, 8, 9];\nlet inserted = [0];\nlet returned = a.shift_right(inserted);\nassert_eq!(returned, [9]);\nassert_eq!(a, [0, 5, 6, 7, 8]);\n\n// The name comes from this operation's similarity to bitshifts\nlet mut a: u8 = 0b10010110;\na >>= 3;\nassert_eq!(a, 0b00010010_u8);\nlet mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];\na.shift_right([0; 3]);\nassert_eq!(a, [0, 0, 0, 1, 0, 0, 1, 0]);\n\n// Remember you can sub-slice to affect less that the whole slice.\n// For example, this is similar to `.remove(4)` + `.insert(1, 'Z')`\nlet mut a = ['a', 'b', 'c', 'd', 'e', 'f'];\nassert_eq!(a[1..=4].shift_right(['Z']), ['e']);\nassert_eq!(a, ['a', 'Z', 'b', 'c', 'd', 'f']);\n\n// If the size matches it's equivalent to `mem::replace`\nlet mut a = [1, 2, 3];\nassert_eq!(a.shift_right([7, 8, 9]), [1, 2, 3]);\nassert_eq!(a, [7, 8, 9]);\n\n// Some of the \"inserted\" elements end up returned if the slice is too short\nlet mut a = [];\nassert_eq!(a.shift_right([1, 2, 3]), [1, 2, 3]);\nlet mut a = [9];\nassert_eq!(a.shift_right([1, 2, 3]), [2, 3, 9]);\nassert_eq!(a, [1]);Fills self with elements by cloning value.
let mut buf = vec![0; 10];\nbuf.fill(1);\nassert_eq!(buf, vec![1; 10]);Fills self with elements returned by calling a closure repeatedly.
This method uses a closure to create new values. If you’d rather\nClone a given value, use fill. If you want to use the Default\ntrait to generate values, you can pass Default::default as the\nargument.
let mut buf = vec![1; 10];\nbuf.fill_with(Default::default);\nassert_eq!(buf, vec![0; 10]);Copies the elements from src into self.
The length of src must be the same as self.
This function will panic if the two slices have different lengths.
\nCloning two elements from a slice into another:
\n\nlet src = [1, 2, 3, 4];\nlet mut dst = [0, 0];\n\n// Because the slices have to be the same length,\n// we slice the source slice from four elements\n// to two. It will panic if we don't do this.\ndst.clone_from_slice(&src[2..]);\n\nassert_eq!(src, [1, 2, 3, 4]);\nassert_eq!(dst, [3, 4]);Rust enforces that there can only be one mutable reference with no\nimmutable references to a particular piece of data in a particular\nscope. Because of this, attempting to use clone_from_slice on a\nsingle slice will result in a compile failure:
let mut slice = [1, 2, 3, 4, 5];\n\nslice[..2].clone_from_slice(&slice[3..]); // compile fail!To work around this, we can use split_at_mut to create two distinct\nsub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];\n\n{\n let (left, right) = slice.split_at_mut(2);\n left.clone_from_slice(&right[1..]);\n}\n\nassert_eq!(slice, [4, 5, 3, 4, 5]);Copies all elements from src into self, using a memcpy.
The length of src must be the same as self.
If T does not implement Copy, use clone_from_slice.
This function will panic if the two slices have different lengths.
\nCopying two elements from a slice into another:
\n\nlet src = [1, 2, 3, 4];\nlet mut dst = [0, 0];\n\n// Because the slices have to be the same length,\n// we slice the source slice from four elements\n// to two. It will panic if we don't do this.\ndst.copy_from_slice(&src[2..]);\n\nassert_eq!(src, [1, 2, 3, 4]);\nassert_eq!(dst, [3, 4]);Rust enforces that there can only be one mutable reference with no\nimmutable references to a particular piece of data in a particular\nscope. Because of this, attempting to use copy_from_slice on a\nsingle slice will result in a compile failure:
let mut slice = [1, 2, 3, 4, 5];\n\nslice[..2].copy_from_slice(&slice[3..]); // compile fail!To work around this, we can use split_at_mut to create two distinct\nsub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];\n\n{\n let (left, right) = slice.split_at_mut(2);\n left.copy_from_slice(&right[1..]);\n}\n\nassert_eq!(slice, [4, 5, 3, 4, 5]);Copies elements from one part of the slice to another part of itself,\nusing a memmove.
\nsrc is the range within self to copy from. dest is the starting\nindex of the range within self to copy to, which will have the same\nlength as src. The two ranges may overlap. The ends of the two ranges\nmust be less than or equal to self.len().
This function will panic if either range exceeds the end of the slice,\nor if the end of src is before the start.
Copying four bytes within a slice:
\n\nlet mut bytes = *b\"Hello, World!\";\n\nbytes.copy_within(1..5, 8);\n\nassert_eq!(&bytes, b\"Hello, Wello!\");Swaps all elements in self with those in other.
The length of other must be the same as self.
This function will panic if the two slices have different lengths.
\nSwapping two elements across slices:
\n\nlet mut slice1 = [0, 0];\nlet mut slice2 = [1, 2, 3, 4];\n\nslice1.swap_with_slice(&mut slice2[2..]);\n\nassert_eq!(slice1, [3, 4]);\nassert_eq!(slice2, [1, 2, 0, 0]);Rust enforces that there can only be one mutable reference to a\nparticular piece of data in a particular scope. Because of this,\nattempting to use swap_with_slice on a single slice will result in\na compile failure:
let mut slice = [1, 2, 3, 4, 5];\nslice[..2].swap_with_slice(&mut slice[3..]); // compile fail!To work around this, we can use split_at_mut to create two distinct\nmutable sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];\n\n{\n let (left, right) = slice.split_at_mut(2);\n left.swap_with_slice(&mut right[1..]);\n}\n\nassert_eq!(slice, [4, 5, 3, 1, 2]);Transmutes the slice to a slice of another type, ensuring alignment of the types is\nmaintained.
\nThis method splits the slice into three distinct slices: prefix, correctly aligned middle\nslice of a new type, and the suffix slice. The middle part will be as big as possible under\nthe given alignment constraint and element size.
\nThis method has no purpose when either input element T or output element U are\nzero-sized and will return the original slice without splitting anything.
This method is essentially a transmute with respect to the elements in the returned\nmiddle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.
Basic usage:
\n\nunsafe {\n let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];\n let (prefix, shorts, suffix) = bytes.align_to::<u16>();\n // less_efficient_algorithm_for_bytes(prefix);\n // more_efficient_algorithm_for_aligned_shorts(shorts);\n // less_efficient_algorithm_for_bytes(suffix);\n}Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the\ntypes is maintained.
\nThis method splits the slice into three distinct slices: prefix, correctly aligned middle\nslice of a new type, and the suffix slice. The middle part will be as big as possible under\nthe given alignment constraint and element size.
\nThis method has no purpose when either input element T or output element U are\nzero-sized and will return the original slice without splitting anything.
This method is essentially a transmute with respect to the elements in the returned\nmiddle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.
Basic usage:
\n\nunsafe {\n let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];\n let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();\n // less_efficient_algorithm_for_bytes(prefix);\n // more_efficient_algorithm_for_aligned_shorts(shorts);\n // less_efficient_algorithm_for_bytes(suffix);\n}portable_simd)Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
\nThis is a safe wrapper around slice::align_to, so inherits the same\nguarantees as that method.
This will panic if the size of the SIMD type is different from\nLANES times that of the scalar.
At the time of writing, the trait restrictions on Simd<T, LANES> keeps\nthat from ever happening, as only power-of-two numbers of lanes are\nsupported. It’s possible that, in the future, those restrictions might\nbe lifted in a way that would make it possible to see panics from this\nmethod for something like LANES == 3.
#![feature(portable_simd)]\nuse core::simd::prelude::*;\n\nlet short = &[1, 2, 3];\nlet (prefix, middle, suffix) = short.as_simd::<4>();\nassert_eq!(middle, []); // Not enough elements for anything in the middle\n\n// They might be split in any possible way between prefix and suffix\nlet it = prefix.iter().chain(suffix).copied();\nassert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);\n\nfn basic_simd_sum(x: &[f32]) -> f32 {\n use std::ops::Add;\n let (prefix, middle, suffix) = x.as_simd();\n let sums = f32x4::from_array([\n prefix.iter().copied().sum(),\n 0.0,\n 0.0,\n suffix.iter().copied().sum(),\n ]);\n let sums = middle.iter().copied().fold(sums, f32x4::add);\n sums.reduce_sum()\n}\n\nlet numbers: Vec<f32> = (1..101).map(|x| x as _).collect();\nassert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);portable_simd)Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types,\nand a mutable suffix.
\nThis is a safe wrapper around slice::align_to_mut, so inherits the same\nguarantees as that method.
This is the mutable version of slice::as_simd; see that for examples.
This will panic if the size of the SIMD type is different from\nLANES times that of the scalar.
At the time of writing, the trait restrictions on Simd<T, LANES> keeps\nthat from ever happening, as only power-of-two numbers of lanes are\nsupported. It’s possible that, in the future, those restrictions might\nbe lifted in a way that would make it possible to see panics from this\nmethod for something like LANES == 3.
Checks if the elements of this slice are sorted.
\nThat is, for each element a and its following element b, a <= b must hold. If the\nslice yields exactly zero or one element, true is returned.
Note that if Self::Item is only PartialOrd, but not Ord, the above definition\nimplies that this function returns false if any two consecutive items are not\ncomparable.
let empty: [i32; 0] = [];\n\nassert!([1, 2, 2, 9].is_sorted());\nassert!(![1, 3, 2, 4].is_sorted());\nassert!([0].is_sorted());\nassert!(empty.is_sorted());\nassert!(![0.0, 1.0, f32::NAN].is_sorted());Checks if the elements of this slice are sorted using the given comparator function.
\nInstead of using PartialOrd::partial_cmp, this function uses the given compare\nfunction to determine whether two elements are to be considered in sorted order.
assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));\nassert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));\n\nassert!([0].is_sorted_by(|a, b| true));\nassert!([0].is_sorted_by(|a, b| false));\n\nlet empty: [i32; 0] = [];\nassert!(empty.is_sorted_by(|a, b| false));\nassert!(empty.is_sorted_by(|a, b| true));Checks if the elements of this slice are sorted using the given key extraction function.
\nInstead of comparing the slice’s elements directly, this function compares the keys of the\nelements, as determined by f. Apart from that, it’s equivalent to is_sorted; see its\ndocumentation for more information.
assert!([\"c\", \"bb\", \"aaa\"].is_sorted_by_key(|s| s.len()));\nassert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));Returns the index of the partition point according to the given predicate\n(the index of the first element of the second partition).
\nThe slice is assumed to be partitioned according to the given predicate.\nThis means that all elements for which the predicate returns true are at the start of the slice\nand all elements for which the predicate returns false are at the end.\nFor example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0\n(all odd numbers are at the start, all even at the end).
If this slice is not partitioned, the returned result is unspecified and meaningless,\nas this method performs a kind of binary search.
\nSee also binary_search, binary_search_by, and binary_search_by_key.
let v = [1, 2, 3, 3, 5, 6, 7];\nlet i = v.partition_point(|&x| x < 5);\n\nassert_eq!(i, 4);\nassert!(v[..i].iter().all(|&x| x < 5));\nassert!(v[i..].iter().all(|&x| !(x < 5)));If all elements of the slice match the predicate, including if the slice\nis empty, then the length of the slice will be returned:
\n\nlet a = [2, 4, 8];\nassert_eq!(a.partition_point(|x| x < &100), a.len());\nlet a: [i32; 0] = [];\nassert_eq!(a.partition_point(|x| x < &100), 0);If you want to insert an item to a sorted vector, while maintaining\nsort order:
\n\nlet mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];\nlet num = 42;\nlet idx = s.partition_point(|&x| x <= num);\ns.insert(idx, num);\nassert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);Removes the subslice corresponding to the given range\nand returns a reference to it.
\nReturns None and does not modify the slice if the given\nrange is out of bounds.
Note that this method only accepts one-sided ranges such as\n2.. or ..6, but not 2..6.
Splitting off the first three elements of a slice:
\n\nlet mut slice: &[_] = &['a', 'b', 'c', 'd'];\nlet mut first_three = slice.split_off(..3).unwrap();\n\nassert_eq!(slice, &['d']);\nassert_eq!(first_three, &['a', 'b', 'c']);Splitting off a slice starting with the third element:
\n\nlet mut slice: &[_] = &['a', 'b', 'c', 'd'];\nlet mut tail = slice.split_off(2..).unwrap();\n\nassert_eq!(slice, &['a', 'b']);\nassert_eq!(tail, &['c', 'd']);Getting None when range is out of bounds:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];\n\nassert_eq!(None, slice.split_off(5..));\nassert_eq!(None, slice.split_off(..5));\nassert_eq!(None, slice.split_off(..=4));\nlet expected: &[char] = &['a', 'b', 'c', 'd'];\nassert_eq!(Some(expected), slice.split_off(..4));Removes the subslice corresponding to the given range\nand returns a mutable reference to it.
\nReturns None and does not modify the slice if the given\nrange is out of bounds.
Note that this method only accepts one-sided ranges such as\n2.. or ..6, but not 2..6.
Splitting off the first three elements of a slice:
\n\nlet mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];\nlet mut first_three = slice.split_off_mut(..3).unwrap();\n\nassert_eq!(slice, &mut ['d']);\nassert_eq!(first_three, &mut ['a', 'b', 'c']);Splitting off a slice starting with the third element:
\n\nlet mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];\nlet mut tail = slice.split_off_mut(2..).unwrap();\n\nassert_eq!(slice, &mut ['a', 'b']);\nassert_eq!(tail, &mut ['c', 'd']);Getting None when range is out of bounds:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];\n\nassert_eq!(None, slice.split_off_mut(5..));\nassert_eq!(None, slice.split_off_mut(..5));\nassert_eq!(None, slice.split_off_mut(..=4));\nlet expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];\nassert_eq!(Some(expected), slice.split_off_mut(..4));Removes the first element of the slice and returns a reference\nto it.
\nReturns None if the slice is empty.
let mut slice: &[_] = &['a', 'b', 'c'];\nlet first = slice.split_off_first().unwrap();\n\nassert_eq!(slice, &['b', 'c']);\nassert_eq!(first, &'a');Removes the first element of the slice and returns a mutable\nreference to it.
\nReturns None if the slice is empty.
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];\nlet first = slice.split_off_first_mut().unwrap();\n*first = 'd';\n\nassert_eq!(slice, &['b', 'c']);\nassert_eq!(first, &'d');Removes the last element of the slice and returns a reference\nto it.
\nReturns None if the slice is empty.
let mut slice: &[_] = &['a', 'b', 'c'];\nlet last = slice.split_off_last().unwrap();\n\nassert_eq!(slice, &['a', 'b']);\nassert_eq!(last, &'c');Removes the last element of the slice and returns a mutable\nreference to it.
\nReturns None if the slice is empty.
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];\nlet last = slice.split_off_last_mut().unwrap();\n*last = 'd';\n\nassert_eq!(slice, &['a', 'b']);\nassert_eq!(last, &'d');Returns mutable references to many indices at once, without doing any checks.
\nAn index can be either a usize, a Range or a RangeInclusive. Note\nthat this method takes an array, so all indices must be of the same type.\nIf passed an array of usizes this method gives back an array of mutable references\nto single elements, while if passed an array of ranges it gives back an array of\nmutable references to slices.
For a safe alternative see get_disjoint_mut.
Calling this method with overlapping or out-of-bounds indices is undefined behavior\neven if the resulting references are not used.
\nlet x = &mut [1, 2, 4];\n\nunsafe {\n let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);\n *a *= 10;\n *b *= 100;\n}\nassert_eq!(x, &[10, 2, 400]);\n\nunsafe {\n let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);\n a[0] = 8;\n b[0] = 88;\n b[1] = 888;\n}\nassert_eq!(x, &[8, 88, 888]);\n\nunsafe {\n let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);\n a[0] = 11;\n a[1] = 111;\n b[0] = 1;\n}\nassert_eq!(x, &[1, 11, 111]);Returns mutable references to many indices at once.
\nAn index can be either a usize, a Range or a RangeInclusive. Note\nthat this method takes an array, so all indices must be of the same type.\nIf passed an array of usizes this method gives back an array of mutable references\nto single elements, while if passed an array of ranges it gives back an array of\nmutable references to slices.
Returns an error if any index is out-of-bounds, or if there are overlapping indices.\nAn empty range is not considered to overlap if it is located at the beginning or at\nthe end of another range, but is considered to overlap if it is located in the middle.
\nThis method does a O(n^2) check to check that there are no overlapping indices, so be careful\nwhen passing many indices.
\nlet v = &mut [1, 2, 3];\nif let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {\n *a = 413;\n *b = 612;\n}\nassert_eq!(v, &[413, 2, 612]);\n\nif let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {\n a[0] = 8;\n b[0] = 88;\n b[1] = 888;\n}\nassert_eq!(v, &[8, 88, 888]);\n\nif let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {\n a[0] = 11;\n a[1] = 111;\n b[0] = 1;\n}\nassert_eq!(v, &[1, 11, 111]);Returns the index that an element reference points to.
\nReturns None if element does not point to the start of an element within the slice.
This method is useful for extending slice iterators like slice::split.
Note that this uses pointer arithmetic and does not compare elements.\nTo find the index of an element via comparison, use\n.iter().position() instead.
Panics if T is zero-sized.
Basic usage:
\n\nlet nums: &[u32] = &[1, 7, 1, 1];\nlet num = &nums[2];\n\nassert_eq!(num, &1);\nassert_eq!(nums.element_offset(num), Some(2));Returning None with an unaligned element:
let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];\nlet flat_arr: &[u32] = arr.as_flattened();\n\nlet ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();\nlet weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();\n\nassert_eq!(ok_elm, &[0, 1]);\nassert_eq!(weird_elm, &[1, 2]);\n\nassert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0\nassert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1Returns the range of indices that a subslice points to.
\nReturns None if subslice does not point within the slice or if it is not aligned with the\nelements in the slice.
This method does not compare elements. Instead, this method finds the location in the slice that\nsubslice was obtained from. To find the index of a subslice via comparison, instead use\n.windows().position().
This method is useful for extending slice iterators like slice::split.
Note that this may return a false positive (either Some(0..0) or Some(self.len()..self.len()))\nif subslice has a length of zero and points to the beginning or end of another, separate, slice.
Panics if T is zero-sized.
Basic usage:
\n\nuse core::range::Range;\n\nlet nums = &[0, 5, 10, 0, 0, 5];\n\nlet mut iter = nums\n .split(|t| *t == 0)\n .map(|n| nums.subslice_range(n).unwrap());\n\nassert_eq!(iter.next(), Some(Range { start: 0, end: 0 }));\nassert_eq!(iter.next(), Some(Range { start: 1, end: 3 }));\nassert_eq!(iter.next(), Some(Range { start: 4, end: 4 }));\nassert_eq!(iter.next(), Some(Range { start: 5, end: 6 }));str_as_str)Returns the same slice &[T].
This method is redundant when used directly on &[T], but\nit helps dereferencing other “container” types to slices,\nfor example Box<[T]> or Arc<[T]>.
str_as_str)Returns the same slice &mut [T].
This method is redundant when used directly on &mut [T], but\nit helps dereferencing other “container” types to slices,\nfor example Box<[T]> or MutexGuard<[T]>.
tarpaulin_include only.Note that overly-large slices may cause the conversions to fail.
\nno_global_oom_handling only.no_global_oom_handling only.Note: str in Concat<str> is not meaningful here.\nThis type parameter of the trait only exists to enable another impl.
Check whether two slices of ConstantTimeEq types are equal.
This function short-circuits if the lengths of the input slices\nare different. Otherwise, it should execute in time independent\nof the slice contents.
\nSince arrays coerce to slices, this function works with fixed-size arrays:
\n\nlet a: [u8; 8] = [0,1,2,3,4,5,6,7];\nlet b: [u8; 8] = [0,1,2,3,0,1,2,3];\n\nlet a_eq_a = a.ct_eq(&a);\nlet a_eq_b = a.ct_eq(&b);\n\nassert_eq!(a_eq_a.unwrap_u8(), 1);\nassert_eq!(a_eq_b.unwrap_u8(), 0);&Self. Read moreamount distinct elements from self Read moreamount distinct elements Read moreself with replacement Read moreamount distinct elements from self Read moreamount distinct elements Read moreRenamed to sample
Self::sample] insteadRenamed to sample_array
Self::sample_array] insteadno_global_oom_handling only.no_global_oom_handling only.no_global_oom_handling only.Self. Read moreImplements comparison of slices lexicographically.
\nImplements comparison of slices lexicographically.
\nU-element arrays, starting at the beginning\nof the slice, and a remainder slice with length strictly less than U. Read moreU-element arrays, starting at the beginning\nof the slice, and a remainder slice with length strictly less than U. Read moreNone if the\nslice is empty. Read moreNone if the slice is empty. Read moreamount elements from the slice at random, without repetition,\nand in random order. The returned iterator is appropriate both for\ncollection into a Vec and filling an existing buffer (see example). Read morechoose_mut, but where the likelihood of each outcome may\nbe specified. Read morechoose_multiple, but where the likelihood of each element’s\ninclusion in the output may be specified. The elements are returned in an\narbitrary, unspecified order. Read moreself in two. Read moreself in two. Read moreself in two. Read moreno_global_oom_handling only.SmallVec from a slice.source as a &Self with\na DST length equal to count. Read moresource as a &Self with\na DST length equal to count. Read moresource as a &mut Self\nwith a DST length equal to count. Read moresource as a &mut Self\nwith a DST length equal to count. Read moreNote: VarULE is well-defined for all [T] where T: ULE, but ZeroSlice is more ergonomic\nwhen T is a low-level ULE type. For example:
// OK: [u8] is a useful type\nlet _: VarZeroVec<[u8]> = unimplemented!();\n\n// Technically works, but [u32::ULE] is not very useful\nlet _: VarZeroVec<[<u32 as AsULE>::ULE]> = unimplemented!();\n\n// Better: ZeroSlice<u32>\nlet _: VarZeroVec<ZeroSlice<u32>> = unimplemented!();&[u8], and return it as &Self with the same lifetime, assuming\nthat this byte slice has previously been run through [Self::parse_bytes()] with\nsuccess. Read moreImpl [Zeroize] on slices of types that can be zeroized with Default.
This impl can eventually be optimized using an memset intrinsic,\nsuch as core::intrinsics::volatile_set_memory. For that reason the\nblanket impl on slices is bounded by [DefaultIsZeroes].
To zeroize a mut slice of Z: Zeroize which does not impl\n[DefaultIsZeroes], call iter_mut().zeroize().
Default so that\napprox_eq() can be called on unknown types.Cow<'_, str>.CStr.Cow<'_, str>.CStr.Buf::remaining(). Note that this can return a shorter slice (this\nallows non-continuous internal representation). Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in the big-endian byte order. Read moreself in the little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself. Read moreself. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreself in big-endian byte order. Read moreself in little-endian byte order. Read moreself in native-endian byte order. Read moreRead methods, if empty. Read moreamount of additional bytes from the internal buffer as having been read.\nSubsequent calls to read only return bytes that have not been marked as read. Read morebuf_read_has_data_left)read. Read morebyte or EOF is reached. Read more0xA byte) is reached, and append\nthem to the provided String buffer. Read moreBased off of the empty function, allows override for optimization purposes.
Buffer. This is different than Default b/c it\nguarantees that the buffer instance will have length zero. Read moreslice. Read moreImplement deserialize from &u8 for all types which implement BinarySerializable.
\nTryFrom would actually be preferable, but not possible because of the orphan\nrules (not completely sure if this could be resolved)
\nself into buf in the expected format for the database.self into buf in the expected format for the database.cb with a piecewise list of byte slices that when concatenated\nproduce the memory pattern of the corresponding instance of T. Read moreVarULE] typeVarULE] type to the dst buffer. dst should\nbe the size of [Self::encode_var_ule_len()]cb with a piecewise list of byte slices that when concatenated\nproduce the memory pattern of the corresponding instance of T. Read moreVarULE] typeVarULE] type to the dst buffer. dst should\nbe the size of [Self::encode_var_ule_len()]alloc only.alloc only.Type in its binary format. Read moreType.mode version of split_at_position
\nmode version of split_at_position
\n&str, the position\ncorresponds to the byte index of the characterindex bytes. panics if index > lengthindex byte offset. panics if index > length&str, the position\ncorresponds to the byte index of the characteralloc only.","servers::prom_remote_write::types::RawBytes"],[" This is a shortcut for [ Read is implemented for Note that reading updates the slice to point to the yet unread part.\nThe slice will be empty when EOF is reached. Replaced with impl<R> ParseSlice<R> for &[u8]
fn parse_slice(&self) -> Option<R>
parse() succeeded Read moreimpl<'s, I, E> Parser<I, <I as Stream>::Slice, E> for &'s [u8]
literal][crate::token::literal].§Example
\n\nfn parser<'s>(s: &mut &'s [u8]) -> ModalResult<&'s [u8]> {\n alt((&\"Hello\"[..], take(5usize))).parse_next(s)\n}\n\nassert_eq!(parser.parse_peek(&b\"Hello, World!\"[..]), Ok((&b\", World!\"[..], &b\"Hello\"[..])));\nassert_eq!(parser.parse_peek(&b\"Something\"[..]), Ok((&b\"hing\"[..], &b\"Somet\"[..])));\nassert!(parser.parse_peek(&b\"Some\"[..]).is_err());\nassert!(parser.parse_peek(&b\"\"[..]).is_err());fn parse_next(&mut self, i: &mut I) -> Result<<I as Stream>::Slice, E>
Stream], turning it into the output Read morefn parse(\n &mut self,\n input: I,\n) -> Result<O, ParseError<I, <E as ParserError<I>>::Inner>>
input, generating O from itfn parse_peek(&mut self, input: I) -> Result<(I, O), E>
Stream], turning it into the output Read morefn by_ref(&mut self) -> ByRef<'_, Self, I, O, E>
&mut Self as a parser Read morefn default_value<O2>(self) -> DefaultValue<Self, I, O, O2, E>
fn void(self) -> Void<Self, I, O, E>
Parser Read morefn output_into<O2>(self) -> OutputInto<Self, I, O, O2, E>
std::convert::From Read morefn take(self) -> Take<Self, I, O, E>
fn with_taken(self) -> WithTaken<Self, I, O, E>
fn span(self) -> Span<Self, I, O, E>
fn with_span(self) -> WithSpan<Self, I, O, E>
fn map<G, O2>(self, map: G) -> Map<Self, G, I, O, O2, E>
fn try_map<G, O2, E2>(self, map: G) -> TryMap<Self, G, I, O, O2, E, E2>
Result over the output of a parser. Read morefn verify_map<G, O2>(self, map: G) -> VerifyMap<Self, G, I, O, O2, E>
fn flat_map<G, H, O2>(self, map: G) -> FlatMap<Self, G, H, I, O, O2, E>
fn and_then<G, O2>(self, inner: G) -> AndThen<Self, G, I, O, O2, E>
fn parse_to<O2>(self) -> ParseTo<Self, I, O, O2, E>
std::str::FromStr to the output of the parser Read morefn verify<G, O2>(self, filter: G) -> Verify<Self, G, I, O, O2, E>
fn context<C>(self, context: C) -> Context<Self, I, O, E, C>
fn context_with<F, C, FI>(\n self,\n context: F,\n) -> ContextWith<Self, I, O, E, F, C, FI>
fn map_err<G, E2>(self, map: G) -> MapErr<Self, G, I, O, E, E2>
fn complete_err(self) -> CompleteErr<Self, I, O, E>
Incomplete][crate::error::ErrMode::Incomplete] into [Backtrack][crate::error::ErrMode::Backtrack] Read morefn err_into<E2>(self) -> ErrInto<Self, I, O, E, E2>
std::convert::Fromimpl<T, U, const N: usize> PartialEq<[U; N]> for &[T]
impl PartialEq<ByteString> for &[u8]
fn eq(&self, other: &ByteString) -> bool
self and other values to be equal, and is used by ==.impl<'a> PartialOrd<BStr> for &'a [u8]
impl<'a> PartialOrd<BStr> for &'a [u8]
impl<'a> PartialOrd<BString> for &'a [u8]
impl PartialOrd<Bytes> for &[u8]
impl<'a> PartialOrd<Bytes> for &'a [u8]
impl PartialOrd<BytesMut> for &[u8]
impl PrimitiveContent for &[u8]
fn encoded_len(&self, _: Mode) -> usize
fn write_encoded<W>(&self, _: Mode, target: &mut W) -> Result<(), Error>
fn to_encoded_bytes(&self, mode: Mode) -> Bytes
fn encode(self) -> Primitive<Self>
fn encode_as(self, tag: Tag) -> Primitive<Self>
fn encode_ref(&self) -> Primitive<&Self>
fn encode_ref_as(&self, tag: Tag) -> Primitive<&Self>
impl Pushable for &[u8]
fn push_to_builder(self, builder: &mut Builder)
impl Read for &[u8]
&[u8] by copying from the slice.fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<(), Error>
read_buf)fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read, except that it reads into a slice of buffers. Read morefn is_read_vectored(&self) -> bool
can_vector)fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf. Read morefn read_buf_exact(\n &mut self,\n cursor: BorrowedCursor<'_, u8>,\n) -> Result<(), Error>
read_buf)cursor. Read morefn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf. Read morefn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf. Read morefn by_ref(&mut self) -> &mut Self
Read. Read morefn chain<R>(self, next: R) -> Chain<Self, R>
fn take(self, limit: u64) -> Take<Self>
limit bytes from it. Read morefn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error>
read_array)impl<'a> ReadRef<'a> for &'a [u8]
fn read_bytes_at(self, offset: u64, size: u64) -> Result<&'a [u8], ()>
u8 slice at the given offset. Read morefn read_bytes_at_until(\n self,\n range: Range<u64>,\n delimiter: u8,\n) -> Result<&'a [u8], ()>
u8 slice which starts at range.start. Read morefn read_bytes(self, offset: &mut u64, size: u64) -> Result<&'a [u8], ()>
u8 slice at the given offset, and update the offset. Read morefn read<T>(self, offset: &mut u64) -> Result<&'a T, ()>
Pod type at the given offset, and update the offset. Read morefn read_at<T>(self, offset: u64) -> Result<&'a T, ()>
Pod type at the given offset. Read moreimpl<'a> ReadRef<'a> for &'a [u8]
fn read_bytes_at(self, offset: u64, size: u64) -> Result<&'a [u8], ()>
u8 slice at the given offset. Read morefn read_bytes_at_until(\n self,\n range: Range<u64>,\n delimiter: u8,\n) -> Result<&'a [u8], ()>
u8 slice which starts at range.start. Read morefn read_bytes(self, offset: &mut u64, size: u64) -> Result<&'a [u8], ()>
u8 slice at the given offset, and update the offset. Read morefn read<T>(self, offset: &mut u64) -> Result<&'a T, ()>
Pod type at the given offset, and update the offset. Read morefn read_at<T>(self, offset: u64) -> Result<&'a T, ()>
Pod type at the given offset. Read moreimpl<'a> Replacer for &'a [u8]
impl<'a> SerializeOctets for &'a [u8]
fn serialize_octets<S>(\n &self,\n serializer: S,\n) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
fn as_serialized_octets(&self) -> AsSerializedOctets<'_, Self>
impl Size for &[u8]
fn unpadded_size(&self) -> usize
fn padded_size(&self) -> usize
impl<'i, T> Stream for &'i [T]
type IterOffsets = Enumerate<Cloned<Iter<'i, T>>>
type Checkpoint = Checkpoint<&'i [T], &'i [T]>
fn iter_offsets(&self) -> <&'i [T] as Stream>::IterOffsets ⓘ
fn eof_offset(&self) -> usize
fn next_token(&mut self) -> Option<<&'i [T] as Stream>::Token>
fn peek_token(&self) -> Option<<&'i [T] as Stream>::Token>
fn offset_for<P>(&self, predicate: P) -> Option<usize>
fn offset_at(&self, tokens: usize) -> Result<usize, Needed>
tokens into the stream Read morefn next_slice(&mut self, offset: usize) -> <&'i [T] as Stream>::Slice ⓘ
unsafe fn next_slice_unchecked(\n &mut self,\n offset: usize,\n) -> <&'i [T] as Stream>::Slice ⓘ
fn peek_slice(&self, offset: usize) -> <&'i [T] as Stream>::Slice ⓘ
unsafe fn peek_slice_unchecked(\n &self,\n offset: usize,\n) -> <&'i [T] as Stream>::Slice ⓘ
fn checkpoint(&self) -> <&'i [T] as Stream>::Checkpoint ⓘ
fn reset(&mut self, checkpoint: &<&'i [T] as Stream>::Checkpoint)
Self::Checkpoint] Read morefn raw(&self) -> &dyn Debug
Stream::traceStream::trace]fn trace(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn peek_finish(&self) -> Self::Slice
impl<T> StreamIsPartial for &[T]
type PartialState = ()
fn restore_partial(&mut self, _state: <&[T] as StreamIsPartial>::PartialState)
fn is_partial_supported() -> bool
Stream] is can ever be incompletefn is_partial(&self) -> bool
Stream] is currently incompleteimpl<T> ToSql for &[T]
fn to_sql(\n &self,\n ty: &Type,\n w: &mut BytesMut,\n) -> Result<IsNull, Box<dyn Error + Send + Sync>>
self into the binary format of the specified\nPostgres Type, appending it to out. Read morefn accepts(ty: &Type) -> bool
Type.fn to_sql_checked(\n &self,\n ty: &Type,\n out: &mut BytesMut,\n) -> Result<IsNull, Box<dyn Error + Send + Sync>>
fn encode_format(&self, _ty: &Type) -> Format
impl ToSql for &[u8]
fn to_sql(\n &self,\n _: &Type,\n w: &mut BytesMut,\n) -> Result<IsNull, Box<dyn Error + Send + Sync>>
self into the binary format of the specified\nPostgres Type, appending it to out. Read morefn accepts(ty: &Type) -> bool
Type.fn to_sql_checked(\n &self,\n ty: &Type,\n out: &mut BytesMut,\n) -> Result<IsNull, Box<dyn Error + Send + Sync>>
fn encode_format(&self, _ty: &Type) -> Format
impl<T> UpdateSlice for &[T]
fn update_slice(self, inner: <&[T] as Stream>::Slice) -> &[T]
Output type to be used as Streamimpl<'a> Value<'a> for &'a [u8]
type ArrayIter = Empty<&'a [u8]>
type ObjectIter = Empty<(&'a str, &'a [u8])>
fn as_value(&self) -> ReferenceValue<'a, &'a [u8]>
fn as_leaf(&self) -> Option<ReferenceValueLeaf<'a>>
fn as_str(&self) -> Option<&'a str>
fn as_u64(&self) -> Option<u64>
fn as_i64(&self) -> Option<i64>
fn as_f64(&self) -> Option<f64>
fn as_datetime(&self) -> Option<DateTime>
fn as_ip_addr(&self) -> Option<Ipv6Addr>
fn as_bool(&self) -> Option<bool>
fn as_pre_tokenized_text(&self) -> Option<Box<PreTokenizedString>>
fn as_bytes(&self) -> Option<&'a [u8]>
fn as_facet(&self) -> Option<&'a str>
impl AsSymbolName for &[u8]
impl ByteSlice for &[u8]
impl CloneableByteSlice for &[u8]
impl CopyableByteSlice for &[u8]