From ba5662a17ee29e736d4bb8d2ea399e7e0c8953b1 Mon Sep 17 00:00:00 2001 From: Zenn Date: Sat, 19 Aug 2023 19:14:32 +0200 Subject: [PATCH] added the heapless crate and added new docs --- Cargo.lock | 96 + Examples/drboy/Cargo.toml | 1 - Examples/drboy/src/lib.rs | 19 + arduboy-rust/Cargo.toml | 1 + arduboy-rust/src/lib.rs | 2 + arduboy-rust/src/library/progmem.rs | 29 + arduboy-rust/src/prelude.rs | 1 + docs/doc/arduboy_rust/all.html | 2 +- .../heapless/binary_heap/enum.Max.html | 12 + .../heapless/binary_heap/enum.Min.html | 12 + .../heapless/binary_heap/index.html | 5 + .../heapless/binary_heap/sidebar-items.js | 1 + .../binary_heap/struct.BinaryHeap.html | 197 + .../heapless/binary_heap/struct.PeekMut.html | 32 + .../heapless/binary_heap/trait.Kind.html | 2 + .../doc/arduboy_rust/heapless/enum.Entry.html | 24 + docs/doc/arduboy_rust/heapless/index.html | 64 + .../arduboy_rust/heapless/sidebar-items.js | 1 + .../heapless/sorted_linked_list/index.html | 21 + .../sorted_linked_list/sidebar-items.js | 1 + .../sorted_linked_list/struct.FindMut.html | 77 + .../sorted_linked_list/struct.Iter.html | 205 + .../struct.LinkedIndexU16.html | 19 + .../struct.LinkedIndexU8.html | 19 + .../struct.LinkedIndexUsize.html | 19 + .../sorted_linked_list/struct.Max.html | 12 + .../sorted_linked_list/struct.Min.html | 12 + .../sorted_linked_list/struct.Node.html | 22 + .../struct.SortedLinkedList.html | 151 + .../sorted_linked_list/trait.Kind.html | 2 + .../trait.SortedLinkedListIndex.html | 2 + .../heapless/struct.BinaryHeap.html | 197 + .../arduboy_rust/heapless/struct.Deque.html | 90 + .../heapless/struct.HistoryBuffer.html | 1089 +++ .../heapless/struct.IndexMap.html | 306 + .../heapless/struct.IndexSet.html | 296 + .../heapless/struct.LinearMap.html | 214 + .../heapless/struct.OccupiedEntry.html | 27 + .../heapless/struct.OldestOrdered.html | 191 + .../arduboy_rust/heapless/struct.String.html | 1373 +++ .../heapless/struct.VacantEntry.html | 24 + .../doc/arduboy_rust/heapless/struct.Vec.html | 2527 +++++ .../heapless/type.FnvIndexMap.html | 38 + .../heapless/type.FnvIndexSet.html | 30 + docs/doc/arduboy_rust/index.html | 4 +- docs/doc/arduboy_rust/macro.f.html | 2 +- .../arduboy_rust/macro.get_sprite_addr.html | 2 +- .../arduboy_rust/macro.get_string_addr.html | 2 +- .../arduboy_rust/macro.get_tones_addr.html | 2 +- docs/doc/arduboy_rust/macro.progmem.html | 22 +- .../arduboy_rust/prelude/fn.constrain.html | 2 +- docs/doc/arduboy_rust/prelude/index.html | 4 +- docs/doc/arduboy_rust/prelude/macro.f.html | 2 +- .../prelude/macro.get_sprite_addr.html | 2 +- .../prelude/macro.get_string_addr.html | 2 +- .../prelude/macro.get_tones_addr.html | 2 +- .../arduboy_rust/prelude/macro.progmem.html | 22 +- .../doc/arduboy_rust/prelude/sidebar-items.js | 2 +- .../prelude/struct.LinearMap.html | 214 + .../arduboy_rust/prelude/struct.String.html | 1373 +++ docs/doc/arduboy_rust/prelude/struct.Vec.html | 2527 +++++ .../arduboy_rust/prelude/trait.Printable.html | 2 +- docs/doc/arduboy_rust/sidebar-items.js | 2 +- docs/doc/atomic_polyfill/all.html | 1 + .../constant.ATOMIC_BOOL_INIT.html | 2 + docs/doc/atomic_polyfill/enum.Ordering.html | 60 + .../atomic_polyfill/fn.compiler_fence.html | 57 + docs/doc/atomic_polyfill/fn.fence.html | 62 + .../atomic_polyfill/fn.spin_loop_hint.html | 3 + docs/doc/atomic_polyfill/index.html | 1 + docs/doc/atomic_polyfill/sidebar-items.js | 1 + .../atomic_polyfill/struct.AtomicBool.html | 163 + docs/doc/atomic_polyfill/struct.AtomicI8.html | 167 + docs/doc/atomic_polyfill/struct.AtomicU8.html | 167 + docs/doc/byteorder/all.html | 1 + docs/doc/byteorder/enum.BigEndian.html | 45 + docs/doc/byteorder/enum.LittleEndian.html | 45 + docs/doc/byteorder/index.html | 41 + docs/doc/byteorder/sidebar-items.js | 1 + docs/doc/byteorder/trait.ByteOrder.html | 961 ++ docs/doc/byteorder/type.BE.html | 2 + docs/doc/byteorder/type.LE.html | 2 + docs/doc/byteorder/type.NativeEndian.html | 5 + docs/doc/byteorder/type.NetworkEndian.html | 15 + docs/doc/crates.js | 2 +- docs/doc/critical_section/all.html | 1 + docs/doc/critical_section/fn.acquire.html | 16 + docs/doc/critical_section/fn.release.html | 5 + docs/doc/critical_section/fn.with.html | 7 + docs/doc/critical_section/index.html | 167 + .../doc/critical_section/macro.set_impl!.html | 11 + docs/doc/critical_section/macro.set_impl.html | 19 + .../critical_section/mutex/struct.Mutex.html | 11 + docs/doc/critical_section/sidebar-items.js | 1 + .../struct.CriticalSection.html | 26 + docs/doc/critical_section/struct.Mutex.html | 101 + .../critical_section/struct.RestoreState.html | 25 + docs/doc/critical_section/trait.Impl.html | 15 + .../type.RawRestoreState.html | 14 + docs/doc/hash32/all.html | 1 + docs/doc/hash32/fnv/struct.Hasher.html | 11 + docs/doc/hash32/index.html | 46 + docs/doc/hash32/murmur3/struct.Hasher.html | 11 + docs/doc/hash32/sidebar-items.js | 1 + .../doc/hash32/struct.BuildHasherDefault.html | 24 + docs/doc/hash32/struct.FnvHasher.html | 12 + docs/doc/hash32/struct.Murmur3Hasher.html | 12 + docs/doc/hash32/trait.BuildHasher.html | 10 + docs/doc/hash32/trait.Hash.html | 119 + docs/doc/hash32/trait.Hasher.html | 11 + docs/doc/heapless/all.html | 1 + docs/doc/heapless/binary_heap/enum.Max.html | 12 + docs/doc/heapless/binary_heap/enum.Min.html | 12 + docs/doc/heapless/binary_heap/index.html | 5 + .../doc/heapless/binary_heap/sidebar-items.js | 1 + .../binary_heap/struct.BinaryHeap.html | 197 + .../heapless/binary_heap/struct.PeekMut.html | 32 + docs/doc/heapless/binary_heap/trait.Kind.html | 2 + docs/doc/heapless/deque/struct.Deque.html | 11 + docs/doc/heapless/enum.Entry.html | 24 + .../histbuf/struct.HistoryBuffer.html | 11 + .../histbuf/struct.OldestOrdered.html | 11 + docs/doc/heapless/index.html | 64 + docs/doc/heapless/indexmap/enum.Entry.html | 11 + .../heapless/indexmap/struct.IndexMap.html | 11 + .../indexmap/struct.OccupiedEntry.html | 11 + .../heapless/indexmap/struct.VacantEntry.html | 11 + .../heapless/indexmap/type.FnvIndexMap.html | 11 + .../heapless/indexset/struct.IndexSet.html | 11 + .../heapless/indexset/type.FnvIndexSet.html | 11 + .../heapless/linear_map/struct.LinearMap.html | 11 + docs/doc/heapless/sidebar-items.js | 1 + .../heapless/sorted_linked_list/index.html | 21 + .../sorted_linked_list/sidebar-items.js | 1 + .../sorted_linked_list/struct.FindMut.html | 77 + .../sorted_linked_list/struct.Iter.html | 205 + .../struct.LinkedIndexU16.html | 19 + .../struct.LinkedIndexU8.html | 19 + .../struct.LinkedIndexUsize.html | 19 + .../sorted_linked_list/struct.Max.html | 12 + .../sorted_linked_list/struct.Min.html | 12 + .../sorted_linked_list/struct.Node.html | 22 + .../struct.SortedLinkedList.html | 151 + .../sorted_linked_list/trait.Kind.html | 2 + .../trait.SortedLinkedListIndex.html | 2 + docs/doc/heapless/string/struct.String.html | 11 + docs/doc/heapless/struct.Deque.html | 89 + docs/doc/heapless/struct.HistoryBuffer.html | 1089 +++ docs/doc/heapless/struct.IndexMap.html | 306 + docs/doc/heapless/struct.IndexSet.html | 296 + docs/doc/heapless/struct.LinearMap.html | 214 + docs/doc/heapless/struct.OccupiedEntry.html | 27 + docs/doc/heapless/struct.OldestOrdered.html | 190 + docs/doc/heapless/struct.String.html | 1368 +++ docs/doc/heapless/struct.VacantEntry.html | 24 + docs/doc/heapless/struct.Vec.html | 2528 +++++ docs/doc/heapless/type.FnvIndexMap.html | 38 + docs/doc/heapless/type.FnvIndexSet.html | 30 + docs/doc/heapless/vec/struct.Vec.html | 11 + .../implementors/byteorder/trait.ByteOrder.js | 3 + .../implementors/core/clone/trait.Clone.js | 6 +- docs/doc/implementors/core/cmp/trait.Eq.js | 5 +- docs/doc/implementors/core/cmp/trait.Ord.js | 4 +- .../implementors/core/cmp/trait.PartialEq.js | 5 +- .../implementors/core/cmp/trait.PartialOrd.js | 4 +- .../implementors/core/convert/trait.AsMut.js | 3 + .../implementors/core/convert/trait.AsRef.js | 3 + .../implementors/core/convert/trait.From.js | 3 + .../core/convert/trait.TryFrom.js | 3 + .../core/default/trait.Default.js | 5 + docs/doc/implementors/core/fmt/trait.Debug.js | 6 +- .../implementors/core/fmt/trait.Display.js | 3 + docs/doc/implementors/core/fmt/trait.Write.js | 3 + docs/doc/implementors/core/hash/trait.Hash.js | 4 +- .../core/iter/traits/collect/trait.Extend.js | 3 + .../iter/traits/collect/trait.FromIterator.js | 3 + .../iter/traits/collect/trait.IntoIterator.js | 3 + .../iter/traits/iterator/trait.Iterator.js | 3 + .../implementors/core/marker/trait.Copy.js | 5 +- .../implementors/core/marker/trait.Freeze.js | 6 +- .../implementors/core/marker/trait.Send.js | 6 +- .../core/marker/trait.StructuralEq.js | 4 +- .../core/marker/trait.StructuralPartialEq.js | 4 +- .../implementors/core/marker/trait.Sync.js | 6 +- .../implementors/core/marker/trait.Unpin.js | 6 +- .../core/ops/deref/trait.Deref.js | 3 + .../core/ops/deref/trait.DerefMut.js | 3 + .../implementors/core/ops/drop/trait.Drop.js | 3 + .../core/ops/index/trait.Index.js | 3 + .../core/ops/index/trait.IndexMut.js | 3 + .../panic/unwind_safe/trait.RefUnwindSafe.js | 6 +- .../panic/unwind_safe/trait.UnwindSafe.js | 6 +- .../core/str/traits/trait.FromStr.js | 3 + .../implementors/hash32/trait.BuildHasher.js | 3 + docs/doc/implementors/hash32/trait.Hash.js | 4 + docs/doc/implementors/hash32/trait.Hasher.js | 3 + .../heapless/binary_heap/trait.Kind.js | 4 + .../heapless/sorted_linked_list/trait.Kind.js | 4 + .../trait.SortedLinkedListIndex.js | 4 + .../trait.CloneStableDeref.js | 3 + .../stable_deref_trait/trait.StableDeref.js | 3 + docs/doc/search-index.js | 10 +- docs/doc/src-files.js | 8 +- docs/doc/src/arduboy_rust/lib.rs.html | 4 + .../src/arduboy_rust/library/progmem.rs.html | 82 + docs/doc/src/arduboy_rust/prelude.rs.html | 2 + docs/doc/src/atomic_polyfill/lib.rs.html | 19 + docs/doc/src/byteorder/lib.rs.html | 8105 +++++++++++++++++ docs/doc/src/critical_section/lib.rs.html | 579 ++ docs/doc/src/critical_section/mutex.rs.html | 401 + docs/doc/src/hash32/fnv.rs.html | 57 + docs/doc/src/hash32/lib.rs.html | 727 ++ docs/doc/src/hash32/murmur3.rs.html | 381 + docs/doc/src/heapless/binary_heap.rs.html | 1483 +++ docs/doc/src/heapless/deque.rs.html | 1663 ++++ docs/doc/src/heapless/histbuf.rs.html | 867 ++ docs/doc/src/heapless/indexmap.rs.html | 2763 ++++++ docs/doc/src/heapless/indexset.rs.html | 1279 +++ docs/doc/src/heapless/lib.rs.html | 239 + docs/doc/src/heapless/linear_map.rs.html | 1089 +++ docs/doc/src/heapless/sealed.rs.html | 117 + .../src/heapless/sorted_linked_list.rs.html | 1733 ++++ docs/doc/src/heapless/string.rs.html | 1441 +++ docs/doc/src/heapless/vec.rs.html | 3201 +++++++ docs/doc/src/stable_deref_trait/lib.rs.html | 379 + docs/doc/stable_deref_trait/all.html | 1 + docs/doc/stable_deref_trait/index.html | 4 + docs/doc/stable_deref_trait/sidebar-items.js | 1 + .../trait.CloneStableDeref.html | 3 + .../stable_deref_trait/trait.StableDeref.html | 59 + 230 files changed, 48215 insertions(+), 40 deletions(-) create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/enum.Max.html create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/enum.Min.html create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/index.html create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/sidebar-items.js create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/struct.BinaryHeap.html create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/struct.PeekMut.html create mode 100644 docs/doc/arduboy_rust/heapless/binary_heap/trait.Kind.html create mode 100644 docs/doc/arduboy_rust/heapless/enum.Entry.html create mode 100644 docs/doc/arduboy_rust/heapless/index.html create mode 100644 docs/doc/arduboy_rust/heapless/sidebar-items.js create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/index.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/sidebar-items.js create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.FindMut.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Iter.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU16.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU8.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexUsize.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Max.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Min.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Node.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.SortedLinkedList.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.Kind.html create mode 100644 docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.BinaryHeap.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.Deque.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.HistoryBuffer.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.IndexMap.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.IndexSet.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.LinearMap.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.OccupiedEntry.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.OldestOrdered.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.String.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.VacantEntry.html create mode 100644 docs/doc/arduboy_rust/heapless/struct.Vec.html create mode 100644 docs/doc/arduboy_rust/heapless/type.FnvIndexMap.html create mode 100644 docs/doc/arduboy_rust/heapless/type.FnvIndexSet.html create mode 100644 docs/doc/arduboy_rust/prelude/struct.LinearMap.html create mode 100644 docs/doc/arduboy_rust/prelude/struct.String.html create mode 100644 docs/doc/arduboy_rust/prelude/struct.Vec.html create mode 100644 docs/doc/atomic_polyfill/all.html create mode 100644 docs/doc/atomic_polyfill/constant.ATOMIC_BOOL_INIT.html create mode 100644 docs/doc/atomic_polyfill/enum.Ordering.html create mode 100644 docs/doc/atomic_polyfill/fn.compiler_fence.html create mode 100644 docs/doc/atomic_polyfill/fn.fence.html create mode 100644 docs/doc/atomic_polyfill/fn.spin_loop_hint.html create mode 100644 docs/doc/atomic_polyfill/index.html create mode 100644 docs/doc/atomic_polyfill/sidebar-items.js create mode 100644 docs/doc/atomic_polyfill/struct.AtomicBool.html create mode 100644 docs/doc/atomic_polyfill/struct.AtomicI8.html create mode 100644 docs/doc/atomic_polyfill/struct.AtomicU8.html create mode 100644 docs/doc/byteorder/all.html create mode 100644 docs/doc/byteorder/enum.BigEndian.html create mode 100644 docs/doc/byteorder/enum.LittleEndian.html create mode 100644 docs/doc/byteorder/index.html create mode 100644 docs/doc/byteorder/sidebar-items.js create mode 100644 docs/doc/byteorder/trait.ByteOrder.html create mode 100644 docs/doc/byteorder/type.BE.html create mode 100644 docs/doc/byteorder/type.LE.html create mode 100644 docs/doc/byteorder/type.NativeEndian.html create mode 100644 docs/doc/byteorder/type.NetworkEndian.html create mode 100644 docs/doc/critical_section/all.html create mode 100644 docs/doc/critical_section/fn.acquire.html create mode 100644 docs/doc/critical_section/fn.release.html create mode 100644 docs/doc/critical_section/fn.with.html create mode 100644 docs/doc/critical_section/index.html create mode 100644 docs/doc/critical_section/macro.set_impl!.html create mode 100644 docs/doc/critical_section/macro.set_impl.html create mode 100644 docs/doc/critical_section/mutex/struct.Mutex.html create mode 100644 docs/doc/critical_section/sidebar-items.js create mode 100644 docs/doc/critical_section/struct.CriticalSection.html create mode 100644 docs/doc/critical_section/struct.Mutex.html create mode 100644 docs/doc/critical_section/struct.RestoreState.html create mode 100644 docs/doc/critical_section/trait.Impl.html create mode 100644 docs/doc/critical_section/type.RawRestoreState.html create mode 100644 docs/doc/hash32/all.html create mode 100644 docs/doc/hash32/fnv/struct.Hasher.html create mode 100644 docs/doc/hash32/index.html create mode 100644 docs/doc/hash32/murmur3/struct.Hasher.html create mode 100644 docs/doc/hash32/sidebar-items.js create mode 100644 docs/doc/hash32/struct.BuildHasherDefault.html create mode 100644 docs/doc/hash32/struct.FnvHasher.html create mode 100644 docs/doc/hash32/struct.Murmur3Hasher.html create mode 100644 docs/doc/hash32/trait.BuildHasher.html create mode 100644 docs/doc/hash32/trait.Hash.html create mode 100644 docs/doc/hash32/trait.Hasher.html create mode 100644 docs/doc/heapless/all.html create mode 100644 docs/doc/heapless/binary_heap/enum.Max.html create mode 100644 docs/doc/heapless/binary_heap/enum.Min.html create mode 100644 docs/doc/heapless/binary_heap/index.html create mode 100644 docs/doc/heapless/binary_heap/sidebar-items.js create mode 100644 docs/doc/heapless/binary_heap/struct.BinaryHeap.html create mode 100644 docs/doc/heapless/binary_heap/struct.PeekMut.html create mode 100644 docs/doc/heapless/binary_heap/trait.Kind.html create mode 100644 docs/doc/heapless/deque/struct.Deque.html create mode 100644 docs/doc/heapless/enum.Entry.html create mode 100644 docs/doc/heapless/histbuf/struct.HistoryBuffer.html create mode 100644 docs/doc/heapless/histbuf/struct.OldestOrdered.html create mode 100644 docs/doc/heapless/index.html create mode 100644 docs/doc/heapless/indexmap/enum.Entry.html create mode 100644 docs/doc/heapless/indexmap/struct.IndexMap.html create mode 100644 docs/doc/heapless/indexmap/struct.OccupiedEntry.html create mode 100644 docs/doc/heapless/indexmap/struct.VacantEntry.html create mode 100644 docs/doc/heapless/indexmap/type.FnvIndexMap.html create mode 100644 docs/doc/heapless/indexset/struct.IndexSet.html create mode 100644 docs/doc/heapless/indexset/type.FnvIndexSet.html create mode 100644 docs/doc/heapless/linear_map/struct.LinearMap.html create mode 100644 docs/doc/heapless/sidebar-items.js create mode 100644 docs/doc/heapless/sorted_linked_list/index.html create mode 100644 docs/doc/heapless/sorted_linked_list/sidebar-items.js create mode 100644 docs/doc/heapless/sorted_linked_list/struct.FindMut.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.Iter.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU16.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU8.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.LinkedIndexUsize.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.Max.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.Min.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.Node.html create mode 100644 docs/doc/heapless/sorted_linked_list/struct.SortedLinkedList.html create mode 100644 docs/doc/heapless/sorted_linked_list/trait.Kind.html create mode 100644 docs/doc/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html create mode 100644 docs/doc/heapless/string/struct.String.html create mode 100644 docs/doc/heapless/struct.Deque.html create mode 100644 docs/doc/heapless/struct.HistoryBuffer.html create mode 100644 docs/doc/heapless/struct.IndexMap.html create mode 100644 docs/doc/heapless/struct.IndexSet.html create mode 100644 docs/doc/heapless/struct.LinearMap.html create mode 100644 docs/doc/heapless/struct.OccupiedEntry.html create mode 100644 docs/doc/heapless/struct.OldestOrdered.html create mode 100644 docs/doc/heapless/struct.String.html create mode 100644 docs/doc/heapless/struct.VacantEntry.html create mode 100644 docs/doc/heapless/struct.Vec.html create mode 100644 docs/doc/heapless/type.FnvIndexMap.html create mode 100644 docs/doc/heapless/type.FnvIndexSet.html create mode 100644 docs/doc/heapless/vec/struct.Vec.html create mode 100644 docs/doc/implementors/byteorder/trait.ByteOrder.js create mode 100644 docs/doc/implementors/core/convert/trait.AsMut.js create mode 100644 docs/doc/implementors/core/convert/trait.AsRef.js create mode 100644 docs/doc/implementors/core/convert/trait.From.js create mode 100644 docs/doc/implementors/core/convert/trait.TryFrom.js create mode 100644 docs/doc/implementors/core/default/trait.Default.js create mode 100644 docs/doc/implementors/core/fmt/trait.Display.js create mode 100644 docs/doc/implementors/core/fmt/trait.Write.js create mode 100644 docs/doc/implementors/core/iter/traits/collect/trait.Extend.js create mode 100644 docs/doc/implementors/core/iter/traits/collect/trait.FromIterator.js create mode 100644 docs/doc/implementors/core/iter/traits/collect/trait.IntoIterator.js create mode 100644 docs/doc/implementors/core/iter/traits/iterator/trait.Iterator.js create mode 100644 docs/doc/implementors/core/ops/deref/trait.Deref.js create mode 100644 docs/doc/implementors/core/ops/deref/trait.DerefMut.js create mode 100644 docs/doc/implementors/core/ops/drop/trait.Drop.js create mode 100644 docs/doc/implementors/core/ops/index/trait.Index.js create mode 100644 docs/doc/implementors/core/ops/index/trait.IndexMut.js create mode 100644 docs/doc/implementors/core/str/traits/trait.FromStr.js create mode 100644 docs/doc/implementors/hash32/trait.BuildHasher.js create mode 100644 docs/doc/implementors/hash32/trait.Hash.js create mode 100644 docs/doc/implementors/hash32/trait.Hasher.js create mode 100644 docs/doc/implementors/heapless/binary_heap/trait.Kind.js create mode 100644 docs/doc/implementors/heapless/sorted_linked_list/trait.Kind.js create mode 100644 docs/doc/implementors/heapless/sorted_linked_list/trait.SortedLinkedListIndex.js create mode 100644 docs/doc/implementors/stable_deref_trait/trait.CloneStableDeref.js create mode 100644 docs/doc/implementors/stable_deref_trait/trait.StableDeref.js create mode 100644 docs/doc/src/atomic_polyfill/lib.rs.html create mode 100644 docs/doc/src/byteorder/lib.rs.html create mode 100644 docs/doc/src/critical_section/lib.rs.html create mode 100644 docs/doc/src/critical_section/mutex.rs.html create mode 100644 docs/doc/src/hash32/fnv.rs.html create mode 100644 docs/doc/src/hash32/lib.rs.html create mode 100644 docs/doc/src/hash32/murmur3.rs.html create mode 100644 docs/doc/src/heapless/binary_heap.rs.html create mode 100644 docs/doc/src/heapless/deque.rs.html create mode 100644 docs/doc/src/heapless/histbuf.rs.html create mode 100644 docs/doc/src/heapless/indexmap.rs.html create mode 100644 docs/doc/src/heapless/indexset.rs.html create mode 100644 docs/doc/src/heapless/lib.rs.html create mode 100644 docs/doc/src/heapless/linear_map.rs.html create mode 100644 docs/doc/src/heapless/sealed.rs.html create mode 100644 docs/doc/src/heapless/sorted_linked_list.rs.html create mode 100644 docs/doc/src/heapless/string.rs.html create mode 100644 docs/doc/src/heapless/vec.rs.html create mode 100644 docs/doc/src/stable_deref_trait/lib.rs.html create mode 100644 docs/doc/stable_deref_trait/all.html create mode 100644 docs/doc/stable_deref_trait/index.html create mode 100644 docs/doc/stable_deref_trait/sidebar-items.js create mode 100644 docs/doc/stable_deref_trait/trait.CloneStableDeref.html create mode 100644 docs/doc/stable_deref_trait/trait.StableDeref.html diff --git a/Cargo.lock b/Cargo.lock index 4bab1d2..b667302 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6,9 +6,37 @@ version = 3 name = "arduboy-rust" version = "1.0.0" dependencies = [ + "heapless", "panic-halt", ] +[[package]] +name = "atomic-polyfill" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ff7eb3f316534d83a8a2c3d1674ace8a5a71198eba31e2e2b597833f699b28" +dependencies = [ + "critical-section", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "critical-section" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7059fff8937831a9ae6f0fe4d658ffabf58f2ca96aa9dec1c889f936f705f216" + [[package]] name = "demo2" version = "0.1.0" @@ -72,6 +100,38 @@ dependencies = [ "arduboy-rust", ] +[[package]] +name = "hash32" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" +dependencies = [ + "byteorder", +] + +[[package]] +name = "heapless" +version = "0.7.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db04bc24a18b9ea980628ecf00e6c0264f3c1426dac36c00cb49b6fbad8b0743" +dependencies = [ + "atomic-polyfill", + "hash32", + "rustc_version", + "spin", + "stable_deref_trait", +] + +[[package]] +name = "lock_api" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +dependencies = [ + "autocfg", + "scopeguard", +] + [[package]] name = "panic-halt" version = "0.2.0" @@ -99,6 +159,27 @@ dependencies = [ "arduboy-rust", ] +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" + [[package]] name = "snake" version = "0.1.0" @@ -106,6 +187,21 @@ dependencies = [ "arduboy-rust", ] +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + [[package]] name = "tone" version = "0.1.0" diff --git a/Examples/drboy/Cargo.toml b/Examples/drboy/Cargo.toml index 0f34493..f196485 100644 --- a/Examples/drboy/Cargo.toml +++ b/Examples/drboy/Cargo.toml @@ -7,5 +7,4 @@ edition = "2021" crate-type = ["staticlib"] [dependencies] - arduboy-rust = { path = "../../arduboy-rust" } diff --git a/Examples/drboy/src/lib.rs b/Examples/drboy/src/lib.rs index de4cf67..7fe9489 100644 --- a/Examples/drboy/src/lib.rs +++ b/Examples/drboy/src/lib.rs @@ -26,6 +26,7 @@ progmem!( ]; ); // dynamic ram variables +#[derive(Debug)] struct Player { bitmap: *const u8, bitmap_frame: u8, @@ -39,6 +40,11 @@ static mut p: Player = Player { x: 0, y: 0, }; +progmem!( + static mut walls: Vec = Vec::new(); +); + +unsafe impl Sync for Player {} // The setup() function runs once when you turn your Arduboy on #[no_mangle] @@ -58,6 +64,9 @@ pub unsafe extern "C" fn loop_() { } arduboy.clear(); sprites::draw_override(p.x, p.y, p.bitmap, p.bitmap_frame); + walls.iter().for_each(|f| { + sprites::draw_override(f.x, f.y, f.bitmap, f.bitmap_frame); + }); arduboy.poll_buttons(); if arduboy.pressed(UP) { p.y -= 1; @@ -77,6 +86,16 @@ pub unsafe extern "C" fn loop_() { p.bitmap_frame = 0 } } + if arduboy.just_pressed(B) { + walls + .push(Player { + bitmap: get_sprite_addr!(pills), + bitmap_frame: 2, + x: random_between(10, 64) as i16, + y: random_between(10, 64) as i16, + }) + .unwrap(); + } arduboy.display(); } diff --git a/arduboy-rust/Cargo.toml b/arduboy-rust/Cargo.toml index b08ad4f..362a78d 100644 --- a/arduboy-rust/Cargo.toml +++ b/arduboy-rust/Cargo.toml @@ -13,4 +13,5 @@ categories = ["game-engines", "games", "api-bindings"] [dependencies] +heapless = "0.7.16" panic-halt = "0.2.0" diff --git a/arduboy-rust/src/lib.rs b/arduboy-rust/src/lib.rs index 29fbd93..2ae2472 100644 --- a/arduboy-rust/src/lib.rs +++ b/arduboy-rust/src/lib.rs @@ -30,6 +30,8 @@ pub mod hardware; mod library; pub mod prelude; mod print; +#[doc(inline)] +pub extern crate heapless; pub use crate::library::arduboy2::{self, Arduboy2, Color, FONT_SIZE, HEIGHT, WIDTH}; pub use crate::library::arduboy_tone::{self, ArduboyTones}; pub use crate::library::eeprom::{EEPROM, EEPROMBYTE}; diff --git a/arduboy-rust/src/library/progmem.rs b/arduboy-rust/src/library/progmem.rs index 61436d9..b54feed 100644 --- a/arduboy-rust/src/library/progmem.rs +++ b/arduboy-rust/src/library/progmem.rs @@ -16,6 +16,11 @@ /// progmem!( /// static image: [u8; _] = [8, 8, 0x81, 0x00, 0x12, 0x40, 0x04, 0x11, 0x00, 0x04]; /// ); +/// +/// // for a Vector +/// progmem!( +/// static mut walls: Vec = Vec::new(); +/// ); /// ``` #[macro_export] macro_rules! progmem { @@ -43,6 +48,30 @@ macro_rules! progmem { $($rest)* } }; + ( + $( #[$attr:meta] )* + $v:vis $id:ident $name:ident: $ty:ty = $value:expr; + $($rest:tt)* + ) => { + $( #[$attr] )* + #[link_section = ".progmem.data"] + $v $id $name: $ty = $value; + $crate::progmem!{ + $($rest)* + } + }; + ( + $( #[$attr:meta] )* + $v:vis $id:ident mut $name:ident: $ty:ty = $value:expr; + $($rest:tt)* + ) => { + $( #[$attr] )* + #[link_section = ".progmem.data"] + $v $id mut $name: $ty = $value; + $crate::progmem!{ + $($rest)* + } + }; () => () } diff --git a/arduboy-rust/src/prelude.rs b/arduboy-rust/src/prelude.rs index e869644..cbefac7 100644 --- a/arduboy-rust/src/prelude.rs +++ b/arduboy-rust/src/prelude.rs @@ -8,6 +8,7 @@ pub use crate::hardware::buttons::{self, *}; #[doc(inline)] pub use crate::hardware::led::{self, *}; +pub use crate::heapless::{LinearMap, String, Vec}; pub use crate::library::arduboy2::{self, *}; pub use crate::library::arduboy_tone::{self, ArduboyTones}; pub use crate::library::arduino::*; diff --git a/docs/doc/arduboy_rust/all.html b/docs/doc/arduboy_rust/all.html index a4622b9..fd884e0 100644 --- a/docs/doc/arduboy_rust/all.html +++ b/docs/doc/arduboy_rust/all.html @@ -1 +1 @@ -List of all items in this crate

List of all items

Structs

Enums

Traits

Macros

Functions

Type Definitions

Constants

\ No newline at end of file +List of all items in this crate

List of all items

Structs

Enums

Traits

Macros

Functions

Type Definitions

Constants

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/enum.Max.html b/docs/doc/arduboy_rust/heapless/binary_heap/enum.Max.html new file mode 100644 index 0000000..10242a2 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/enum.Max.html @@ -0,0 +1,12 @@ +Max in arduboy_rust::heapless::binary_heap - Rust
pub enum Max {}
Expand description

Max-heap

+

Trait Implementations§

source§

impl Kind for Max

Auto Trait Implementations§

§

impl RefUnwindSafe for Max

§

impl Send for Max

§

impl Sync for Max

§

impl Unpin for Max

§

impl UnwindSafe for Max

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/enum.Min.html b/docs/doc/arduboy_rust/heapless/binary_heap/enum.Min.html new file mode 100644 index 0000000..c06af34 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/enum.Min.html @@ -0,0 +1,12 @@ +Min in arduboy_rust::heapless::binary_heap - Rust
pub enum Min {}
Expand description

Min-heap

+

Trait Implementations§

source§

impl Kind for Min

Auto Trait Implementations§

§

impl RefUnwindSafe for Min

§

impl Send for Min

§

impl Sync for Min

§

impl Unpin for Min

§

impl UnwindSafe for Min

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/index.html b/docs/doc/arduboy_rust/heapless/binary_heap/index.html new file mode 100644 index 0000000..2836246 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/index.html @@ -0,0 +1,5 @@ +arduboy_rust::heapless::binary_heap - Rust
Expand description

A priority queue implemented with a binary heap.

+

Insertion and popping the largest element have O(log n) time complexity. Checking the largest +/ smallest element is O(1).

+

Structs

  • A priority queue implemented with a binary heap.
  • Structure wrapping a mutable reference to the greatest item on a +BinaryHeap.

Enums

Traits

  • The binary heap kind: min-heap or max-heap
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/sidebar-items.js b/docs/doc/arduboy_rust/heapless/binary_heap/sidebar-items.js new file mode 100644 index 0000000..1a0b7ee --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Max","Min"],"struct":["BinaryHeap","PeekMut"],"trait":["Kind"]}; \ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/struct.BinaryHeap.html b/docs/doc/arduboy_rust/heapless/binary_heap/struct.BinaryHeap.html new file mode 100644 index 0000000..b58129d --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/struct.BinaryHeap.html @@ -0,0 +1,197 @@ +BinaryHeap in arduboy_rust::heapless::binary_heap - Rust
pub struct BinaryHeap<T, K, const N: usize> { /* private fields */ }
Expand description

A priority queue implemented with a binary heap.

+

This can be either a min-heap or a max-heap.

+

It is a logic error for an item to be modified in such a way that the item’s ordering relative +to any other item, as determined by the Ord trait, changes while it is in the heap. This is +normally only possible through Cell, RefCell, global state, I/O, or unsafe code.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+
+// We can use peek to look at the next item in the heap. In this case,
+// there's no items in there yet so we get None.
+assert_eq!(heap.peek(), None);
+
+// Let's add some scores...
+heap.push(1).unwrap();
+heap.push(5).unwrap();
+heap.push(2).unwrap();
+
+// Now peek shows the most important item in the heap.
+assert_eq!(heap.peek(), Some(&5));
+
+// We can check the length of a heap.
+assert_eq!(heap.len(), 3);
+
+// We can iterate over the items in the heap, although they are returned in
+// a random order.
+for x in &heap {
+    println!("{}", x);
+}
+
+// If we instead pop these scores, they should come back in order.
+assert_eq!(heap.pop(), Some(5));
+assert_eq!(heap.pop(), Some(2));
+assert_eq!(heap.pop(), Some(1));
+assert_eq!(heap.pop(), None);
+
+// We can clear the heap of any remaining items.
+heap.clear();
+
+// The heap should now be empty.
+assert!(heap.is_empty())
+

Implementations§

source§

impl<T, K, const N: usize> BinaryHeap<T, K, N>

source

pub const fn new() -> BinaryHeap<T, K, N>

Creates an empty BinaryHeap as a $K-heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+// allocate the binary heap on the stack
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(4).unwrap();
+
+// allocate the binary heap in a static variable
+static mut HEAP: BinaryHeap<i32, Max, 8> = BinaryHeap::new();
+
source§

impl<T, K, const N: usize> BinaryHeap<T, K, N>where + T: Ord, + K: Kind,

source

pub fn capacity(&self) -> usize

Returns the capacity of the binary heap.

+
source

pub fn clear(&mut self)

Drops all items from the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert!(!heap.is_empty());
+
+heap.clear();
+
+assert!(heap.is_empty());
+
source

pub fn len(&self) -> usize

Returns the length of the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert_eq!(heap.len(), 2);
+
source

pub fn is_empty(&self) -> bool

Checks if the binary heap is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+
+assert!(heap.is_empty());
+
+heap.push(3).unwrap();
+heap.push(5).unwrap();
+heap.push(1).unwrap();
+
+assert!(!heap.is_empty());
+
source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator visiting all values in the underlying vector, in arbitrary order.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(2).unwrap();
+heap.push(3).unwrap();
+heap.push(4).unwrap();
+
+// Print 1, 2, 3, 4 in arbitrary order
+for x in heap.iter() {
+    println!("{}", x);
+
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator visiting all values in the underlying vector, in arbitrary order.

+

WARNING Mutating the items in the binary heap can leave the heap in an inconsistent +state.

+
source

pub fn peek(&self) -> Option<&T>

Returns the top (greatest if max-heap, smallest if min-heap) item in the binary heap, or +None if it is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+assert_eq!(heap.peek(), None);
+
+heap.push(1).unwrap();
+heap.push(5).unwrap();
+heap.push(2).unwrap();
+assert_eq!(heap.peek(), Some(&5));
+
source

pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, K, N>>

Returns a mutable reference to the greatest item in the binary heap, or +None if it is empty.

+

Note: If the PeekMut value is leaked, the heap may be in an +inconsistent state.

+
Examples
+

Basic usage:

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+assert!(heap.peek_mut().is_none());
+
+heap.push(1);
+heap.push(5);
+heap.push(2);
+{
+    let mut val = heap.peek_mut().unwrap();
+    *val = 0;
+}
+
+assert_eq!(heap.peek(), Some(&2));
+
source

pub fn pop(&mut self) -> Option<T>

Removes the top (greatest if max-heap, smallest if min-heap) item from the binary heap and +returns it, or None if it is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert_eq!(heap.pop(), Some(3));
+assert_eq!(heap.pop(), Some(1));
+assert_eq!(heap.pop(), None);
+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Removes the top (greatest if max-heap, smallest if min-heap) item from the binary heap and +returns it, without checking if the binary heap is empty.

+
source

pub fn push(&mut self, item: T) -> Result<(), T>

Pushes an item onto the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(3).unwrap();
+heap.push(5).unwrap();
+heap.push(1).unwrap();
+
+assert_eq!(heap.len(), 3);
+assert_eq!(heap.peek(), Some(&5));
+
source

pub unsafe fn push_unchecked(&mut self, item: T)

Pushes an item onto the binary heap without first checking if it’s full.

+
source

pub fn into_vec(self) -> Vec<T, N>

Returns the underlying Vec<T,N>. Order is arbitrary and time is O(1).

+

Trait Implementations§

source§

impl<T, K, const N: usize> Clone for BinaryHeap<T, K, N>where + K: Kind, + T: Ord + Clone,

source§

fn clone(&self) -> BinaryHeap<T, K, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, K, const N: usize> Debug for BinaryHeap<T, K, N>where + K: Kind, + T: Ord + Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, K, const N: usize> Default for BinaryHeap<T, K, N>where + T: Ord, + K: Kind,

source§

fn default() -> BinaryHeap<T, K, N>

Returns the “default value” for a type. Read more
source§

impl<'a, T, K, const N: usize> IntoIterator for &'a BinaryHeap<T, K, N>where + K: Kind, + T: Ord,

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a BinaryHeap<T, K, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, K, const N: usize> RefUnwindSafe for BinaryHeap<T, K, N>where + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, K, const N: usize> Send for BinaryHeap<T, K, N>where + K: Send, + T: Send,

§

impl<T, K, const N: usize> Sync for BinaryHeap<T, K, N>where + K: Sync, + T: Sync,

§

impl<T, K, const N: usize> Unpin for BinaryHeap<T, K, N>where + K: Unpin, + T: Unpin,

§

impl<T, K, const N: usize> UnwindSafe for BinaryHeap<T, K, N>where + K: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/struct.PeekMut.html b/docs/doc/arduboy_rust/heapless/binary_heap/struct.PeekMut.html new file mode 100644 index 0000000..a27e3de --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/struct.PeekMut.html @@ -0,0 +1,32 @@ +PeekMut in arduboy_rust::heapless::binary_heap - Rust
pub struct PeekMut<'a, T, K, const N: usize>where
+    T: Ord,
+    K: Kind,{ /* private fields */ }
Expand description

Structure wrapping a mutable reference to the greatest item on a +BinaryHeap.

+

This struct is created by the peek_mut method on BinaryHeap. See +its documentation for more.

+

Implementations§

source§

impl<'a, T, K, const N: usize> PeekMut<'a, T, K, N>where + T: Ord, + K: Kind,

source

pub fn pop(this: PeekMut<'a, T, K, N>) -> T

Removes the peeked value from the heap and returns it.

+

Trait Implementations§

source§

impl<T, K, const N: usize> Deref for PeekMut<'_, T, K, N>where + T: Ord, + K: Kind,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
source§

impl<T, K, const N: usize> DerefMut for PeekMut<'_, T, K, N>where + T: Ord, + K: Kind,

source§

fn deref_mut(&mut self) -> &mut T

Mutably dereferences the value.
source§

impl<T, K, const N: usize> Drop for PeekMut<'_, T, K, N>where + T: Ord, + K: Kind,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'a, T, K, const N: usize> RefUnwindSafe for PeekMut<'a, T, K, N>where + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<'a, T, K, const N: usize> Send for PeekMut<'a, T, K, N>where + K: Send, + T: Send,

§

impl<'a, T, K, const N: usize> Sync for PeekMut<'a, T, K, N>where + K: Sync, + T: Sync,

§

impl<'a, T, K, const N: usize> Unpin for PeekMut<'a, T, K, N>

§

impl<'a, T, K, const N: usize> !UnwindSafe for PeekMut<'a, T, K, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/binary_heap/trait.Kind.html b/docs/doc/arduboy_rust/heapless/binary_heap/trait.Kind.html new file mode 100644 index 0000000..b595623 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/binary_heap/trait.Kind.html @@ -0,0 +1,2 @@ +Kind in arduboy_rust::heapless::binary_heap - Rust
pub trait Kind: Sealed { }
Expand description

The binary heap kind: min-heap or max-heap

+

Implementors§

source§

impl Kind for Max

source§

impl Kind for Min

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/enum.Entry.html b/docs/doc/arduboy_rust/heapless/enum.Entry.html new file mode 100644 index 0000000..536fcc3 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/enum.Entry.html @@ -0,0 +1,24 @@ +Entry in arduboy_rust::heapless - Rust
pub enum Entry<'a, K, V, const N: usize> {
+    Occupied(OccupiedEntry<'a, K, V, N>),
+    Vacant(VacantEntry<'a, K, V, N>),
+}
Expand description

A view into an entry in the map

+

Variants§

§

Occupied(OccupiedEntry<'a, K, V, N>)

The entry corresponding to the key K exists in the map

+
§

Vacant(VacantEntry<'a, K, V, N>)

The entry corresponding to the key K does not exist in the map

+

Auto Trait Implementations§

§

impl<'a, K, V, const N: usize> RefUnwindSafe for Entry<'a, K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<'a, K, V, const N: usize> Send for Entry<'a, K, V, N>where + K: Send, + V: Send,

§

impl<'a, K, V, const N: usize> Sync for Entry<'a, K, V, N>where + K: Sync, + V: Sync,

§

impl<'a, K, V, const N: usize> Unpin for Entry<'a, K, V, N>where + K: Unpin,

§

impl<'a, K, V, const N: usize> !UnwindSafe for Entry<'a, K, V, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/index.html b/docs/doc/arduboy_rust/heapless/index.html new file mode 100644 index 0000000..1a5f22c --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/index.html @@ -0,0 +1,64 @@ +arduboy_rust::heapless - Rust
Expand description

static friendly data structures that don’t require dynamic memory allocation

+

The core principle behind heapless is that its data structures are backed by a static memory +allocation. For example, you can think of heapless::Vec as an alternative version of +std::Vec with fixed capacity and that can’t be re-allocated on the fly (e.g. via push).

+

All heapless data structures store their memory allocation inline and specify their capacity +via their type parameter N. This means that you can instantiate a heapless data structure on +the stack, in a static variable, or even in the heap.

+ +
use heapless::Vec; // fixed capacity `std::Vec`
+
+// on the stack
+let mut xs: Vec<u8, 8> = Vec::new(); // can hold up to 8 elements
+xs.push(42).unwrap();
+assert_eq!(xs.pop(), Some(42));
+
+// in a `static` variable
+static mut XS: Vec<u8, 8> = Vec::new();
+
+let xs = unsafe { &mut XS };
+
+xs.push(42);
+assert_eq!(xs.pop(), Some(42));
+
+// in the heap (though kind of pointless because no reallocation)
+let mut ys: Box<Vec<u8, 8>> = Box::new(Vec::new());
+ys.push(42).unwrap();
+assert_eq!(ys.pop(), Some(42));
+

Because they have fixed capacity heapless data structures don’t implicitly reallocate. This +means that operations like heapless::Vec.push are truly constant time rather than amortized +constant time with potentially unbounded (depends on the allocator) worst case execution time +(which is bad / unacceptable for hard real time applications).

+

heapless data structures don’t use a memory allocator which means no risk of an uncatchable +Out Of Memory (OOM) condition while performing operations on them. It’s certainly possible to +run out of capacity while growing heapless data structures, but the API lets you handle this +possibility by returning a Result on operations that may exhaust the capacity of the data +structure.

+

List of currently implemented data structures:

+ +

Optional Features

+

The heapless crate provides the following optional Cargo features:

+ +

Minimum Supported Rust Version (MSRV)

+

This crate is guaranteed to compile on stable Rust 1.51 and up with its default set of features. +It might compile on older versions but that may change in any new patch release.

+

Modules

  • A priority queue implemented with a binary heap.
  • A fixed sorted priority linked list, similar to BinaryHeap but with different properties +on push, pop, etc. +For example, the sorting of the list will never memcpy the underlying value, so having large +objects in the list will not cause a performance hit.

Structs

Enums

  • A view into an entry in the map

Type Definitions

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sidebar-items.js b/docs/doc/arduboy_rust/heapless/sidebar-items.js new file mode 100644 index 0000000..47fb163 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Entry"],"mod":["binary_heap","sorted_linked_list"],"struct":["BinaryHeap","Deque","HistoryBuffer","IndexMap","IndexSet","LinearMap","OccupiedEntry","OldestOrdered","String","VacantEntry","Vec"],"type":["FnvIndexMap","FnvIndexSet"]}; \ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/index.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/index.html new file mode 100644 index 0000000..fa33aa1 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/index.html @@ -0,0 +1,21 @@ +arduboy_rust::heapless::sorted_linked_list - Rust
Expand description

A fixed sorted priority linked list, similar to BinaryHeap but with different properties +on push, pop, etc. +For example, the sorting of the list will never memcpy the underlying value, so having large +objects in the list will not cause a performance hit.

+

Examples

+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+// The largest value will always be first
+ll.push(1).unwrap();
+assert_eq!(ll.peek(), Some(&1));
+
+ll.push(2).unwrap();
+assert_eq!(ll.peek(), Some(&2));
+
+ll.push(3).unwrap();
+assert_eq!(ll.peek(), Some(&3));
+
+// This will not fit in the queue.
+assert_eq!(ll.push(4), Err(4));
+

Structs

Traits

  • The linked list kind: min-list or max-list
  • Trait for defining an index for the linked list, never implemented by users.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/sidebar-items.js b/docs/doc/arduboy_rust/heapless/sorted_linked_list/sidebar-items.js new file mode 100644 index 0000000..ae6b39f --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["FindMut","Iter","LinkedIndexU16","LinkedIndexU8","LinkedIndexUsize","Max","Min","Node","SortedLinkedList"],"trait":["Kind","SortedLinkedListIndex"]}; \ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.FindMut.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.FindMut.html new file mode 100644 index 0000000..f65ece0 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.FindMut.html @@ -0,0 +1,77 @@ +FindMut in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct FindMut<'a, T, Idx, K, const N: usize>where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,{ /* private fields */ }
Expand description

Implementations§

source§

impl<'a, T, Idx, K, const N: usize> FindMut<'a, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source

pub fn pop(self) -> T

This will pop the element from the list.

+

Complexity is worst-case O(1).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+ll.push(3).unwrap();
+
+// Find a value and update it
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+find.pop();
+
+assert_eq!(ll.pop(), Ok(3));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+
source

pub fn finish(self)

This will resort the element into the correct position in the list if needed. The resorting +will only happen if the element has been accessed mutably.

+

Same as calling drop.

+

Complexity is worst-case O(N).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+ll.push(3).unwrap();
+
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+find.finish(); // No resort, we did not access the value.
+
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+*find += 1000;
+find.finish(); // Will resort, we accessed (and updated) the value.
+
+assert_eq!(ll.pop(), Ok(1002));
+assert_eq!(ll.pop(), Ok(3));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+

Trait Implementations§

source§

impl<T, Idx, K, const N: usize> Deref for FindMut<'_, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &<FindMut<'_, T, Idx, K, N> as Deref>::Target

Dereferences the value.
source§

impl<T, Idx, K, const N: usize> DerefMut for FindMut<'_, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source§

fn deref_mut(&mut self) -> &mut <FindMut<'_, T, Idx, K, N> as Deref>::Target

Mutably dereferences the value.
source§

impl<T, Idx, K, const N: usize> Drop for FindMut<'_, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'a, T, Idx, K, const N: usize> RefUnwindSafe for FindMut<'a, T, Idx, K, N>where + Idx: RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<'a, T, Idx, K, const N: usize> Send for FindMut<'a, T, Idx, K, N>where + Idx: Send, + K: Send, + T: Send,

§

impl<'a, T, Idx, K, const N: usize> Sync for FindMut<'a, T, Idx, K, N>where + Idx: Sync, + K: Sync, + T: Sync,

§

impl<'a, T, Idx, K, const N: usize> Unpin for FindMut<'a, T, Idx, K, N>where + Idx: Unpin,

§

impl<'a, T, Idx, K, const N: usize> !UnwindSafe for FindMut<'a, T, Idx, K, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Iter.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Iter.html new file mode 100644 index 0000000..478baf8 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Iter.html @@ -0,0 +1,205 @@ +Iter in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct Iter<'a, T, Idx, K, const N: usize>where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,{ /* private fields */ }
Expand description

Iterator for the linked list.

+

Trait Implementations§

source§

impl<'a, T, Idx, K, const N: usize> Iterator for Iter<'a, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

§

type Item = &'a T

The type of the elements being iterated over.
source§

fn next(&mut self) -> Option<<Iter<'a, T, Idx, K, N> as Iterator>::Item>

Advances the iterator and returns the next value. Read more
§

fn next_chunk<const N: usize>( + &mut self +) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.0.0§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
1.0.0§

fn count(self) -> usizewhere + Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
1.0.0§

fn last(self) -> Option<Self::Item>where + Self: Sized,

Consumes the iterator, returning the last element. Read more
§

fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.0.0§

fn nth(&mut self, n: usize) -> Option<Self::Item>

Returns the nth element of the iterator. Read more
1.28.0§

fn step_by(self, step: usize) -> StepBy<Self>where + Self: Sized,

Creates an iterator starting at the same point, but stepping by +the given amount at each iteration. Read more
1.0.0§

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.0.0§

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator,

‘Zips up’ two iterators into a single iterator of pairs. Read more
§

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>where + Self: Sized, + G: FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator +between adjacent items of the original iterator. Read more
1.0.0§

fn map<B, F>(self, f: F) -> Map<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each +element. Read more
1.21.0§

fn for_each<F>(self, f: F)where + Self: Sized, + F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.0.0§

fn filter<P>(self, predicate: P) -> Filter<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element +should be yielded. Read more
1.0.0§

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.0.0§

fn enumerate(self) -> Enumerate<Self>where + Self: Sized,

Creates an iterator which gives the current iteration count as well as +the next value. Read more
1.0.0§

fn peekable(self) -> Peekable<Self>where + Self: Sized,

Creates an iterator which can use the peek and peek_mut methods +to look at the next element of the iterator without consuming it. See +their documentation for more information. Read more
1.0.0§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.0.0§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where + Self: Sized, + P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.0.0§

fn skip(self, n: usize) -> Skip<Self>where + Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.0.0§

fn take(self, n: usize) -> Take<Self>where + Self: Sized,

Creates an iterator that yields the first n elements, or fewer +if the underlying iterator ends sooner. Read more
1.0.0§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where + Self: Sized, + F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but +unlike fold, produces a new iterator. Read more
1.0.0§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where + Self: Sized, + U: IntoIterator, + F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
1.0.0§

fn fuse(self) -> Fuse<Self>where + Self: Sized,

Creates an iterator which ends after the first [None]. Read more
1.0.0§

fn inspect<F>(self, f: F) -> Inspect<Self, F>where + Self: Sized, + F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.0.0§

fn by_ref(&mut self) -> &mut Selfwhere + Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.0.0§

fn collect<B>(self) -> Bwhere + B: FromIterator<Self::Item>, + Self: Sized,

Transforms an iterator into a collection. Read more
§

fn collect_into<E>(self, collection: &mut E) -> &mut Ewhere + E: Extend<Self::Item>, + Self: Sized,

🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.0.0§

fn partition<B, F>(self, f: F) -> (B, B)where + Self: Sized, + B: Default + Extend<Self::Item>, + F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
§

fn is_partitioned<P>(self, predicate: P) -> boolwhere + Self: Sized, + P: FnMut(Self::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate, +such that all those that return true precede all those that return false. Read more
1.27.0§

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try<Output = B>,

An iterator method that applies a function as long as it returns +successfully, producing a single, final value. Read more
1.27.0§

fn try_for_each<F, R>(&mut self, f: F) -> Rwhere + Self: Sized, + F: FnMut(Self::Item) -> R, + R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the +iterator, stopping at the first error and returning that error. Read more
1.0.0§

fn fold<B, F>(self, init: B, f: F) -> Bwhere + Self: Sized, + F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation, +returning the final result. Read more
1.51.0§

fn reduce<F>(self, f: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing +operation. Read more
§

fn try_reduce<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> R, + R: Try<Output = Self::Item>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the +closure returns a failure, the failure is propagated back to the caller immediately. Read more
1.0.0§

fn all<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.0.0§

fn any<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.0.0§

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0§

fn find_map<B, F>(&mut self, f: F) -> Option<B>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns +the first non-none result. Read more
§

fn try_find<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere + Self: Sized, + F: FnMut(&Self::Item) -> R, + R: Try<Output = bool>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns +the first true result or the first error. Read more
1.0.0§

fn position<P>(&mut self, predicate: P) -> Option<usize>where + Self: Sized, + P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0§

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the +specified function. Read more
1.15.0§

fn max_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the +specified comparison function. Read more
1.6.0§

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the +specified function. Read more
1.15.0§

fn min_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the +specified comparison function. Read more
1.0.0§

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where + FromA: Default + Extend<A>, + FromB: Default + Extend<B>, + Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0§

fn copied<'a, T>(self) -> Copied<Self>where + T: 'a + Copy, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.0.0§

fn cloned<'a, T>(self) -> Cloned<Self>where + T: 'a + Clone, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
§

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0§

fn sum<S>(self) -> Swhere + Self: Sized, + S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0§

fn product<P>(self) -> Pwhere + Self: Sized, + P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
§

fn cmp_by<I, F>(self, other: I, cmp: F) -> Orderingwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn partial_cmp<I>(self, other: I) -> Option<Ordering>where + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Lexicographically compares the [PartialOrd] elements of +this [Iterator] with those of another. The comparison works like short-circuit +evaluation, returning a result without comparing the remaining elements. +As soon as an order can be determined, the evaluation stops and a result is returned. Read more
§

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn eq<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are equal to those of +another. Read more
§

fn eq_by<I, F>(self, other: I, eq: F) -> boolwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this [Iterator] are equal to those of +another with respect to the specified equality function. Read more
1.5.0§

fn ne<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are not equal to those of +another. Read more
1.5.0§

fn lt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less than those of another. Read more
1.5.0§

fn le<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less or equal to those of another. Read more
1.5.0§

fn gt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than those of another. Read more
1.5.0§

fn ge<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than or equal to those of another. Read more
§

fn is_sorted_by<F>(self, compare: F) -> boolwhere + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
§

fn is_sorted_by_key<F, K>(self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction +function. Read more

Auto Trait Implementations§

§

impl<'a, T, Idx, K, const N: usize> RefUnwindSafe for Iter<'a, T, Idx, K, N>where + Idx: RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<'a, T, Idx, K, const N: usize> Send for Iter<'a, T, Idx, K, N>where + Idx: Send + Sync, + K: Sync, + T: Sync,

§

impl<'a, T, Idx, K, const N: usize> Sync for Iter<'a, T, Idx, K, N>where + Idx: Sync, + K: Sync, + T: Sync,

§

impl<'a, T, Idx, K, const N: usize> Unpin for Iter<'a, T, Idx, K, N>where + Idx: Unpin,

§

impl<'a, T, Idx, K, const N: usize> UnwindSafe for Iter<'a, T, Idx, K, N>where + Idx: UnwindSafe + RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<I> IntoIterator for Iwhere + I: Iterator,

§

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
§

type IntoIter = I

Which kind of iterator are we turning this into?
const: unstable§

fn into_iter(self) -> I

Creates an iterator from a value. Read more
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU16.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU16.html new file mode 100644 index 0000000..f40a4c3 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU16.html @@ -0,0 +1,19 @@ +LinkedIndexU16 in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct LinkedIndexU16(_);
Expand description

Index for the SortedLinkedList with specific backing storage.

+

Trait Implementations§

source§

impl Clone for LinkedIndexU16

source§

fn clone(&self) -> LinkedIndexU16

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LinkedIndexU16

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Ord for LinkedIndexU16

source§

fn cmp(&self, other: &LinkedIndexU16) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LinkedIndexU16> for LinkedIndexU16

source§

fn eq(&self, other: &LinkedIndexU16) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LinkedIndexU16> for LinkedIndexU16

source§

fn partial_cmp(&self, other: &LinkedIndexU16) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LinkedIndexU16

source§

impl Eq for LinkedIndexU16

source§

impl SortedLinkedListIndex for LinkedIndexU16

source§

impl StructuralEq for LinkedIndexU16

source§

impl StructuralPartialEq for LinkedIndexU16

Auto Trait Implementations§

§

impl RefUnwindSafe for LinkedIndexU16

§

impl Send for LinkedIndexU16

§

impl Sync for LinkedIndexU16

§

impl Unpin for LinkedIndexU16

§

impl UnwindSafe for LinkedIndexU16

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU8.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU8.html new file mode 100644 index 0000000..dbbd845 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexU8.html @@ -0,0 +1,19 @@ +LinkedIndexU8 in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct LinkedIndexU8(_);
Expand description

Index for the SortedLinkedList with specific backing storage.

+

Trait Implementations§

source§

impl Clone for LinkedIndexU8

source§

fn clone(&self) -> LinkedIndexU8

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LinkedIndexU8

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Ord for LinkedIndexU8

source§

fn cmp(&self, other: &LinkedIndexU8) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LinkedIndexU8> for LinkedIndexU8

source§

fn eq(&self, other: &LinkedIndexU8) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LinkedIndexU8> for LinkedIndexU8

source§

fn partial_cmp(&self, other: &LinkedIndexU8) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LinkedIndexU8

source§

impl Eq for LinkedIndexU8

source§

impl SortedLinkedListIndex for LinkedIndexU8

source§

impl StructuralEq for LinkedIndexU8

source§

impl StructuralPartialEq for LinkedIndexU8

Auto Trait Implementations§

§

impl RefUnwindSafe for LinkedIndexU8

§

impl Send for LinkedIndexU8

§

impl Sync for LinkedIndexU8

§

impl Unpin for LinkedIndexU8

§

impl UnwindSafe for LinkedIndexU8

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexUsize.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexUsize.html new file mode 100644 index 0000000..c63080f --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.LinkedIndexUsize.html @@ -0,0 +1,19 @@ +LinkedIndexUsize in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct LinkedIndexUsize(_);
Expand description

Index for the SortedLinkedList with specific backing storage.

+

Trait Implementations§

source§

impl Clone for LinkedIndexUsize

source§

fn clone(&self) -> LinkedIndexUsize

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LinkedIndexUsize

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Ord for LinkedIndexUsize

source§

fn cmp(&self, other: &LinkedIndexUsize) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LinkedIndexUsize> for LinkedIndexUsize

source§

fn eq(&self, other: &LinkedIndexUsize) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LinkedIndexUsize> for LinkedIndexUsize

source§

fn partial_cmp(&self, other: &LinkedIndexUsize) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LinkedIndexUsize

source§

impl Eq for LinkedIndexUsize

source§

impl SortedLinkedListIndex for LinkedIndexUsize

source§

impl StructuralEq for LinkedIndexUsize

source§

impl StructuralPartialEq for LinkedIndexUsize

Auto Trait Implementations§

§

impl RefUnwindSafe for LinkedIndexUsize

§

impl Send for LinkedIndexUsize

§

impl Sync for LinkedIndexUsize

§

impl Unpin for LinkedIndexUsize

§

impl UnwindSafe for LinkedIndexUsize

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Max.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Max.html new file mode 100644 index 0000000..dbb2258 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Max.html @@ -0,0 +1,12 @@ +Max in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct Max;
Expand description

Marker for Max sorted SortedLinkedList.

+

Trait Implementations§

source§

impl Kind for Max

Auto Trait Implementations§

§

impl RefUnwindSafe for Max

§

impl Send for Max

§

impl Sync for Max

§

impl Unpin for Max

§

impl UnwindSafe for Max

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Min.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Min.html new file mode 100644 index 0000000..6871435 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Min.html @@ -0,0 +1,12 @@ +Min in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct Min;
Expand description

Marker for Min sorted SortedLinkedList.

+

Trait Implementations§

source§

impl Kind for Min

Auto Trait Implementations§

§

impl RefUnwindSafe for Min

§

impl Send for Min

§

impl Sync for Min

§

impl Unpin for Min

§

impl UnwindSafe for Min

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Node.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Node.html new file mode 100644 index 0000000..2d47de3 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.Node.html @@ -0,0 +1,22 @@ +Node in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct Node<T, Idx> { /* private fields */ }
Expand description

A node in the SortedLinkedList.

+

Auto Trait Implementations§

§

impl<T, Idx> RefUnwindSafe for Node<T, Idx>where + Idx: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, Idx> Send for Node<T, Idx>where + Idx: Send, + T: Send,

§

impl<T, Idx> Sync for Node<T, Idx>where + Idx: Sync, + T: Sync,

§

impl<T, Idx> Unpin for Node<T, Idx>where + Idx: Unpin, + T: Unpin,

§

impl<T, Idx> UnwindSafe for Node<T, Idx>where + Idx: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.SortedLinkedList.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.SortedLinkedList.html new file mode 100644 index 0000000..1682156 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/struct.SortedLinkedList.html @@ -0,0 +1,151 @@ +SortedLinkedList in arduboy_rust::heapless::sorted_linked_list - Rust
pub struct SortedLinkedList<T, Idx, K, const N: usize>where
+    Idx: SortedLinkedListIndex,{ /* private fields */ }
Expand description

The linked list.

+

Implementations§

source§

impl<T, K, const N: usize> SortedLinkedList<T, LinkedIndexU8, K, N>

source

pub const fn new_u8() -> SortedLinkedList<T, LinkedIndexU8, K, N>

Create a new linked list.

+
source§

impl<T, K, const N: usize> SortedLinkedList<T, LinkedIndexU16, K, N>

source

pub const fn new_u16() -> SortedLinkedList<T, LinkedIndexU16, K, N>

Create a new linked list.

+
source§

impl<T, K, const N: usize> SortedLinkedList<T, LinkedIndexUsize, K, N>

source

pub const fn new_usize() -> SortedLinkedList<T, LinkedIndexUsize, K, N>

Create a new linked list.

+
source§

impl<T, Idx, K, const N: usize> SortedLinkedList<T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source

pub unsafe fn push_unchecked(&mut self, value: T)

Pushes a value onto the list without checking if the list is full.

+

Complexity is worst-case O(N).

+
Safety
+

Assumes that the list is not full.

+
source

pub fn push(&mut self, value: T) -> Result<(), T>

Pushes an element to the linked list and sorts it into place.

+

Complexity is worst-case O(N).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+// The largest value will always be first
+ll.push(1).unwrap();
+assert_eq!(ll.peek(), Some(&1));
+
+ll.push(2).unwrap();
+assert_eq!(ll.peek(), Some(&2));
+
+ll.push(3).unwrap();
+assert_eq!(ll.peek(), Some(&3));
+
+// This will not fit in the queue.
+assert_eq!(ll.push(4), Err(4));
+
source

pub fn iter(&self) -> Iter<'_, T, Idx, K, N>

Get an iterator over the sorted list.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+
+let mut iter = ll.iter();
+
+assert_eq!(iter.next(), Some(&2));
+assert_eq!(iter.next(), Some(&1));
+assert_eq!(iter.next(), None);
+
source

pub fn find_mut<F>(&mut self, f: F) -> Option<FindMut<'_, T, Idx, K, N>>where + F: FnMut(&T) -> bool,

Find an element in the list that can be changed and resorted.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+ll.push(3).unwrap();
+
+// Find a value and update it
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+*find += 1000;
+find.finish();
+
+assert_eq!(ll.pop(), Ok(1002));
+assert_eq!(ll.pop(), Ok(3));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+
source

pub fn peek(&self) -> Option<&T>

Peek at the first element.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max, Min};
+let mut ll_max: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+// The largest value will always be first
+ll_max.push(1).unwrap();
+assert_eq!(ll_max.peek(), Some(&1));
+ll_max.push(2).unwrap();
+assert_eq!(ll_max.peek(), Some(&2));
+ll_max.push(3).unwrap();
+assert_eq!(ll_max.peek(), Some(&3));
+
+let mut ll_min: SortedLinkedList<_, _, Min, 3> = SortedLinkedList::new_usize();
+
+// The Smallest value will always be first
+ll_min.push(3).unwrap();
+assert_eq!(ll_min.peek(), Some(&3));
+ll_min.push(2).unwrap();
+assert_eq!(ll_min.peek(), Some(&2));
+ll_min.push(1).unwrap();
+assert_eq!(ll_min.peek(), Some(&1));
+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Pop an element from the list without checking so the list is not empty.

+
Safety
+

Assumes that the list is not empty.

+
source

pub fn pop(&mut self) -> Result<T, ()>

Pops the first element in the list.

+

Complexity is worst-case O(1).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+
+assert_eq!(ll.pop(), Ok(2));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+
source

pub fn is_full(&self) -> bool

Checks if the linked list is full.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+assert_eq!(ll.is_full(), false);
+
+ll.push(1).unwrap();
+assert_eq!(ll.is_full(), false);
+ll.push(2).unwrap();
+assert_eq!(ll.is_full(), false);
+ll.push(3).unwrap();
+assert_eq!(ll.is_full(), true);
+
source

pub fn is_empty(&self) -> bool

Checks if the linked list is empty.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+assert_eq!(ll.is_empty(), true);
+
+ll.push(1).unwrap();
+assert_eq!(ll.is_empty(), false);
+

Trait Implementations§

source§

impl<T, Idx, K, const N: usize> Debug for SortedLinkedList<T, Idx, K, N>where + T: Ord + Debug, + Idx: SortedLinkedListIndex, + K: Kind,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, Idx, K, const N: usize> Drop for SortedLinkedList<T, Idx, K, N>where + Idx: SortedLinkedListIndex,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T, Idx, K, const N: usize> RefUnwindSafe for SortedLinkedList<T, Idx, K, N>where + Idx: RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, Idx, K, const N: usize> Send for SortedLinkedList<T, Idx, K, N>where + Idx: Send, + K: Send, + T: Send,

§

impl<T, Idx, K, const N: usize> Sync for SortedLinkedList<T, Idx, K, N>where + Idx: Sync, + K: Sync, + T: Sync,

§

impl<T, Idx, K, const N: usize> Unpin for SortedLinkedList<T, Idx, K, N>where + Idx: Unpin, + K: Unpin, + T: Unpin,

§

impl<T, Idx, K, const N: usize> UnwindSafe for SortedLinkedList<T, Idx, K, N>where + Idx: UnwindSafe, + K: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.Kind.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.Kind.html new file mode 100644 index 0000000..5101c01 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.Kind.html @@ -0,0 +1,2 @@ +Kind in arduboy_rust::heapless::sorted_linked_list - Rust
pub trait Kind: Sealed { }
Expand description

The linked list kind: min-list or max-list

+

Implementors§

source§

impl Kind for Max

source§

impl Kind for Min

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html b/docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html new file mode 100644 index 0000000..3583833 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html @@ -0,0 +1,2 @@ +SortedLinkedListIndex in arduboy_rust::heapless::sorted_linked_list - Rust
pub trait SortedLinkedListIndex: Copy { }
Expand description

Trait for defining an index for the linked list, never implemented by users.

+

Implementors§

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.BinaryHeap.html b/docs/doc/arduboy_rust/heapless/struct.BinaryHeap.html new file mode 100644 index 0000000..e065857 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.BinaryHeap.html @@ -0,0 +1,197 @@ +BinaryHeap in arduboy_rust::heapless - Rust
pub struct BinaryHeap<T, K, const N: usize> { /* private fields */ }
Expand description

A priority queue implemented with a binary heap.

+

This can be either a min-heap or a max-heap.

+

It is a logic error for an item to be modified in such a way that the item’s ordering relative +to any other item, as determined by the Ord trait, changes while it is in the heap. This is +normally only possible through Cell, RefCell, global state, I/O, or unsafe code.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+
+// We can use peek to look at the next item in the heap. In this case,
+// there's no items in there yet so we get None.
+assert_eq!(heap.peek(), None);
+
+// Let's add some scores...
+heap.push(1).unwrap();
+heap.push(5).unwrap();
+heap.push(2).unwrap();
+
+// Now peek shows the most important item in the heap.
+assert_eq!(heap.peek(), Some(&5));
+
+// We can check the length of a heap.
+assert_eq!(heap.len(), 3);
+
+// We can iterate over the items in the heap, although they are returned in
+// a random order.
+for x in &heap {
+    println!("{}", x);
+}
+
+// If we instead pop these scores, they should come back in order.
+assert_eq!(heap.pop(), Some(5));
+assert_eq!(heap.pop(), Some(2));
+assert_eq!(heap.pop(), Some(1));
+assert_eq!(heap.pop(), None);
+
+// We can clear the heap of any remaining items.
+heap.clear();
+
+// The heap should now be empty.
+assert!(heap.is_empty())
+

Implementations§

source§

impl<T, K, const N: usize> BinaryHeap<T, K, N>

source

pub const fn new() -> BinaryHeap<T, K, N>

Creates an empty BinaryHeap as a $K-heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+// allocate the binary heap on the stack
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(4).unwrap();
+
+// allocate the binary heap in a static variable
+static mut HEAP: BinaryHeap<i32, Max, 8> = BinaryHeap::new();
+
source§

impl<T, K, const N: usize> BinaryHeap<T, K, N>where + T: Ord, + K: Kind,

source

pub fn capacity(&self) -> usize

Returns the capacity of the binary heap.

+
source

pub fn clear(&mut self)

Drops all items from the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert!(!heap.is_empty());
+
+heap.clear();
+
+assert!(heap.is_empty());
+
source

pub fn len(&self) -> usize

Returns the length of the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert_eq!(heap.len(), 2);
+
source

pub fn is_empty(&self) -> bool

Checks if the binary heap is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+
+assert!(heap.is_empty());
+
+heap.push(3).unwrap();
+heap.push(5).unwrap();
+heap.push(1).unwrap();
+
+assert!(!heap.is_empty());
+
source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator visiting all values in the underlying vector, in arbitrary order.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(2).unwrap();
+heap.push(3).unwrap();
+heap.push(4).unwrap();
+
+// Print 1, 2, 3, 4 in arbitrary order
+for x in heap.iter() {
+    println!("{}", x);
+
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator visiting all values in the underlying vector, in arbitrary order.

+

WARNING Mutating the items in the binary heap can leave the heap in an inconsistent +state.

+
source

pub fn peek(&self) -> Option<&T>

Returns the top (greatest if max-heap, smallest if min-heap) item in the binary heap, or +None if it is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+assert_eq!(heap.peek(), None);
+
+heap.push(1).unwrap();
+heap.push(5).unwrap();
+heap.push(2).unwrap();
+assert_eq!(heap.peek(), Some(&5));
+
source

pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, K, N>>

Returns a mutable reference to the greatest item in the binary heap, or +None if it is empty.

+

Note: If the PeekMut value is leaked, the heap may be in an +inconsistent state.

+
Examples
+

Basic usage:

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+assert!(heap.peek_mut().is_none());
+
+heap.push(1);
+heap.push(5);
+heap.push(2);
+{
+    let mut val = heap.peek_mut().unwrap();
+    *val = 0;
+}
+
+assert_eq!(heap.peek(), Some(&2));
+
source

pub fn pop(&mut self) -> Option<T>

Removes the top (greatest if max-heap, smallest if min-heap) item from the binary heap and +returns it, or None if it is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert_eq!(heap.pop(), Some(3));
+assert_eq!(heap.pop(), Some(1));
+assert_eq!(heap.pop(), None);
+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Removes the top (greatest if max-heap, smallest if min-heap) item from the binary heap and +returns it, without checking if the binary heap is empty.

+
source

pub fn push(&mut self, item: T) -> Result<(), T>

Pushes an item onto the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(3).unwrap();
+heap.push(5).unwrap();
+heap.push(1).unwrap();
+
+assert_eq!(heap.len(), 3);
+assert_eq!(heap.peek(), Some(&5));
+
source

pub unsafe fn push_unchecked(&mut self, item: T)

Pushes an item onto the binary heap without first checking if it’s full.

+
source

pub fn into_vec(self) -> Vec<T, N>

Returns the underlying Vec<T,N>. Order is arbitrary and time is O(1).

+

Trait Implementations§

source§

impl<T, K, const N: usize> Clone for BinaryHeap<T, K, N>where + K: Kind, + T: Ord + Clone,

source§

fn clone(&self) -> BinaryHeap<T, K, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, K, const N: usize> Debug for BinaryHeap<T, K, N>where + K: Kind, + T: Ord + Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, K, const N: usize> Default for BinaryHeap<T, K, N>where + T: Ord, + K: Kind,

source§

fn default() -> BinaryHeap<T, K, N>

Returns the “default value” for a type. Read more
source§

impl<'a, T, K, const N: usize> IntoIterator for &'a BinaryHeap<T, K, N>where + K: Kind, + T: Ord,

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a BinaryHeap<T, K, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, K, const N: usize> RefUnwindSafe for BinaryHeap<T, K, N>where + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, K, const N: usize> Send for BinaryHeap<T, K, N>where + K: Send, + T: Send,

§

impl<T, K, const N: usize> Sync for BinaryHeap<T, K, N>where + K: Sync, + T: Sync,

§

impl<T, K, const N: usize> Unpin for BinaryHeap<T, K, N>where + K: Unpin, + T: Unpin,

§

impl<T, K, const N: usize> UnwindSafe for BinaryHeap<T, K, N>where + K: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.Deque.html b/docs/doc/arduboy_rust/heapless/struct.Deque.html new file mode 100644 index 0000000..b392315 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.Deque.html @@ -0,0 +1,90 @@ +Deque in arduboy_rust::heapless - Rust
pub struct Deque<T, const N: usize> { /* private fields */ }
Expand description

A fixed capacity double-ended queue.

+

Examples

+
use heapless::Deque;
+
+// A deque with a fixed capacity of 8 elements allocated on the stack
+let mut deque = Deque::<_, 8>::new();
+
+// You can use it as a good old FIFO queue.
+deque.push_back(1);
+deque.push_back(2);
+assert_eq!(deque.len(), 2);
+
+assert_eq!(deque.pop_front(), Some(1));
+assert_eq!(deque.pop_front(), Some(2));
+assert_eq!(deque.len(), 0);
+
+// Deque is double-ended, you can push and pop from the front and back.
+deque.push_back(1);
+deque.push_front(2);
+deque.push_back(3);
+deque.push_front(4);
+assert_eq!(deque.pop_front(), Some(4));
+assert_eq!(deque.pop_front(), Some(2));
+assert_eq!(deque.pop_front(), Some(1));
+assert_eq!(deque.pop_front(), Some(3));
+
+// You can iterate it, yielding all the elements front-to-back.
+for x in &deque {
+    println!("{}", x);
+}
+

Implementations§

source§

impl<T, const N: usize> Deque<T, N>

source

pub const fn new() -> Deque<T, N>

Constructs a new, empty deque with a fixed capacity of N

+
Examples
+
use heapless::Deque;
+
+// allocate the deque on the stack
+let mut x: Deque<u8, 16> = Deque::new();
+
+// allocate the deque in a static variable
+static mut X: Deque<u8, 16> = Deque::new();
+
source

pub const fn capacity(&self) -> usize

Returns the maximum number of elements the deque can hold.

+
source

pub const fn len(&self) -> usize

Returns the number of elements currently in the deque.

+
source

pub fn clear(&mut self)

Clears the deque, removing all values.

+
source

pub fn is_empty(&self) -> bool

Returns whether the deque is empty.

+
source

pub fn is_full(&self) -> bool

Returns whether the deque is full (i.e. if len() == capacity().

+
source

pub fn as_slices(&self) -> (&[T], &[T])

Returns a pair of slices which contain, in order, the contents of the Deque.

+
source

pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T])

Returns a pair of mutable slices which contain, in order, the contents of the Deque.

+
source

pub fn front(&self) -> Option<&T>

Provides a reference to the front element, or None if the Deque is empty.

+
source

pub fn front_mut(&mut self) -> Option<&mut T>

Provides a mutable reference to the front element, or None if the Deque is empty.

+
source

pub fn back(&self) -> Option<&T>

Provides a reference to the back element, or None if the Deque is empty.

+
source

pub fn back_mut(&mut self) -> Option<&mut T>

Provides a mutable reference to the back element, or None if the Deque is empty.

+
source

pub fn pop_front(&mut self) -> Option<T>

Removes the item from the front of the deque and returns it, or None if it’s empty

+
source

pub fn pop_back(&mut self) -> Option<T>

Removes the item from the back of the deque and returns it, or None if it’s empty

+
source

pub fn push_front(&mut self, item: T) -> Result<(), T>

Appends an item to the front of the deque

+

Returns back the item if the deque is full

+
source

pub fn push_back(&mut self, item: T) -> Result<(), T>

Appends an item to the back of the deque

+

Returns back the item if the deque is full

+
source

pub unsafe fn pop_front_unchecked(&mut self) -> T

Removes an item from the front of the deque and returns it, without checking that the deque +is not empty

+
Safety
+

It’s undefined behavior to call this on an empty deque

+
source

pub unsafe fn pop_back_unchecked(&mut self) -> T

Removes an item from the back of the deque and returns it, without checking that the deque +is not empty

+
Safety
+

It’s undefined behavior to call this on an empty deque

+
source

pub unsafe fn push_front_unchecked(&mut self, item: T)

Appends an item to the front of the deque

+
Safety
+

This assumes the deque is not full.

+
source

pub unsafe fn push_back_unchecked(&mut self, item: T)

Appends an item to the back of the deque

+
Safety
+

This assumes the deque is not full.

+
source

pub fn iter(&self) -> Iter<'_, T, N>

Returns an iterator over the deque.

+
source

pub fn iter_mut(&mut self) -> IterMut<'_, T, N>

Returns an iterator that allows modifying each value.

+

Trait Implementations§

source§

impl<T, const N: usize> Clone for Deque<T, N>where + T: Clone,

source§

fn clone(&self) -> Deque<T, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, const N: usize> Debug for Deque<T, N>where + T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for Deque<T, N>

source§

fn default() -> Deque<T, N>

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Drop for Deque<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a Deque<T, N>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a Deque<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a mut Deque<T, N>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a mut Deque<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> IntoIterator for Deque<T, N>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <Deque<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for Deque<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for Deque<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for Deque<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for Deque<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for Deque<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.HistoryBuffer.html b/docs/doc/arduboy_rust/heapless/struct.HistoryBuffer.html new file mode 100644 index 0000000..1e2bbf3 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.HistoryBuffer.html @@ -0,0 +1,1089 @@ +HistoryBuffer in arduboy_rust::heapless - Rust
pub struct HistoryBuffer<T, const N: usize> { /* private fields */ }
Expand description

A “history buffer”, similar to a write-only ring buffer of fixed length.

+

This buffer keeps a fixed number of elements. On write, the oldest element +is overwritten. Thus, the buffer is useful to keep a history of values with +some desired depth, and for example calculate a rolling average.

+

Examples

+
use heapless::HistoryBuffer;
+
+// Initialize a new buffer with 8 elements.
+let mut buf = HistoryBuffer::<_, 8>::new();
+
+// Starts with no data
+assert_eq!(buf.recent(), None);
+
+buf.write(3);
+buf.write(5);
+buf.extend(&[4, 4]);
+
+// The most recent written element is a four.
+assert_eq!(buf.recent(), Some(&4));
+
+// To access all elements in an unspecified order, use `as_slice()`.
+for el in buf.as_slice() { println!("{:?}", el); }
+
+// Now we can prepare an average of all values, which comes out to 4.
+let avg = buf.as_slice().iter().sum::<usize>() / buf.len();
+assert_eq!(avg, 4);
+

Implementations§

source§

impl<T, const N: usize> HistoryBuffer<T, N>

source

pub const fn new() -> HistoryBuffer<T, N>

Constructs a new history buffer.

+

The construction of a HistoryBuffer works in const contexts.

+
Examples
+
use heapless::HistoryBuffer;
+
+// Allocate a 16-element buffer on the stack
+let x: HistoryBuffer<u8, 16> = HistoryBuffer::new();
+assert_eq!(x.len(), 0);
+
source

pub fn clear(&mut self)

Clears the buffer, replacing every element with the default value of +type T.

+
source§

impl<T, const N: usize> HistoryBuffer<T, N>where + T: Copy + Clone,

source

pub fn new_with(t: T) -> HistoryBuffer<T, N>

Constructs a new history buffer, where every element is the given value.

+
Examples
+
use heapless::HistoryBuffer;
+
+// Allocate a 16-element buffer on the stack
+let mut x: HistoryBuffer<u8, 16> = HistoryBuffer::new_with(4);
+// All elements are four
+assert_eq!(x.as_slice(), [4; 16]);
+
source

pub fn clear_with(&mut self, t: T)

Clears the buffer, replacing every element with the given value.

+
source§

impl<T, const N: usize> HistoryBuffer<T, N>

source

pub fn len(&self) -> usize

Returns the current fill level of the buffer.

+
source

pub fn capacity(&self) -> usize

Returns the capacity of the buffer, which is the length of the +underlying backing array.

+
source

pub fn write(&mut self, t: T)

Writes an element to the buffer, overwriting the oldest value.

+
source

pub fn extend_from_slice(&mut self, other: &[T])where + T: Clone,

Clones and writes all elements in a slice to the buffer.

+

If the slice is longer than the buffer, only the last self.len() +elements will actually be stored.

+
source

pub fn recent(&self) -> Option<&T>

Returns a reference to the most recently written value.

+
Examples
+
use heapless::HistoryBuffer;
+
+let mut x: HistoryBuffer<u8, 16> = HistoryBuffer::new();
+x.write(4);
+x.write(10);
+assert_eq!(x.recent(), Some(&10));
+
source

pub fn as_slice(&self) -> &[T]

Returns the array slice backing the buffer, without keeping track +of the write position. Therefore, the element order is unspecified.

+
source

pub fn oldest_ordered<'a>(&'a self) -> OldestOrdered<'a, T, N>

Returns an iterator for iterating over the buffer from oldest to newest.

+
Examples
+
use heapless::HistoryBuffer;
+
+let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
+buffer.extend([0, 0, 0, 1, 2, 3, 4, 5, 6]);
+let expected = [1, 2, 3, 4, 5, 6];
+for (x, y) in buffer.oldest_ordered().zip(expected.iter()) {
+    assert_eq!(x, y)
+}
+
+

Methods from Deref<Target = [T]>§

1.23.0

pub fn is_ascii(&self) -> bool

Checks if all bytes in this slice are within the ASCII range.

+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this slice is_ascii, returns it as a slice of +ASCII characters, otherwise returns None.

+

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this slice of bytes into a slice of ASCII characters, +without checking whether they’re valid.

+
Safety
+

Every byte in the slice must be in 0..=127, or else this is UB.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool

Checks that two slices are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
1.60.0

pub fn escape_ascii(&self) -> EscapeAscii<'_>

Returns an iterator that produces an escaped version of this slice, +treating it as an ASCII string.

+
Examples
+

+let s = b"0\t\r\n'\"\\\x9d";
+let escaped = s.escape_ascii().to_string();
+assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
+

pub fn trim_ascii_start(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
+assert_eq!(b"  ".trim_ascii_start(), b"");
+assert_eq!(b"".trim_ascii_start(), b"");
+

pub fn trim_ascii_end(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with trailing ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
+assert_eq!(b"  ".trim_ascii_end(), b"");
+assert_eq!(b"".trim_ascii_end(), b"");
+

pub fn trim_ascii(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading and trailing ASCII whitespace bytes +removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
+assert_eq!(b"  ".trim_ascii(), b"");
+assert_eq!(b"".trim_ascii(), b"");
+

pub fn as_str(&self) -> &str

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a UTF-8 str.

+

pub fn as_bytes(&self) -> &[u8]

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a slice of u8 bytes.

+

pub fn flatten(&self) -> &[T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &[[T; N]], and flattens it to a &[T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
+
+assert_eq!(
+    [[1, 2, 3], [4, 5, 6]].flatten(),
+    [[1, 2], [3, 4], [5, 6]].flatten(),
+);
+
+let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
+assert!(slice_of_empty_arrays.flatten().is_empty());
+
+let empty_slice_of_arrays: &[[u32; 10]] = &[];
+assert!(empty_slice_of_arrays.flatten().is_empty());
+
1.0.0

pub fn len(&self) -> usize

Returns the number of elements in the slice.

+
Examples
+
let a = [1, 2, 3];
+assert_eq!(a.len(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if the slice has a length of 0.

+
Examples
+
let a = [1, 2, 3];
+assert!(!a.is_empty());
+
1.0.0

pub fn first(&self) -> Option<&T>

Returns the first element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&10), v.first());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.first());
+
1.5.0

pub fn split_first(&self) -> Option<(&T, &[T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first() {
+    assert_eq!(first, &0);
+    assert_eq!(elements, &[1, 2]);
+}
+
1.5.0

pub fn split_last(&self) -> Option<(&T, &[T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last() {
+    assert_eq!(last, &2);
+    assert_eq!(elements, &[0, 1]);
+}
+
1.0.0

pub fn last(&self) -> Option<&T>

Returns the last element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&30), v.last());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.last());
+

pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice, or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.first_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.first_chunk::<0>());
+

pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk::<2>() {
+    assert_eq!(first, &[0, 1]);
+    assert_eq!(elements, &[2]);
+}
+

pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk::<2>() {
+    assert_eq!(last, &[1, 2]);
+    assert_eq!(elements, &[0]);
+}
+

pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last element of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.last_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.last_chunk::<0>());
+
1.0.0

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a reference to an element or subslice depending on the type of +index.

+
    +
  • If given a position, returns a reference to the element at that +position or None if out of bounds.
  • +
  • If given a range, returns the subslice corresponding to that range, +or None if out of bounds.
  • +
+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&40), v.get(1));
+assert_eq!(Some(&[10, 40][..]), v.get(0..2));
+assert_eq!(None, v.get(3));
+assert_eq!(None, v.get(0..4));
+
1.0.0

pub unsafe fn get_unchecked<I>( + &self, + index: I +) -> &<I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a reference to an element or subslice, without doing bounds +checking.

+

For a safe alternative see get.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &[1, 2, 4];
+
+unsafe {
+    assert_eq!(x.get_unchecked(1), &2);
+}
+
1.0.0

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

The caller must also ensure that the memory the pointer (non-transitively) points to +is never written to (except inside an UnsafeCell) using this pointer or any pointer +derived 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 +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &[1, 2, 4];
+let x_ptr = x.as_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
+    }
+}
+
1.48.0

pub fn as_ptr_range(&self) -> Range<*const T>

Returns the two raw pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_ptr for warnings on using these pointers. The end pointer +requires extra caution, as it does not point to a valid element in the +slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+

It can also be useful to check if a pointer to an element refers to an +element of this slice:

+ +
let a = [1, 2, 3];
+let x = &a[1] as *const _;
+let y = &5 as *const _;
+
+assert!(a.as_ptr_range().contains(&x));
+assert!(!a.as_ptr_range().contains(&y));
+
1.0.0

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the slice.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &[1, 2, 4];
+let mut iterator = x.iter();
+
+assert_eq!(iterator.next(), Some(&1));
+assert_eq!(iterator.next(), Some(&2));
+assert_eq!(iterator.next(), Some(&4));
+assert_eq!(iterator.next(), None);
+
1.0.0

pub fn windows(&self, size: usize) -> Windows<'_, T>

Returns an iterator over all contiguous windows of length +size. The windows overlap. If the slice is shorter than +size, the iterator returns no values.

+
Panics
+

Panics if size is 0.

+
Examples
+
let slice = ['r', 'u', 's', 't'];
+let mut iter = slice.windows(2);
+assert_eq!(iter.next().unwrap(), &['r', 'u']);
+assert_eq!(iter.next().unwrap(), &['u', 's']);
+assert_eq!(iter.next().unwrap(), &['s', 't']);
+assert!(iter.next().is_none());
+

If the slice is shorter than size:

+ +
let slice = ['f', 'o', 'o'];
+let mut iter = slice.windows(4);
+assert!(iter.next().is_none());
+

There’s no windows_mut, as that existing would let safe code violate the +“only one &mut at a time to the same thing” rule. However, you can sometimes +use Cell::as_slice_of_cells in +conjunction with windows to accomplish something similar:

+ +
use std::cell::Cell;
+
+let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
+let slice = &mut array[..];
+let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
+for w in slice_of_cells.windows(3) {
+    Cell::swap(&w[0], &w[2]);
+}
+assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
+
1.0.0

pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and rchunks for the same iterator but starting at the end of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert_eq!(iter.next().unwrap(), &['m']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of chunks.

+

See chunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and rchunks_exact for the same iterator but starting at the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &[[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &[[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
+

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (chunks, remainder) = slice.as_chunks();
+assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
+assert_eq!(remainder, &['m']);
+

If you expect the slice to be an exact multiple, you can combine +let-else with an empty slice pattern:

+ +
#![feature(slice_as_chunks)]
+let slice = ['R', 'u', 's', 't'];
+let (chunks, []) = slice.as_chunks::<2>() else {
+    panic!("slice didn't have even length")
+};
+assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
+

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (remainder, chunks) = slice.as_rchunks();
+assert_eq!(remainder, &['l']);
+assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
+

pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are array references and do not overlap. If N does not divide the +length of the slice, then the last up to N-1 elements will be omitted and can be +retrieved from the remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.array_chunks();
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>

🔬This is a nightly-only experimental API. (array_windows)

Returns an iterator over overlapping windows of N elements of a slice, +starting 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
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_windows)]
+let slice = [0, 1, 2, 3];
+let mut iter = slice.array_windows();
+assert_eq!(iter.next().unwrap(), &[0, 1]);
+assert_eq!(iter.next().unwrap(), &[1, 2]);
+assert_eq!(iter.next().unwrap(), &[2, 3]);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and chunks for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert_eq!(iter.next().unwrap(), &['l']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +end of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of rchunks.

+

See rchunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and chunks_exact for the same iterator but starting at the beginning of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['l']);
+

pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping runs +of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&[3, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+
1.0.0

pub fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let v = [1, 2, 3, 4, 5, 6];
+
+{
+   let (left, right) = v.split_at(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let v = [1, 2, 3, 4, 5, 6];
+
+unsafe {
+   let (left, right) = v.split_at_unchecked(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.split_array_ref::<0>();
+   assert_eq!(left, &[]);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<2>();
+    assert_eq!(left, &[1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<6>();
+    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index from +the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index len - N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.rsplit_array_ref::<0>();
+   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+   assert_eq!(right, &[]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<2>();
+    assert_eq!(left, [1, 2, 3, 4]);
+    assert_eq!(right, &[5, 6]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<6>();
+    assert_eq!(left, []);
+    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
+}
+
1.0.0

pub fn split<F>(&self, pred: F) -> Split<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is not contained in the subslices.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the first element is matched, an empty slice will be the first item +returned by the iterator. Similarly, if the last element in the slice +is matched, an empty slice will be the last item returned by the +iterator:

+ +
let slice = [10, 40, 33];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert!(iter.next().is_none());
+

If two matched elements are directly adjacent, an empty slice will be +present between them:

+ +
let slice = [10, 6, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+
1.51.0

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is contained in the end of the previous +subslice as a terminator.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the last element of the slice is matched, +that element will be considered the terminator of the preceding slice. +That slice will be the last item returned by the iterator.

+ +
let slice = [3, 10, 40, 33];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[3]);
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert!(iter.next().is_none());
+
1.27.0

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, starting at the end of the slice and working backwards. +The matched element is not contained in the subslices.

+
Examples
+
let slice = [11, 22, 33, 0, 44, 55];
+let mut iter = slice.rsplit(|num| *num == 0);
+
+assert_eq!(iter.next().unwrap(), &[44, 55]);
+assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
+assert_eq!(iter.next(), None);
+

As with split(), if the first or last element is matched, an empty +slice will be the first (or last) item returned by the iterator.

+ +
let v = &[0, 1, 1, 2, 3, 5, 8];
+let mut it = v.rsplit(|n| *n % 2 == 0);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next().unwrap(), &[3, 5]);
+assert_eq!(it.next().unwrap(), &[1, 1]);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next(), None);
+
1.0.0

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once by numbers divisible by 3 (i.e., [10, 40], +[20, 60, 50]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once, starting from the end, by numbers divisible +by 3 (i.e., [50], [10, 40, 30, 20]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.rsplitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn contains(&self, x: &T) -> boolwhere + T: PartialEq<T>,

Returns true if the slice contains an element with the given value.

+

This operation is O(n).

+

Note that if you have a sorted slice, binary_search may be faster.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.contains(&30));
+assert!(!v.contains(&50));
+

If you do not have a &T, but some other value that you can compare +with one (for example, String implements PartialEq<str>), you can +use iter().any:

+ +
let v = [String::from("hello"), String::from("world")]; // slice of `String`
+assert!(v.iter().any(|e| e == "hello")); // search with `&str`
+assert!(!v.iter().any(|e| e == "hi"));
+
1.0.0

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.starts_with(&[10]));
+assert!(v.starts_with(&[10, 40]));
+assert!(!v.starts_with(&[50]));
+assert!(!v.starts_with(&[10, 50]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.starts_with(&[]));
+let v: &[u8] = &[];
+assert!(v.starts_with(&[]));
+
1.0.0

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.ends_with(&[30]));
+assert!(v.ends_with(&[40, 30]));
+assert!(!v.ends_with(&[50]));
+assert!(!v.ends_with(&[50, 30]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.ends_with(&[]));
+let v: &[u8] = &[];
+assert!(v.ends_with(&[]));
+
1.51.0

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the prefix removed.

+

If the slice starts with prefix, returns the subslice after the prefix, wrapped in Some. +If prefix is empty, simply returns the original slice.

+

If the slice does not start with prefix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
+assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
+assert_eq!(v.strip_prefix(&[50]), None);
+assert_eq!(v.strip_prefix(&[10, 50]), None);
+
+let prefix : &str = "he";
+assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
+           Some(b"llo".as_ref()));
+
1.51.0

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the suffix removed.

+

If the slice ends with suffix, returns the subslice before the suffix, wrapped in Some. +If suffix is empty, simply returns the original slice.

+

If the slice does not end with suffix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
+assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
+assert_eq!(v.strip_suffix(&[50]), None);
+assert_eq!(v.strip_suffix(&[50, 30]), None);
+

Binary searches this slice for a given element. +If the slice is not sorted, the returned result is unspecified and +meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search_by, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+assert_eq!(s.binary_search(&13),  Ok(9));
+assert_eq!(s.binary_search(&4),   Err(7));
+assert_eq!(s.binary_search(&100), Err(13));
+let r = s.binary_search(&1);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+

If you want to find that whole range of matching items, rather than +an 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];
+
+let low = s.partition_point(|x| x < &1);
+assert_eq!(low, 1);
+let high = s.partition_point(|x| x <= &1);
+assert_eq!(high, 5);
+let r = s.binary_search(&1);
+assert!((low..high).contains(&r.unwrap()));
+
+assert!(s[..low].iter().all(|&x| x < 1));
+assert!(s[low..high].iter().all(|&x| x == 1));
+assert!(s[high..].iter().all(|&x| x > 1));
+
+// For something not found, the "range" of equal items is empty
+assert_eq!(s.partition_point(|x| x < &11), 9);
+assert_eq!(s.partition_point(|x| x <= &11), 9);
+assert_eq!(s.binary_search(&11), Err(9));
+

If you want to insert an item to a sorted vector, while maintaining +sort order, consider using partition_point:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+
1.0.0

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where + F: FnMut(&'a T) -> Ordering,

Binary searches this slice with a comparator function.

+

The comparator function should return an order code that indicates +whether its argument is Less, Equal or Greater the desired +target. +If the slice is not sorted or if the comparator function does not +implement an order consistent with the sort order of the underlying +slice, the returned result is unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+let seek = 13;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
+let seek = 4;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
+let seek = 100;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
+let seek = 1;
+let r = s.binary_search_by(|probe| probe.cmp(&seek));
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.10.0

pub fn binary_search_by_key<'a, B, F>( + &'a self, + b: &B, + f: F +) -> Result<usize, usize>where + F: FnMut(&'a T) -> B, + B: Ord,

Binary searches this slice with a key extraction function.

+

Assumes that the slice is sorted by the key, for instance with +sort_by_key using the same key extraction function. +If the slice is not sorted by the key, the returned result is +unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by, and partition_point.

+
Examples
+

Looks up a series of four elements in a slice of pairs sorted by +their second elements. The first is found, with a uniquely +determined position; the second and third are not found; the +fourth could match any position in [1, 4].

+ +
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
+         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
+         (1, 21), (2, 34), (4, 55)];
+
+assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
+assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
+assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
+let r = s.binary_search_by_key(&1, |&(a, b)| b);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.30.0

pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])

Transmute the slice to a slice of another type, ensuring alignment of the types is +maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])where + Simd<T, LANES>: AsRef<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

+

This is a safe wrapper around [slice::align_to], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+
Examples
+
#![feature(portable_simd)]
+use core::simd::SimdFloat;
+
+let short = &[1, 2, 3];
+let (prefix, middle, suffix) = short.as_simd::<4>();
+assert_eq!(middle, []); // Not enough elements for anything in the middle
+
+// They might be split in any possible way between prefix and suffix
+let it = prefix.iter().chain(suffix).copied();
+assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
+
+fn basic_simd_sum(x: &[f32]) -> f32 {
+    use std::ops::Add;
+    use std::simd::f32x4;
+    let (prefix, middle, suffix) = x.as_simd();
+    let sums = f32x4::from_array([
+        prefix.iter().copied().sum(),
+        0.0,
+        0.0,
+        suffix.iter().copied().sum(),
+    ]);
+    let sums = middle.iter().copied().fold(sums, f32x4::add);
+    sums.reduce_sum()
+}
+
+let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
+assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
+

pub fn is_sorted(&self) -> boolwhere + T: PartialOrd<T>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted.

+

That is, for each element a and its following element b, a <= b must hold. If the +slice yields exactly zero or one element, true is returned.

+

Note that if Self::Item is only PartialOrd, but not Ord, the above definition +implies that this function returns false if any two consecutive items are not +comparable.

+
Examples
+
#![feature(is_sorted)]
+let empty: [i32; 0] = [];
+
+assert!([1, 2, 2, 9].is_sorted());
+assert!(![1, 3, 2, 4].is_sorted());
+assert!([0].is_sorted());
+assert!(empty.is_sorted());
+assert!(![0.0, 1.0, f32::NAN].is_sorted());
+

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> boolwhere + F: FnMut(&'a T, &'a T) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given comparator function.

+

Instead of using PartialOrd::partial_cmp, this function uses the given compare +function to determine the ordering of two elements. Apart from that, it’s equivalent to +is_sorted; see its documentation for more information.

+

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> boolwhere + F: FnMut(&'a T) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given key extraction function.

+

Instead of comparing the slice’s elements directly, this function compares the keys of the +elements, as determined by f. Apart from that, it’s equivalent to is_sorted; see its +documentation for more information.

+
Examples
+
#![feature(is_sorted)]
+
+assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
+assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
+
1.52.0

pub fn partition_point<P>(&self, pred: P) -> usizewhere + P: FnMut(&T) -> bool,

Returns the index of the partition point according to the given predicate +(the index of the first element of the second partition).

+

The slice is assumed to be partitioned according to the given predicate. +This means that all elements for which the predicate returns true are at the start of the slice +and all elements for which the predicate returns false are at the end. +For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 +(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, +as this method performs a kind of binary search.

+

See also binary_search, binary_search_by, and binary_search_by_key.

+
Examples
+
let v = [1, 2, 3, 3, 5, 6, 7];
+let i = v.partition_point(|&x| x < 5);
+
+assert_eq!(i, 4);
+assert!(v[..i].iter().all(|&x| x < 5));
+assert!(v[i..].iter().all(|&x| !(x < 5)));
+

If all elements of the slice match the predicate, including if the slice +is empty, then the length of the slice will be returned:

+ +
let a = [2, 4, 8];
+assert_eq!(a.partition_point(|x| x < &100), a.len());
+let a: [i32; 0] = [];
+assert_eq!(a.partition_point(|x| x < &100), 0);
+

If you want to insert an item to a sorted vector, while maintaining +sort order:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+

Trait Implementations§

source§

impl<T, const N: usize> AsRef<[T]> for HistoryBuffer<T, N>

source§

fn as_ref(&self) -> &[T]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> Debug for HistoryBuffer<T, N>where + T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for HistoryBuffer<T, N>

source§

fn default() -> HistoryBuffer<T, N>

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Deref for HistoryBuffer<T, N>

§

type Target = [T]

The resulting type after dereferencing.
source§

fn deref(&self) -> &[T]

Dereferences the value.
source§

impl<T, const N: usize> Drop for HistoryBuffer<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> Extend<&'a T> for HistoryBuffer<T, N>where + T: 'a + Clone,

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> Extend<T> for HistoryBuffer<T, N>

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for HistoryBuffer<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for HistoryBuffer<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for HistoryBuffer<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for HistoryBuffer<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for HistoryBuffer<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.IndexMap.html b/docs/doc/arduboy_rust/heapless/struct.IndexMap.html new file mode 100644 index 0000000..9264902 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.IndexMap.html @@ -0,0 +1,306 @@ +IndexMap in arduboy_rust::heapless - Rust
pub struct IndexMap<K, V, S, const N: usize> { /* private fields */ }
Expand description

Fixed capacity IndexMap

+

Note that you cannot use IndexMap directly, since it is generic around the hashing algorithm +in use. Pick a concrete instantiation like FnvIndexMap instead +or create your own.

+

Note that the capacity of the IndexMap must be a power of 2.

+

Examples

+

Since IndexMap cannot be used directly, we’re using its FnvIndexMap instantiation +for this example.

+ +
use heapless::FnvIndexMap;
+
+// A hash map with a capacity of 16 key-value pairs allocated on the stack
+let mut book_reviews = FnvIndexMap::<_, _, 16>::new();
+
+// review some books.
+book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.").unwrap();
+book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.").unwrap();
+book_reviews.insert("Pride and Prejudice",               "Very enjoyable.").unwrap();
+book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.").unwrap();
+
+// check for a specific one.
+if !book_reviews.contains_key("Les Misérables") {
+    println!("We've got {} reviews, but Les Misérables ain't one.",
+             book_reviews.len());
+}
+
+// oops, this review has a lot of spelling mistakes, let's delete it.
+book_reviews.remove("The Adventures of Sherlock Holmes");
+
+// look up the values associated with some keys.
+let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
+for book in &to_find {
+    match book_reviews.get(book) {
+        Some(review) => println!("{}: {}", book, review),
+        None => println!("{} is unreviewed.", book)
+    }
+}
+
+// iterate over everything.
+for (book, review) in &book_reviews {
+    println!("{}: \"{}\"", book, review);
+}
+

Implementations§

source§

impl<K, V, S, const N: usize> IndexMap<K, V, BuildHasherDefault<S>, N>

source

pub const fn new() -> IndexMap<K, V, BuildHasherDefault<S>, N>

Creates an empty IndexMap.

+
source§

impl<K, V, S, const N: usize> IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold

+
source

pub fn keys(&self) -> impl Iterator<Item = &K>

Return an iterator over the keys of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for key in map.keys() {
+    println!("{}", key);
+}
+
source

pub fn values(&self) -> impl Iterator<Item = &V>

Return an iterator over the values of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V>

Return an iterator over mutable references to the the values of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values_mut() {
+    *val += 10;
+}
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn iter(&self) -> Iter<'_, K, V>

Return an iterator over the key-value pairs of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (key, val) in map.iter() {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

Return an iterator over the key-value pairs of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (_, val) in map.iter_mut() {
+    *val = 2;
+}
+
+for (key, val) in &map {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn first(&self) -> Option<(&K, &V)>

Get the first key-value pair

+

Computes in O(1) time

+
source

pub fn first_mut(&mut self) -> Option<(&K, &mut V)>

Get the first key-value pair, with mutable access to the value

+

Computes in O(1) time

+
source

pub fn last(&self) -> Option<(&K, &V)>

Get the last key-value pair

+

Computes in O(1) time

+
source

pub fn last_mut(&mut self) -> Option<(&K, &mut V)>

Get the last key-value pair, with mutable access to the value

+

Computes in O(1) time

+
source

pub fn entry(&mut self, key: K) -> Entry<'_, K, V, N>

Returns an entry for the corresponding key

+ +
use heapless::FnvIndexMap;
+use heapless::Entry;
+let mut map = FnvIndexMap::<_, _, 16>::new();
+if let Entry::Vacant(v) = map.entry("a") {
+    v.insert(1).unwrap();
+}
+if let Entry::Occupied(mut o) = map.entry("a") {
+    println!("found {}", *o.get()); // Prints 1
+    o.insert(2);
+}
+// Prints 2
+println!("val: {}", *map.get("a").unwrap());
+
source

pub fn len(&self) -> usize

Return the number of key-value pairs in the map.

+

Computes in O(1) time.

+ +
use heapless::FnvIndexMap;
+
+let mut a = FnvIndexMap::<_, _, 16>::new();
+assert_eq!(a.len(), 0);
+a.insert(1, "a").unwrap();
+assert_eq!(a.len(), 1);
+
source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

+

Computes in O(1) time.

+ +
use heapless::FnvIndexMap;
+
+let mut a = FnvIndexMap::<_, _, 16>::new();
+assert!(a.is_empty());
+a.insert(1, "a");
+assert!(!a.is_empty());
+
source

pub fn clear(&mut self)

Remove all key-value pairs in the map, while preserving its capacity.

+

Computes in O(n) time.

+ +
use heapless::FnvIndexMap;
+
+let mut a = FnvIndexMap::<_, _, 16>::new();
+a.insert(1, "a");
+a.clear();
+assert!(a.is_empty());
+
source

pub fn get<Q>(&self, key: &Q) -> Option<&V>where + K: Borrow<Q>, + Q: Hash + Eq + ?Sized,

Returns a reference to the value corresponding to the key.

+

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed +form must match those for the key type.

+

Computes in O(1) time (average).

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.get(&1), Some(&"a"));
+assert_eq!(map.get(&2), None);
+
source

pub fn contains_key<Q>(&self, key: &Q) -> boolwhere + K: Borrow<Q>, + Q: Eq + Hash + ?Sized,

Returns true if the map contains a value for the specified key.

+

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed +form must match those for the key type.

+

Computes in O(1) time (average).

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.contains_key(&1), true);
+assert_eq!(map.contains_key(&2), false);
+
source

pub fn get_mut<Q, 'v>(&'v mut self, key: &Q) -> Option<&'v mut V>where + K: Borrow<Q>, + Q: Hash + Eq + ?Sized,

Returns a mutable reference to the value corresponding to the key.

+

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed +form must match those for the key type.

+

Computes in O(1) time (average).

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+map.insert(1, "a").unwrap();
+if let Some(x) = map.get_mut(&1) {
+    *x = "b";
+}
+assert_eq!(map[&1], "b");
+
source

pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)>

Inserts a key-value pair into the map.

+

If an equivalent key already exists in the map: the key remains and retains in its place in +the order, its corresponding value is updated with value and the older value is returned +inside Some(_).

+

If no equivalent key existed in the map: the new key-value pair is inserted, last in order, +and None is returned.

+

Computes in O(1) time (average).

+

See also entry if you you want to insert or modify or if you need to get the index of the +corresponding key-value pair.

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+assert_eq!(map.insert(37, "a"), Ok(None));
+assert_eq!(map.is_empty(), false);
+
+map.insert(37, "b");
+assert_eq!(map.insert(37, "c"), Ok(Some("b")));
+assert_eq!(map[&37], "c");
+
source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: Hash + Eq + ?Sized,

Same as swap_remove

+

Computes in O(1) time (average).

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.remove(&1), Some("a"));
+assert_eq!(map.remove(&1), None);
+
source

pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: Hash + Eq + ?Sized,

Remove the key-value pair equivalent to key and return its value.

+

Like Vec::swap_remove, the pair is removed by swapping it with the last element of the map +and popping it off. This perturbs the postion of what used to be the last element!

+

Return None if key is not in map.

+

Computes in O(1) time (average).

+

Trait Implementations§

source§

impl<K, V, S, const N: usize> Clone for IndexMap<K, V, S, N>where + K: Eq + Hash + Clone, + V: Clone, + S: Clone,

source§

fn clone(&self) -> IndexMap<K, V, S, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K, V, S, const N: usize> Debug for IndexMap<K, V, S, N>where + K: Eq + Hash + Debug, + V: Debug, + S: BuildHasher,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<K, V, S, const N: usize> Default for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher + Default,

source§

fn default() -> IndexMap<K, V, S, N>

Returns the “default value” for a type. Read more
source§

impl<'a, K, V, S, const N: usize> Extend<(&'a K, &'a V)> for IndexMap<K, V, S, N>where + K: Eq + Hash + Copy, + V: Copy, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = (&'a K, &'a V)>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<K, V, S, const N: usize> Extend<(K, V)> for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = (K, V)>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<K, V, S, const N: usize> FromIterator<(K, V)> for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher + Default,

source§

fn from_iter<I>(iterable: I) -> IndexMap<K, V, S, N>where + I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl<'a, K, Q, V, S, const N: usize> Index<&'a Q> for IndexMap<K, V, S, N>where + K: Eq + Hash + Borrow<Q>, + Q: Eq + Hash + ?Sized, + S: BuildHasher,

§

type Output = V

The returned type after indexing.
source§

fn index(&self, key: &Q) -> &V

Performs the indexing (container[index]) operation. Read more
source§

impl<'a, K, Q, V, S, const N: usize> IndexMut<&'a Q> for IndexMap<K, V, S, N>where + K: Eq + Hash + Borrow<Q>, + Q: Eq + Hash + ?Sized, + S: BuildHasher,

source§

fn index_mut(&mut self, key: &Q) -> &mut V

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, K, V, S, const N: usize> IntoIterator for &'a IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a IndexMap<K, V, S, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, K, V, S, const N: usize> IntoIterator for &'a mut IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

§

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a mut IndexMap<K, V, S, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, S, const N: usize> IntoIterator for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

§

type Item = (K, V)

The type of the elements being iterated over.
§

type IntoIter = IntoIter<K, V, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <IndexMap<K, V, S, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, S, S2, const N: usize, const N2: usize> PartialEq<IndexMap<K, V, S2, N2>> for IndexMap<K, V, S, N>where + K: Eq + Hash, + V: Eq, + S: BuildHasher, + S2: BuildHasher,

source§

fn eq(&self, other: &IndexMap<K, V, S2, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<K, V, S, const N: usize> Eq for IndexMap<K, V, S, N>where + K: Eq + Hash, + V: Eq, + S: BuildHasher,

Auto Trait Implementations§

§

impl<K, V, S, const N: usize> RefUnwindSafe for IndexMap<K, V, S, N>where + K: RefUnwindSafe, + S: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<K, V, S, const N: usize> Send for IndexMap<K, V, S, N>where + K: Send, + S: Send, + V: Send,

§

impl<K, V, S, const N: usize> Sync for IndexMap<K, V, S, N>where + K: Sync, + S: Sync, + V: Sync,

§

impl<K, V, S, const N: usize> Unpin for IndexMap<K, V, S, N>where + K: Unpin, + S: Unpin, + V: Unpin,

§

impl<K, V, S, const N: usize> UnwindSafe for IndexMap<K, V, S, N>where + K: UnwindSafe, + S: UnwindSafe, + V: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.IndexSet.html b/docs/doc/arduboy_rust/heapless/struct.IndexSet.html new file mode 100644 index 0000000..6b89699 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.IndexSet.html @@ -0,0 +1,296 @@ +IndexSet in arduboy_rust::heapless - Rust
pub struct IndexSet<T, S, const N: usize> { /* private fields */ }
Expand description

Fixed capacity IndexSet.

+

Note that you cannot use IndexSet directly, since it is generic around the hashing algorithm +in use. Pick a concrete instantiation like FnvIndexSet instead +or create your own.

+

Note that the capacity of the IndexSet must be a power of 2.

+

Examples

+

Since IndexSet cannot be used directly, we’re using its FnvIndexSet instantiation +for this example.

+ +
use heapless::FnvIndexSet;
+
+// A hash set with a capacity of 16 elements allocated on the stack
+let mut books = FnvIndexSet::<_, 16>::new();
+
+// Add some books.
+books.insert("A Dance With Dragons").unwrap();
+books.insert("To Kill a Mockingbird").unwrap();
+books.insert("The Odyssey").unwrap();
+books.insert("The Great Gatsby").unwrap();
+
+// Check for a specific one.
+if !books.contains("The Winds of Winter") {
+    println!("We have {} books, but The Winds of Winter ain't one.",
+             books.len());
+}
+
+// Remove a book.
+books.remove("The Odyssey");
+
+// Iterate over everything.
+for book in &books {
+    println!("{}", book);
+}
+

Implementations§

source§

impl<T, S, const N: usize> IndexSet<T, BuildHasherDefault<S>, N>

source

pub const fn new() -> IndexSet<T, BuildHasherDefault<S>, N>

Creates an empty IndexSet

+
source§

impl<T, S, const N: usize> IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher,

source

pub fn capacity(&self) -> usize

Returns the number of elements the set can hold

+
Examples
+
use heapless::FnvIndexSet;
+
+let set = FnvIndexSet::<i32, 16>::new();
+assert_eq!(set.capacity(), 16);
+
source

pub fn iter(&self) -> Iter<'_, T>

Return an iterator over the values of the set, in their order

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut set = FnvIndexSet::<_, 16>::new();
+set.insert("a").unwrap();
+set.insert("b").unwrap();
+
+// Will print in an arbitrary order.
+for x in set.iter() {
+    println!("{}", x);
+}
+
source

pub fn first(&self) -> Option<&T>

Get the first value

+

Computes in O(1) time

+
source

pub fn last(&self) -> Option<&T>

Get the last value

+

Computes in O(1) time

+
source

pub fn difference<S2, const N2: usize, 'a>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> Difference<'a, T, S2, N2>where + S2: BuildHasher,

Visits the values representing the difference, i.e. the values that are in self but not in +other.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Can be seen as `a - b`.
+for x in a.difference(&b) {
+    println!("{}", x); // Print 1
+}
+
+let diff: FnvIndexSet<_, 16> = a.difference(&b).collect();
+assert_eq!(diff, [1].iter().collect::<FnvIndexSet<_, 16>>());
+
+// Note that difference is not symmetric,
+// and `b - a` means something else:
+let diff: FnvIndexSet<_, 16> = b.difference(&a).collect();
+assert_eq!(diff, [4].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn symmetric_difference<S2, const N2: usize, 'a>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> impl Iterator<Item = &'a T>where + S2: BuildHasher,

Visits the values representing the symmetric difference, i.e. the values that are in self +or in other but not in both.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Print 1, 4 in that order order.
+for x in a.symmetric_difference(&b) {
+    println!("{}", x);
+}
+
+let diff1: FnvIndexSet<_, 16> = a.symmetric_difference(&b).collect();
+let diff2: FnvIndexSet<_, 16> = b.symmetric_difference(&a).collect();
+
+assert_eq!(diff1, diff2);
+assert_eq!(diff1, [1, 4].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn intersection<S2, const N2: usize, 'a>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> Intersection<'a, T, S2, N2>where + S2: BuildHasher,

Visits the values representing the intersection, i.e. the values that are both in self and +other.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Print 2, 3 in that order.
+for x in a.intersection(&b) {
+    println!("{}", x);
+}
+
+let intersection: FnvIndexSet<_, 16> = a.intersection(&b).collect();
+assert_eq!(intersection, [2, 3].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn union<S2, const N2: usize, 'a>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> impl Iterator<Item = &'a T>where + S2: BuildHasher,

Visits the values representing the union, i.e. all the values in self or other, without +duplicates.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Print 1, 2, 3, 4 in that order.
+for x in a.union(&b) {
+    println!("{}", x);
+}
+
+let union: FnvIndexSet<_, 16> = a.union(&b).collect();
+assert_eq!(union, [1, 2, 3, 4].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn len(&self) -> usize

Returns the number of elements in the set.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+assert_eq!(v.len(), 0);
+v.insert(1).unwrap();
+assert_eq!(v.len(), 1);
+
source

pub fn is_empty(&self) -> bool

Returns true if the set contains no elements.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+assert!(v.is_empty());
+v.insert(1).unwrap();
+assert!(!v.is_empty());
+
source

pub fn clear(&mut self)

Clears the set, removing all values.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+v.insert(1).unwrap();
+v.clear();
+assert!(v.is_empty());
+
source

pub fn contains<Q>(&self, value: &Q) -> boolwhere + T: Borrow<Q>, + Q: Eq + Hash + ?Sized,

Returns true if the set contains a value.

+

The value may be any borrowed form of the set’s value type, but Hash and Eq on the +borrowed form must match those for the value type.

+
Examples
+
use heapless::FnvIndexSet;
+
+let set: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+assert_eq!(set.contains(&1), true);
+assert_eq!(set.contains(&4), false);
+
source

pub fn is_disjoint<S2, const N2: usize>( + &self, + other: &IndexSet<T, S2, N2> +) -> boolwhere + S2: BuildHasher,

Returns true if self has no elements in common with other. This is equivalent to +checking for an empty intersection.

+
Examples
+
use heapless::FnvIndexSet;
+
+let a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(a.is_disjoint(&b), true);
+b.insert(4).unwrap();
+assert_eq!(a.is_disjoint(&b), true);
+b.insert(1).unwrap();
+assert_eq!(a.is_disjoint(&b), false);
+
source

pub fn is_subset<S2, const N2: usize>( + &self, + other: &IndexSet<T, S2, N2> +) -> boolwhere + S2: BuildHasher,

Returns true if the set is a subset of another, i.e. other contains at least all the +values in self.

+
Examples
+
use heapless::FnvIndexSet;
+
+let sup: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut set = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(set.is_subset(&sup), true);
+set.insert(2).unwrap();
+assert_eq!(set.is_subset(&sup), true);
+set.insert(4).unwrap();
+assert_eq!(set.is_subset(&sup), false);
+
source

pub fn is_superset<S2, const N2: usize>( + &self, + other: &IndexSet<T, S2, N2> +) -> boolwhere + S2: BuildHasher,

Examples
+
use heapless::FnvIndexSet;
+
+let sub: FnvIndexSet<_, 16> = [1, 2].iter().cloned().collect();
+let mut set = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(set.is_superset(&sub), false);
+
+set.insert(0).unwrap();
+set.insert(1).unwrap();
+assert_eq!(set.is_superset(&sub), false);
+
+set.insert(2).unwrap();
+assert_eq!(set.is_superset(&sub), true);
+
source

pub fn insert(&mut self, value: T) -> Result<bool, T>

Adds a value to the set.

+

If the set did not have this value present, true is returned.

+

If the set did have this value present, false is returned.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut set = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(set.insert(2).unwrap(), true);
+assert_eq!(set.insert(2).unwrap(), false);
+assert_eq!(set.len(), 1);
+
source

pub fn remove<Q>(&mut self, value: &Q) -> boolwhere + T: Borrow<Q>, + Q: Eq + Hash + ?Sized,

Removes a value from the set. Returns true if the value was present in the set.

+

The value may be any borrowed form of the set’s value type, but Hash and Eq on the +borrowed form must match those for the value type.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut set = FnvIndexSet::<_, 16>::new();
+
+set.insert(2).unwrap();
+assert_eq!(set.remove(&2), true);
+assert_eq!(set.remove(&2), false);
+

Trait Implementations§

source§

impl<T, S, const N: usize> Clone for IndexSet<T, S, N>where + T: Eq + Hash + Clone, + S: Clone,

source§

fn clone(&self) -> IndexSet<T, S, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, S, const N: usize> Debug for IndexSet<T, S, N>where + T: Eq + Hash + Debug, + S: BuildHasher,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, S, const N: usize> Default for IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher + Default,

source§

fn default() -> IndexSet<T, S, N>

Returns the “default value” for a type. Read more
source§

impl<'a, T, S, const N: usize> Extend<&'a T> for IndexSet<T, S, N>where + T: 'a + Eq + Hash + Copy, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, S, const N: usize> Extend<T> for IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, S, const N: usize> FromIterator<T> for IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher + Default,

source§

fn from_iter<I>(iter: I) -> IndexSet<T, S, N>where + I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
source§

impl<'a, T, S, const N: usize> IntoIterator for &'a IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher,

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a IndexSet<T, S, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, S1, S2, const N1: usize, const N2: usize> PartialEq<IndexSet<T, S2, N2>> for IndexSet<T, S1, N1>where + T: Eq + Hash, + S1: BuildHasher, + S2: BuildHasher,

source§

fn eq(&self, other: &IndexSet<T, S2, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl<T, S, const N: usize> RefUnwindSafe for IndexSet<T, S, N>where + S: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, S, const N: usize> Send for IndexSet<T, S, N>where + S: Send, + T: Send,

§

impl<T, S, const N: usize> Sync for IndexSet<T, S, N>where + S: Sync, + T: Sync,

§

impl<T, S, const N: usize> Unpin for IndexSet<T, S, N>where + S: Unpin, + T: Unpin,

§

impl<T, S, const N: usize> UnwindSafe for IndexSet<T, S, N>where + S: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.LinearMap.html b/docs/doc/arduboy_rust/heapless/struct.LinearMap.html new file mode 100644 index 0000000..07a1054 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.LinearMap.html @@ -0,0 +1,214 @@ +LinearMap in arduboy_rust::heapless - Rust
pub struct LinearMap<K, V, const N: usize> { /* private fields */ }
Expand description

A fixed capacity map / dictionary that performs lookups via linear search

+

Note that as this map doesn’t use hashing so most operations are O(N) instead of O(1)

+

Implementations§

source§

impl<K, V, const N: usize> LinearMap<K, V, N>

source

pub const fn new() -> LinearMap<K, V, N>

Creates an empty LinearMap

+
Examples
+
use heapless::LinearMap;
+
+// allocate the map on the stack
+let mut map: LinearMap<&str, isize, 8> = LinearMap::new();
+
+// allocate the map in a static variable
+static mut MAP: LinearMap<&str, isize, 8> = LinearMap::new();
+
source§

impl<K, V, const N: usize> LinearMap<K, V, N>where + K: Eq,

source

pub fn capacity(&self) -> usize

Returns the number of elements that the map can hold

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let map: LinearMap<&str, isize, 8> = LinearMap::new();
+assert_eq!(map.capacity(), 8);
+
source

pub fn clear(&mut self)

Clears the map, removing all key-value pairs

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+map.clear();
+assert!(map.is_empty());
+
source

pub fn contains_key(&self, key: &K) -> bool

Returns true if the map contains a value for the specified key.

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.contains_key(&1), true);
+assert_eq!(map.contains_key(&2), false);
+
source

pub fn get<Q>(&self, key: &Q) -> Option<&V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Returns a reference to the value corresponding to the key

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.get(&1), Some(&"a"));
+assert_eq!(map.get(&2), None);
+
source

pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Returns a mutable reference to the value corresponding to the key

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+if let Some(x) = map.get_mut(&1) {
+    *x = "b";
+}
+assert_eq!(map[&1], "b");
+
source

pub fn len(&self) -> usize

Returns the number of elements in this map

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut a: LinearMap<_, _, 8> = LinearMap::new();
+assert_eq!(a.len(), 0);
+a.insert(1, "a").unwrap();
+assert_eq!(a.len(), 1);
+
source

pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)>

Inserts a key-value pair into the map.

+

If the map did not have this key present, None is returned.

+

If the map did have this key present, the value is updated, and the old value is returned.

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+assert_eq!(map.insert(37, "a").unwrap(), None);
+assert_eq!(map.is_empty(), false);
+
+map.insert(37, "b").unwrap();
+assert_eq!(map.insert(37, "c").unwrap(), Some("b"));
+assert_eq!(map[&37], "c");
+
source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut a: LinearMap<_, _, 8> = LinearMap::new();
+assert!(a.is_empty());
+a.insert(1, "a").unwrap();
+assert!(!a.is_empty());
+
source

pub fn iter(&self) -> Iter<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order.

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (key, val) in map.iter() {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the +values

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+// Update all values
+for (_, val) in map.iter_mut() {
+    *val = 2;
+}
+
+for (key, val) in &map {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn keys(&self) -> impl Iterator<Item = &K>

An iterator visiting all keys in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for key in map.keys() {
+    println!("{}", key);
+}
+
source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Removes a key from the map, returning the value at the key if the key was previously in the +map

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.remove(&1), Some("a"));
+assert_eq!(map.remove(&1), None);
+
source

pub fn values(&self) -> impl Iterator<Item = &V>

An iterator visiting all values in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V>

An iterator visiting all values mutably in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values_mut() {
+    *val += 10;
+}
+
+for val in map.values() {
+    println!("{}", val);
+}
+

Trait Implementations§

source§

impl<K, V, const N: usize> Clone for LinearMap<K, V, N>where + K: Eq + Clone, + V: Clone,

source§

fn clone(&self) -> LinearMap<K, V, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K, V, const N: usize> Debug for LinearMap<K, V, N>where + K: Eq + Debug, + V: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<K, V, const N: usize> Default for LinearMap<K, V, N>where + K: Eq,

source§

fn default() -> LinearMap<K, V, N>

Returns the “default value” for a type. Read more
source§

impl<K, V, const N: usize> Drop for LinearMap<K, V, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<K, V, const N: usize> FromIterator<(K, V)> for LinearMap<K, V, N>where + K: Eq,

source§

fn from_iter<I>(iter: I) -> LinearMap<K, V, N>where + I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl<'a, K, V, Q, const N: usize> Index<&'a Q> for LinearMap<K, V, N>where + K: Borrow<Q> + Eq, + Q: Eq + ?Sized,

§

type Output = V

The returned type after indexing.
source§

fn index(&self, key: &Q) -> &V

Performs the indexing (container[index]) operation. Read more
source§

impl<'a, K, V, Q, const N: usize> IndexMut<&'a Q> for LinearMap<K, V, N>where + K: Borrow<Q> + Eq, + Q: Eq + ?Sized,

source§

fn index_mut(&mut self, key: &Q) -> &mut V

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, K, V, const N: usize> IntoIterator for &'a LinearMap<K, V, N>where + K: Eq,

§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a LinearMap<K, V, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, const N: usize, const N2: usize> PartialEq<LinearMap<K, V, N2>> for LinearMap<K, V, N>where + K: Eq, + V: PartialEq<V>,

source§

fn eq(&self, other: &LinearMap<K, V, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<K, V, const N: usize> Eq for LinearMap<K, V, N>where + K: Eq, + V: PartialEq<V>,

Auto Trait Implementations§

§

impl<K, V, const N: usize> RefUnwindSafe for LinearMap<K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<K, V, const N: usize> Send for LinearMap<K, V, N>where + K: Send, + V: Send,

§

impl<K, V, const N: usize> Sync for LinearMap<K, V, N>where + K: Sync, + V: Sync,

§

impl<K, V, const N: usize> Unpin for LinearMap<K, V, N>where + K: Unpin, + V: Unpin,

§

impl<K, V, const N: usize> UnwindSafe for LinearMap<K, V, N>where + K: UnwindSafe, + V: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.OccupiedEntry.html b/docs/doc/arduboy_rust/heapless/struct.OccupiedEntry.html new file mode 100644 index 0000000..1f41815 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.OccupiedEntry.html @@ -0,0 +1,27 @@ +OccupiedEntry in arduboy_rust::heapless - Rust
pub struct OccupiedEntry<'a, K, V, const N: usize> { /* private fields */ }
Expand description

An occupied entry which can be manipulated

+

Implementations§

source§

impl<'a, K, V, const N: usize> OccupiedEntry<'a, K, V, N>where + K: Eq + Hash,

source

pub fn key(&self) -> &K

Gets a reference to the key that this entity corresponds to

+
source

pub fn remove_entry(self) -> (K, V)

Removes this entry from the map and yields its corresponding key and value

+
source

pub fn get(&self) -> &V

Gets a reference to the value associated with this entry

+
source

pub fn get_mut(&mut self) -> &mut V

Gets a mutable reference to the value associated with this entry

+
source

pub fn into_mut(self) -> &'a mut V

Consumes this entry and yields a reference to the underlying value

+
source

pub fn insert(self, value: V) -> V

Overwrites the underlying map’s value with this entry’s value

+
source

pub fn remove(self) -> V

Removes this entry from the map and yields its value

+

Auto Trait Implementations§

§

impl<'a, K, V, const N: usize> RefUnwindSafe for OccupiedEntry<'a, K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<'a, K, V, const N: usize> Send for OccupiedEntry<'a, K, V, N>where + K: Send, + V: Send,

§

impl<'a, K, V, const N: usize> Sync for OccupiedEntry<'a, K, V, N>where + K: Sync, + V: Sync,

§

impl<'a, K, V, const N: usize> Unpin for OccupiedEntry<'a, K, V, N>where + K: Unpin,

§

impl<'a, K, V, const N: usize> !UnwindSafe for OccupiedEntry<'a, K, V, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.OldestOrdered.html b/docs/doc/arduboy_rust/heapless/struct.OldestOrdered.html new file mode 100644 index 0000000..51d68ea --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.OldestOrdered.html @@ -0,0 +1,191 @@ +OldestOrdered in arduboy_rust::heapless - Rust
pub struct OldestOrdered<'a, T, const N: usize> { /* private fields */ }
Expand description

An iterator on the underlying buffer ordered from oldest data to newest

+

Trait Implementations§

source§

impl<'a, T, const N: usize> Clone for OldestOrdered<'a, T, N>where + T: Clone,

source§

fn clone(&self) -> OldestOrdered<'a, T, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a, T, const N: usize> Iterator for OldestOrdered<'a, T, N>

§

type Item = &'a T

The type of the elements being iterated over.
source§

fn next(&mut self) -> Option<&'a T>

Advances the iterator and returns the next value. Read more
§

fn next_chunk<const N: usize>( + &mut self +) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.0.0§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
1.0.0§

fn count(self) -> usizewhere + Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
1.0.0§

fn last(self) -> Option<Self::Item>where + Self: Sized,

Consumes the iterator, returning the last element. Read more
§

fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.0.0§

fn nth(&mut self, n: usize) -> Option<Self::Item>

Returns the nth element of the iterator. Read more
1.28.0§

fn step_by(self, step: usize) -> StepBy<Self>where + Self: Sized,

Creates an iterator starting at the same point, but stepping by +the given amount at each iteration. Read more
1.0.0§

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.0.0§

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator,

‘Zips up’ two iterators into a single iterator of pairs. Read more
§

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>where + Self: Sized, + G: FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator +between adjacent items of the original iterator. Read more
1.0.0§

fn map<B, F>(self, f: F) -> Map<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each +element. Read more
1.21.0§

fn for_each<F>(self, f: F)where + Self: Sized, + F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.0.0§

fn filter<P>(self, predicate: P) -> Filter<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element +should be yielded. Read more
1.0.0§

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.0.0§

fn enumerate(self) -> Enumerate<Self>where + Self: Sized,

Creates an iterator which gives the current iteration count as well as +the next value. Read more
1.0.0§

fn peekable(self) -> Peekable<Self>where + Self: Sized,

Creates an iterator which can use the peek and peek_mut methods +to look at the next element of the iterator without consuming it. See +their documentation for more information. Read more
1.0.0§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.0.0§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where + Self: Sized, + P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.0.0§

fn skip(self, n: usize) -> Skip<Self>where + Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.0.0§

fn take(self, n: usize) -> Take<Self>where + Self: Sized,

Creates an iterator that yields the first n elements, or fewer +if the underlying iterator ends sooner. Read more
1.0.0§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where + Self: Sized, + F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but +unlike fold, produces a new iterator. Read more
1.0.0§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where + Self: Sized, + U: IntoIterator, + F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
1.0.0§

fn fuse(self) -> Fuse<Self>where + Self: Sized,

Creates an iterator which ends after the first [None]. Read more
1.0.0§

fn inspect<F>(self, f: F) -> Inspect<Self, F>where + Self: Sized, + F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.0.0§

fn by_ref(&mut self) -> &mut Selfwhere + Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.0.0§

fn collect<B>(self) -> Bwhere + B: FromIterator<Self::Item>, + Self: Sized,

Transforms an iterator into a collection. Read more
§

fn collect_into<E>(self, collection: &mut E) -> &mut Ewhere + E: Extend<Self::Item>, + Self: Sized,

🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.0.0§

fn partition<B, F>(self, f: F) -> (B, B)where + Self: Sized, + B: Default + Extend<Self::Item>, + F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
§

fn is_partitioned<P>(self, predicate: P) -> boolwhere + Self: Sized, + P: FnMut(Self::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate, +such that all those that return true precede all those that return false. Read more
1.27.0§

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try<Output = B>,

An iterator method that applies a function as long as it returns +successfully, producing a single, final value. Read more
1.27.0§

fn try_for_each<F, R>(&mut self, f: F) -> Rwhere + Self: Sized, + F: FnMut(Self::Item) -> R, + R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the +iterator, stopping at the first error and returning that error. Read more
1.0.0§

fn fold<B, F>(self, init: B, f: F) -> Bwhere + Self: Sized, + F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation, +returning the final result. Read more
1.51.0§

fn reduce<F>(self, f: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing +operation. Read more
§

fn try_reduce<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> R, + R: Try<Output = Self::Item>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the +closure returns a failure, the failure is propagated back to the caller immediately. Read more
1.0.0§

fn all<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.0.0§

fn any<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.0.0§

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0§

fn find_map<B, F>(&mut self, f: F) -> Option<B>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns +the first non-none result. Read more
§

fn try_find<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere + Self: Sized, + F: FnMut(&Self::Item) -> R, + R: Try<Output = bool>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns +the first true result or the first error. Read more
1.0.0§

fn position<P>(&mut self, predicate: P) -> Option<usize>where + Self: Sized, + P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0§

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the +specified function. Read more
1.15.0§

fn max_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the +specified comparison function. Read more
1.6.0§

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the +specified function. Read more
1.15.0§

fn min_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the +specified comparison function. Read more
1.0.0§

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where + FromA: Default + Extend<A>, + FromB: Default + Extend<B>, + Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0§

fn copied<'a, T>(self) -> Copied<Self>where + T: 'a + Copy, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.0.0§

fn cloned<'a, T>(self) -> Cloned<Self>where + T: 'a + Clone, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
§

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0§

fn sum<S>(self) -> Swhere + Self: Sized, + S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0§

fn product<P>(self) -> Pwhere + Self: Sized, + P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
§

fn cmp_by<I, F>(self, other: I, cmp: F) -> Orderingwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn partial_cmp<I>(self, other: I) -> Option<Ordering>where + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Lexicographically compares the [PartialOrd] elements of +this [Iterator] with those of another. The comparison works like short-circuit +evaluation, returning a result without comparing the remaining elements. +As soon as an order can be determined, the evaluation stops and a result is returned. Read more
§

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn eq<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are equal to those of +another. Read more
§

fn eq_by<I, F>(self, other: I, eq: F) -> boolwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this [Iterator] are equal to those of +another with respect to the specified equality function. Read more
1.5.0§

fn ne<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are not equal to those of +another. Read more
1.5.0§

fn lt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less than those of another. Read more
1.5.0§

fn le<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less or equal to those of another. Read more
1.5.0§

fn gt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than those of another. Read more
1.5.0§

fn ge<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than or equal to those of another. Read more
§

fn is_sorted_by<F>(self, compare: F) -> boolwhere + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
§

fn is_sorted_by_key<F, K>(self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction +function. Read more

Auto Trait Implementations§

§

impl<'a, T, const N: usize> RefUnwindSafe for OldestOrdered<'a, T, N>where + T: RefUnwindSafe,

§

impl<'a, T, const N: usize> Send for OldestOrdered<'a, T, N>where + T: Sync,

§

impl<'a, T, const N: usize> Sync for OldestOrdered<'a, T, N>where + T: Sync,

§

impl<'a, T, const N: usize> Unpin for OldestOrdered<'a, T, N>

§

impl<'a, T, const N: usize> UnwindSafe for OldestOrdered<'a, T, N>where + T: RefUnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<I> IntoIterator for Iwhere + I: Iterator,

§

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
§

type IntoIter = I

Which kind of iterator are we turning this into?
const: unstable§

fn into_iter(self) -> I

Creates an iterator from a value. Read more
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.String.html b/docs/doc/arduboy_rust/heapless/struct.String.html new file mode 100644 index 0000000..8d7307d --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.String.html @@ -0,0 +1,1373 @@ +String in arduboy_rust::heapless - Rust
pub struct String<const N: usize> { /* private fields */ }
Expand description

A fixed capacity String

+

Implementations§

source§

impl<const N: usize> String<N>

source

pub const fn new() -> String<N>

Constructs a new, empty String with a fixed capacity of N bytes

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+// allocate the string on the stack
+let mut s: String<4> = String::new();
+
+// allocate the string in a static variable
+static mut S: String<4> = String::new();
+
source

pub fn into_bytes(self) -> Vec<u8, N>

Converts a String into a byte vector.

+

This consumes the String, so we do not need to copy its contents.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let s: String<4> = String::from("ab");
+let b = s.into_bytes();
+assert!(b.len() == 2);
+
+assert_eq!(&['a' as u8, 'b' as u8], &b[..]);
+
source

pub fn as_str(&self) -> &str

Extracts a string slice containing the entire string.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::from("ab");
+assert!(s.as_str() == "ab");
+
+let _s = s.as_str();
+// s.push('c'); // <- cannot borrow `s` as mutable because it is also borrowed as immutable
+
source

pub fn as_mut_str(&mut self) -> &mut str

Converts a String into a mutable string slice.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::from("ab");
+let s = s.as_mut_str();
+s.make_ascii_uppercase();
+
source

pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, N>

Returns a mutable reference to the contents of this String.

+
Safety
+

This function is unsafe because it does not check that the bytes passed +to it are valid UTF-8. If this constraint is violated, it may cause +memory unsafety issues with future users of the String, as the rest of +the library assumes that Strings are valid UTF-8.

+
Examples
+

Basic usage:

+ +
let mut s = String::from("hello");
+
+unsafe {
+    let vec = s.as_mut_vec();
+    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
+
+    vec.reverse();
+}
+assert_eq!(s, "olleh");
+
source

pub fn push_str(&mut self, string: &str) -> Result<(), ()>

Appends a given string slice onto the end of this String.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+assert!(s.push_str("bar").is_ok());
+
+assert_eq!("foobar", s);
+
+assert!(s.push_str("tender").is_err());
+
source

pub fn capacity(&self) -> usize

Returns the maximum number of elements the String can hold

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::new();
+assert!(s.capacity() == 4);
+
source

pub fn push(&mut self, c: char) -> Result<(), ()>

Appends the given char to the end of this String.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("abc");
+
+s.push('1').unwrap();
+s.push('2').unwrap();
+s.push('3').unwrap();
+
+assert!("abc123" == s.as_str());
+
+assert_eq!("abc123", s);
+
source

pub fn truncate(&mut self, new_len: usize)

Shortens this String to the specified length.

+

If new_len is greater than the string’s current length, this has no +effect.

+

Note that this method has no effect on the allocated capacity +of the string

+
Panics
+

Panics if new_len does not lie on a char boundary.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("hello");
+
+s.truncate(2);
+
+assert_eq!("he", s);
+
source

pub fn pop(&mut self) -> Option<char>

Removes the last character from the string buffer and returns it.

+

Returns None if this String is empty.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+assert_eq!(s.pop(), Some('o'));
+assert_eq!(s.pop(), Some('o'));
+assert_eq!(s.pop(), Some('f'));
+
+assert_eq!(s.pop(), None);
+
source

pub fn clear(&mut self)

Truncates this String, removing all contents.

+

While this means the String will have a length of zero, it does not +touch its capacity.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+s.clear();
+
+assert!(s.is_empty());
+assert_eq!(0, s.len());
+assert_eq!(8, s.capacity());
+

Methods from Deref<Target = str>§

1.0.0

pub fn len(&self) -> usize

Returns the length of self.

+

This length is in bytes, not chars or graphemes. In other words, +it might not be what a human considers the length of the string.

+
Examples
+
let len = "foo".len();
+assert_eq!(3, len);
+
+assert_eq!("ƒoo".len(), 4); // fancy f!
+assert_eq!("ƒoo".chars().count(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

+
Examples
+
let s = "";
+assert!(s.is_empty());
+
+let s = "not empty";
+assert!(!s.is_empty());
+
1.9.0

pub fn is_char_boundary(&self, index: usize) -> bool

Checks that index-th byte is the first byte in a UTF-8 code point +sequence or the end of the string.

+

The start and end of the string (when index == self.len()) are +considered to be boundaries.

+

Returns false if index is greater than self.len().

+
Examples
+
let s = "Löwe 老虎 Léopard";
+assert!(s.is_char_boundary(0));
+// start of `老`
+assert!(s.is_char_boundary(6));
+assert!(s.is_char_boundary(s.len()));
+
+// second byte of `ö`
+assert!(!s.is_char_boundary(2));
+
+// third byte of `老`
+assert!(!s.is_char_boundary(8));
+

pub fn floor_char_boundary(&self, index: usize) -> usize

🔬This is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not exceeding index where is_char_boundary(x) is true.

+

This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t +exceed a given number of bytes. Note that this is done purely at the character level +and can still visually split graphemes, even though the underlying characters aren’t +split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only +includes 🧑 (person) instead.

+
Examples
+
#![feature(round_char_boundary)]
+let s = "❤️🧡💛💚💙💜";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.floor_char_boundary(13);
+assert_eq!(closest, 10);
+assert_eq!(&s[..closest], "❤️🧡");
+

pub fn ceil_char_boundary(&self, index: usize) -> usize

🔬This is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not below index where is_char_boundary(x) is true.

+

This method is the natural complement to floor_char_boundary. See that method +for more details.

+
Panics
+

Panics if index > self.len().

+
Examples
+
#![feature(round_char_boundary)]
+let s = "❤️🧡💛💚💙💜";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.ceil_char_boundary(13);
+assert_eq!(closest, 14);
+assert_eq!(&s[..closest], "❤️🧡💛");
+
1.0.0

pub fn as_bytes(&self) -> &[u8]

Converts a string slice to a byte slice. To convert the byte slice back +into a string slice, use the [from_utf8] function.

+
Examples
+
let bytes = "bors".as_bytes();
+assert_eq!(b"bors", bytes);
+
1.20.0

pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8]

Converts a mutable string slice to a mutable byte slice.

+
Safety
+

The caller must ensure that the content of the slice is valid UTF-8 +before the borrow ends and the underlying str is used.

+

Use of a str whose contents are not valid UTF-8 is undefined behavior.

+
Examples
+

Basic usage:

+ +
let mut s = String::from("Hello");
+let bytes = unsafe { s.as_bytes_mut() };
+
+assert_eq!(b"Hello", bytes);
+

Mutability:

+ +
let mut s = String::from("🗻∈🌏");
+
+unsafe {
+    let bytes = s.as_bytes_mut();
+
+    bytes[0] = 0xF0;
+    bytes[1] = 0x9F;
+    bytes[2] = 0x8D;
+    bytes[3] = 0x94;
+}
+
+assert_eq!("🍔∈🌏", s);
+
1.0.0

pub fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +[u8]. This pointer will be pointing to the first byte of the string +slice.

+

The caller must ensure that the returned pointer is never written to. +If you need to mutate the contents of the string slice, use as_mut_ptr.

+
Examples
+
let s = "Hello";
+let ptr = s.as_ptr();
+
1.36.0

pub fn as_mut_ptr(&mut self) -> *mut u8

Converts a mutable string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +[u8]. This pointer will be pointing to the first byte of the string +slice.

+

It is your responsibility to make sure that the string slice only gets +modified in a way that it remains valid UTF-8.

+
1.20.0

pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where + I: SliceIndex<str>,

Returns a subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +[None] whenever equivalent indexing operation would panic.

+
Examples
+
let v = String::from("🗻∈🌏");
+
+assert_eq!(Some("🗻"), v.get(0..4));
+
+// indices not on UTF-8 sequence boundaries
+assert!(v.get(1..).is_none());
+assert!(v.get(..8).is_none());
+
+// out of bounds
+assert!(v.get(..42).is_none());
+
1.20.0

pub fn get_mut<I>( + &mut self, + i: I +) -> Option<&mut <I as SliceIndex<str>>::Output>where + I: SliceIndex<str>,

Returns a mutable subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +[None] whenever equivalent indexing operation would panic.

+
Examples
+
let mut v = String::from("hello");
+// correct length
+assert!(v.get_mut(0..5).is_some());
+// out of bounds
+assert!(v.get_mut(..42).is_none());
+assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
+
+assert_eq!("hello", v);
+{
+    let s = v.get_mut(0..2);
+    let s = s.map(|s| {
+        s.make_ascii_uppercase();
+        &*s
+    });
+    assert_eq!(Some("HE"), s);
+}
+assert_eq!("HEllo", v);
+
1.20.0

pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere + I: SliceIndex<str>,

Returns an unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
Safety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
Examples
+
let v = "🗻∈🌏";
+unsafe {
+    assert_eq!("🗻", v.get_unchecked(0..4));
+    assert_eq!("∈", v.get_unchecked(4..7));
+    assert_eq!("🌏", v.get_unchecked(7..11));
+}
+
1.20.0

pub unsafe fn get_unchecked_mut<I>( + &mut self, + i: I +) -> &mut <I as SliceIndex<str>>::Outputwhere + I: SliceIndex<str>,

Returns a mutable, unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
Safety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
Examples
+
let mut v = String::from("🗻∈🌏");
+unsafe {
+    assert_eq!("🗻", v.get_unchecked_mut(0..4));
+    assert_eq!("∈", v.get_unchecked_mut(4..7));
+    assert_eq!("🌏", v.get_unchecked_mut(7..11));
+}
+
1.0.0

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

👎Deprecated since 1.29.0: use get_unchecked(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks.

+

This is generally not recommended, use with caution! For a safe +alternative see [str] and Index.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get a mutable string slice instead, see the +slice_mut_unchecked method.

+
Safety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
Examples
+
let s = "Löwe 老虎 Léopard";
+
+unsafe {
+    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
+}
+
+let s = "Hello, world!";
+
+unsafe {
+    assert_eq!("world", s.slice_unchecked(7, 12));
+}
+
1.5.0

pub unsafe fn slice_mut_unchecked( + &mut self, + begin: usize, + end: usize +) -> &mut str

👎Deprecated since 1.29.0: use get_unchecked_mut(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks. +This is generally not recommended, use with caution! For a safe +alternative see [str] and IndexMut.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get an immutable string slice instead, see the +slice_unchecked method.

+
Safety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
1.4.0

pub fn split_at(&self, mid: usize) -> (&str, &str)

Divide one string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get mutable string slices instead, see the split_at_mut +method.

+
Panics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is +past the end of the last code point of the string slice.

+
Examples
+
let s = "Per Martin-Löf";
+
+let (first, last) = s.split_at(3);
+
+assert_eq!("Per", first);
+assert_eq!(" Martin-Löf", last);
+
1.4.0

pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)

Divide one mutable string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get immutable string slices instead, see the split_at method.

+
Panics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is +past the end of the last code point of the string slice.

+
Examples
+
let mut s = "Per Martin-Löf".to_string();
+{
+    let (first, last) = s.split_at_mut(3);
+    first.make_ascii_uppercase();
+    assert_eq!("PER", first);
+    assert_eq!(" Martin-Löf", last);
+}
+assert_eq!("PER Martin-Löf", s);
+
1.0.0

pub fn chars(&self) -> Chars<'_>

Returns an iterator over the chars of a string slice.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns such an iterator.

+

It’s important to remember that char represents a Unicode Scalar +Value, and might not match your idea of what a ‘character’ is. Iteration +over grapheme clusters may be what you actually want. This functionality +is not provided by Rust’s standard library, check crates.io instead.

+
Examples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.chars().count();
+assert_eq!(7, count);
+
+let mut chars = word.chars();
+
+assert_eq!(Some('g'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('d'), chars.next());
+assert_eq!(Some('b'), chars.next());
+assert_eq!(Some('y'), chars.next());
+assert_eq!(Some('e'), chars.next());
+
+assert_eq!(None, chars.next());
+

Remember, chars might not match your intuition about characters:

+ +
let y = "y̆";
+
+let mut chars = y.chars();
+
+assert_eq!(Some('y'), chars.next()); // not 'y̆'
+assert_eq!(Some('\u{0306}'), chars.next());
+
+assert_eq!(None, chars.next());
+
1.0.0

pub fn char_indices(&self) -> CharIndices<'_>

Returns an iterator over the chars of a string slice, and their +positions.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns an iterator of both +these chars, as well as their byte positions.

+

The iterator yields tuples. The position is first, the char is +second.

+
Examples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.char_indices().count();
+assert_eq!(7, count);
+
+let mut char_indices = word.char_indices();
+
+assert_eq!(Some((0, 'g')), char_indices.next());
+assert_eq!(Some((1, 'o')), char_indices.next());
+assert_eq!(Some((2, 'o')), char_indices.next());
+assert_eq!(Some((3, 'd')), char_indices.next());
+assert_eq!(Some((4, 'b')), char_indices.next());
+assert_eq!(Some((5, 'y')), char_indices.next());
+assert_eq!(Some((6, 'e')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+

Remember, chars might not match your intuition about characters:

+ +
let yes = "y̆es";
+
+let mut char_indices = yes.char_indices();
+
+assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
+assert_eq!(Some((1, '\u{0306}')), char_indices.next());
+
+// note the 3 here - the last character took up two bytes
+assert_eq!(Some((3, 'e')), char_indices.next());
+assert_eq!(Some((4, 's')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+
1.0.0

pub fn bytes(&self) -> Bytes<'_>

An iterator over the bytes of a string slice.

+

As a string slice consists of a sequence of bytes, we can iterate +through a string slice by byte. This method returns such an iterator.

+
Examples
+
let mut bytes = "bors".bytes();
+
+assert_eq!(Some(b'b'), bytes.next());
+assert_eq!(Some(b'o'), bytes.next());
+assert_eq!(Some(b'r'), bytes.next());
+assert_eq!(Some(b's'), bytes.next());
+
+assert_eq!(None, bytes.next());
+
1.1.0

pub fn split_whitespace(&self) -> SplitWhitespace<'_>

Splits a string slice by whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of whitespace.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space. If you only want to split on ASCII whitespace +instead, use split_ascii_whitespace.

+
Examples
+

Basic usage:

+ +
let mut iter = "A few words".split_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of whitespace are considered:

+ +
let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_whitespace().next(), None);
+assert_eq!("   ".split_whitespace().next(), None);
+
1.34.0

pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>

Splits a string slice by ASCII whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of ASCII whitespace.

+

To split by Unicode Whitespace instead, use split_whitespace.

+
Examples
+

Basic usage:

+ +
let mut iter = "A few words".split_ascii_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of ASCII whitespace are considered:

+ +
let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all ASCII whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_ascii_whitespace().next(), None);
+assert_eq!("   ".split_ascii_whitespace().next(), None);
+
1.0.0

pub fn lines(&self) -> Lines<'_>

An iterator over the lines of a string, as string slices.

+

Lines are split at line endings that are either newlines (\n) or +sequences of a carriage return followed by a line feed (\r\n).

+

Line terminators are not included in the lines returned by the iterator.

+

The final line ending is optional. A string that ends with a final line +ending will return the same lines as an otherwise identical string +without a final line ending.

+
Examples
+

Basic usage:

+ +
let text = "foo\r\nbar\n\nbaz\n";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+

The final line ending isn’t required:

+ +
let text = "foo\nbar\n\r\nbaz";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+
1.0.0

pub fn lines_any(&self) -> LinesAny<'_>

👎Deprecated since 1.4.0: use lines() instead now

An iterator over the lines of a string.

+
1.8.0

pub fn encode_utf16(&self) -> EncodeUtf16<'_>

Returns an iterator of u16 over the string encoded as UTF-16.

+
Examples
+
let text = "Zażółć gęślą jaźń";
+
+let utf8_len = text.len();
+let utf16_len = text.encode_utf16().count();
+
+assert!(utf16_len <= utf8_len);
+
1.0.0

pub fn contains<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>,

Returns true if the given pattern matches a sub-slice of +this string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.contains("nana"));
+assert!(!bananas.contains("apples"));
+
1.0.0

pub fn starts_with<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>,

Returns true if the given pattern matches a prefix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.starts_with("bana"));
+assert!(!bananas.starts_with("nana"));
+
1.0.0

pub fn ends_with<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns true if the given pattern matches a suffix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.ends_with("anas"));
+assert!(!bananas.ends_with("nana"));
+
1.0.0

pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>where + P: Pattern<'a>,

Returns the byte index of the first character of this string slice that +matches the pattern.

+

Returns [None] if the pattern doesn’t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
let s = "Löwe 老虎 Léopard Gepardi";
+
+assert_eq!(s.find('L'), Some(0));
+assert_eq!(s.find('é'), Some(14));
+assert_eq!(s.find("pard"), Some(17));
+

More complex patterns using point-free style and closures:

+ +
let s = "Löwe 老虎 Léopard";
+
+assert_eq!(s.find(char::is_whitespace), Some(5));
+assert_eq!(s.find(char::is_lowercase), Some(1));
+assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
+assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
+

Not finding the pattern:

+ +
let s = "Löwe 老虎 Léopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.find(x), None);
+
1.0.0

pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns the byte index for the first character of the last match of the pattern in +this string slice.

+

Returns [None] if the pattern doesn’t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
let s = "Löwe 老虎 Léopard Gepardi";
+
+assert_eq!(s.rfind('L'), Some(13));
+assert_eq!(s.rfind('é'), Some(14));
+assert_eq!(s.rfind("pard"), Some(24));
+

More complex patterns with closures:

+ +
let s = "Löwe 老虎 Léopard";
+
+assert_eq!(s.rfind(char::is_whitespace), Some(12));
+assert_eq!(s.rfind(char::is_lowercase), Some(20));
+

Not finding the pattern:

+ +
let s = "Löwe 老虎 Léopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.rfind(x), None);
+
1.0.0

pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P>where + P: Pattern<'a>,

An iterator over substrings of this string slice, separated by +characters matched by a pattern.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rsplit method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
+assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
+
+let v: Vec<&str> = "".split('X').collect();
+assert_eq!(v, [""]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
+assert_eq!(v, ["lion", "", "tiger", "leopard"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
+assert_eq!(v, ["lion", "tiger", "leopard"]);
+
+let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
+assert_eq!(v, ["abc", "def", "ghi"]);
+
+let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
+assert_eq!(v, ["lion", "tiger", "leopard"]);
+

If the pattern is a slice of chars, split on each occurrence of any of the characters:

+ +
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
+assert_eq!(v, ["2020", "11", "03", "23", "59"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["abc", "def", "ghi"]);
+

If a string contains multiple contiguous separators, you will end up +with empty strings in the output:

+ +
let x = "||||a||b|c".to_string();
+let d: Vec<_> = x.split('|').collect();
+
+assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
+

Contiguous separators are separated by the empty string.

+ +
let x = "(///)".to_string();
+let d: Vec<_> = x.split('/').collect();
+
+assert_eq!(d, &["(", "", "", ")"]);
+

Separators at the start or end of a string are neighbored +by empty strings.

+ +
let d: Vec<_> = "010".split("0").collect();
+assert_eq!(d, &["", "1", ""]);
+

When the empty string is used as a separator, it separates +every character in the string, along with the beginning +and end of the string.

+ +
let f: Vec<_> = "rust".split("").collect();
+assert_eq!(f, &["", "r", "u", "s", "t", ""]);
+

Contiguous separators can lead to possibly surprising behavior +when whitespace is used as the separator. This code is correct:

+ +
let x = "    a  b c".to_string();
+let d: Vec<_> = x.split(' ').collect();
+
+assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
+

It does not give you:

+ +
assert_eq!(d, &["a", "b", "c"]);
+

Use split_whitespace for this behavior.

+
1.51.0

pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P>where + P: Pattern<'a>,

An iterator over substrings of this string slice, separated by +characters matched by a pattern. Differs from the iterator produced by +split in that split_inclusive leaves the matched part as the +terminator of the substring.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
+

If the last element of the string is matched, +that element will be considered the terminator of the preceding substring. +That substring will be the last item returned by the iterator.

+ +
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
+
1.0.0

pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of the given string slice, separated by +characters matched by a pattern and yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the split method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
+assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
+
+let v: Vec<&str> = "".rsplit('X').collect();
+assert_eq!(v, [""]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
+assert_eq!(v, ["leopard", "tiger", "", "lion"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
+assert_eq!(v, ["leopard", "tiger", "lion"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["ghi", "def", "abc"]);
+
1.0.0

pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P>where + P: Pattern<'a>,

An iterator over substrings of the given string slice, separated by +characters matched by a pattern.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring +is skipped if empty.

+

This method can be used for string data that is terminated, +rather than separated by a pattern.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rsplit_terminator method can be used.

+
Examples
+
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
+assert_eq!(v, ["A", "B"]);
+
+let v: Vec<&str> = "A..B..".split_terminator(".").collect();
+assert_eq!(v, ["A", "", "B", ""]);
+
+let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
+assert_eq!(v, ["A", "B", "C", "D"]);
+
1.0.0

pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of self, separated by characters +matched by a pattern and yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring is +skipped if empty.

+

This method can be used for string data that is terminated, +rather than separated by a pattern.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a +reverse search, and it will be double ended if a forward/reverse +search yields the same elements.

+

For iterating from the front, the split_terminator method can be +used.

+
Examples
+
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
+assert_eq!(v, ["B", "A"]);
+
+let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
+assert_eq!(v, ["", "B", "", "A"]);
+
+let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
+assert_eq!(v, ["D", "C", "B", "A"]);
+
1.0.0

pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P>where + P: Pattern<'a>,

An iterator over substrings of the given string slice, separated by a +pattern, restricted to returning at most n items.

+

If n substrings are returned, the last substring (the nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will not be double ended, because it is +not efficient to support.

+

If the pattern allows a reverse search, the rsplitn method can be +used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
+assert_eq!(v, ["Mary", "had", "a little lambda"]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
+assert_eq!(v, ["lion", "", "tigerXleopard"]);
+
+let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
+assert_eq!(v, ["abcXdef"]);
+
+let v: Vec<&str> = "".splitn(1, 'X').collect();
+assert_eq!(v, [""]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["abc", "defXghi"]);
+
1.0.0

pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of this string slice, separated by a +pattern, starting from the end of the string, restricted to returning +at most n items.

+

If n substrings are returned, the last substring (the nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will not be double ended, because it is not +efficient to support.

+

For splitting from the front, the splitn method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
+assert_eq!(v, ["lamb", "little", "Mary had a"]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
+assert_eq!(v, ["leopard", "tiger", "lionX"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
+assert_eq!(v, ["leopard", "lion::tiger"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["ghi", "abc1def"]);
+
1.52.0

pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where + P: Pattern<'a>,

Splits the string on the first occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
Examples
+
assert_eq!("cfg".split_once('='), None);
+assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
+assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
+
1.52.0

pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Splits the string on the last occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
Examples
+
assert_eq!("cfg".rsplit_once('='), None);
+assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
+
1.2.0

pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P>where + P: Pattern<'a>,

An iterator over the disjoint matches of a pattern within the given string +slice.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rmatches method can be used.

+
Examples
+
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
+assert_eq!(v, ["abc", "abc", "abc"]);
+
+let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
+assert_eq!(v, ["1", "2", "3"]);
+
1.2.0

pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over the disjoint matches of a pattern within this string slice, +yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the matches method can be used.

+
Examples
+
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
+assert_eq!(v, ["abc", "abc", "abc"]);
+
+let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
+assert_eq!(v, ["3", "2", "1"]);
+
1.5.0

pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P>where + P: Pattern<'a>,

An iterator over the disjoint matches of a pattern within this string +slice as well as the index that the match starts at.

+

For matches of pat within self that overlap, only the indices +corresponding to the first match are returned.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rmatch_indices method can be used.

+
Examples
+
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
+assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
+
+let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
+assert_eq!(v, [(1, "abc"), (4, "abc")]);
+
+let v: Vec<_> = "ababa".match_indices("aba").collect();
+assert_eq!(v, [(0, "aba")]); // only the first `aba`
+
1.5.0

pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over the disjoint matches of a pattern within self, +yielded in reverse order along with the index of the match.

+

For matches of pat within self that overlap, only the indices +corresponding to the last match are returned.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the match_indices method can be used.

+
Examples
+
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
+assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
+
+let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
+assert_eq!(v, [(4, "abc"), (1, "abc")]);
+
+let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
+assert_eq!(v, [(2, "aba")]); // only the last `aba`
+
1.0.0

pub fn trim(&self) -> &str

Returns a string slice with leading and trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Examples
+
let s = "\n Hello\tworld\t\n";
+
+assert_eq!("Hello\tworld", s.trim());
+
1.30.0

pub fn trim_start(&self) -> &str

Returns a string slice with leading whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Text directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
Examples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("Hello\tworld\t\n", s.trim_start());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('E') == s.trim_start().chars().next());
+
+let s = "  עברית  ";
+assert!(Some('ע') == s.trim_start().chars().next());
+
1.30.0

pub fn trim_end(&self) -> &str

Returns a string slice with trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Text directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
Examples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("\n Hello\tworld", s.trim_end());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('h') == s.trim_end().chars().rev().next());
+
+let s = "  עברית  ";
+assert!(Some('ת') == s.trim_end().chars().rev().next());
+
1.0.0

pub fn trim_left(&self) -> &str

👎Deprecated since 1.33.0: superseded by trim_start

Returns a string slice with leading whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
Text directionality
+

A string is a sequence of bytes. ‘Left’ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the right side, not the left.

+
Examples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!("Hello\tworld\t", s.trim_left());
+

Directionality:

+ +
let s = "  English";
+assert!(Some('E') == s.trim_left().chars().next());
+
+let s = "  עברית";
+assert!(Some('ע') == s.trim_left().chars().next());
+
1.0.0

pub fn trim_right(&self) -> &str

👎Deprecated since 1.33.0: superseded by trim_end

Returns a string slice with trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
Text directionality
+

A string is a sequence of bytes. ‘Right’ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the left side, not the right.

+
Examples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!(" Hello\tworld", s.trim_right());
+

Directionality:

+ +
let s = "English  ";
+assert!(Some('h') == s.trim_right().chars().rev().next());
+
+let s = "עברית  ";
+assert!(Some('ת') == s.trim_right().chars().rev().next());
+
1.0.0

pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,

Returns a string slice with all prefixes and suffixes that match a +pattern repeatedly removed.

+

The pattern can be a char, a slice of chars, or a function +or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
+assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
+
1.30.0

pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>,

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
Examples
+
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
+
1.45.0

pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>where + P: Pattern<'a>,

Returns a string slice with the prefix removed.

+

If the string starts with the pattern prefix, returns substring after the prefix, wrapped +in Some. Unlike trim_start_matches, this method removes the prefix exactly once.

+

If the string does not start with prefix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
+assert_eq!("foo:bar".strip_prefix("bar"), None);
+assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
+
1.45.0

pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns a string slice with the suffix removed.

+

If the string ends with the pattern suffix, returns the substring before the suffix, +wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.

+

If the string does not end with suffix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
+assert_eq!("bar:foo".strip_suffix("bar"), None);
+assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
+
1.30.0

pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.0.0

pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>,

👎Deprecated since 1.33.0: superseded by trim_start_matches

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. ‘Left’ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the right side, not the left.

+
Examples
+
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
+
1.0.0

pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

👎Deprecated since 1.33.0: superseded by trim_end_matches

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. ‘Right’ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the left side, not the right.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.0.0

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where + F: FromStr,

Parses this string slice into another type.

+

Because parse is so general, it can cause problems with type +inference. As such, parse is one of the few times you’ll see +the syntax affectionately known as the ‘turbofish’: ::<>. This +helps the inference algorithm understand specifically which type +you’re trying to parse into.

+

parse can parse into any type that implements the [FromStr] trait.

+
Errors
+

Will return Err if it’s not possible to parse this string slice into +the desired type.

+
Examples
+

Basic usage

+ +
let four: u32 = "4".parse().unwrap();
+
+assert_eq!(4, four);
+

Using the ‘turbofish’ instead of annotating four:

+ +
let four = "4".parse::<u32>();
+
+assert_eq!(Ok(4), four);
+

Failing to parse:

+ +
let nope = "j".parse::<u32>();
+
+assert!(nope.is_err());
+
1.23.0

pub fn is_ascii(&self) -> bool

Checks if all characters in this string are within the ASCII range.

+
Examples
+
let ascii = "hello!\n";
+let non_ascii = "Grüße, Jürgen ❤";
+
+assert!(ascii.is_ascii());
+assert!(!non_ascii.is_ascii());
+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this string slice is_ascii, returns it as a slice +of ASCII characters, otherwise returns None.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &str) -> bool

Checks that two strings are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
Examples
+
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
+assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
+assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
+
1.23.0

pub fn make_ascii_uppercase(&mut self)

Converts this string to its ASCII upper case equivalent in-place.

+

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, +but non-ASCII letters are unchanged.

+

To return a new uppercased value without modifying the existing one, use +to_ascii_uppercase().

+
Examples
+
let mut s = String::from("Grüße, Jürgen ❤");
+
+s.make_ascii_uppercase();
+
+assert_eq!("GRüßE, JüRGEN ❤", s);
+
1.23.0

pub fn make_ascii_lowercase(&mut self)

Converts this string to its ASCII lower case equivalent in-place.

+

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, +but non-ASCII letters are unchanged.

+

To return a new lowercased value without modifying the existing one, use +to_ascii_lowercase().

+
Examples
+
let mut s = String::from("GRÜßE, JÜRGEN ❤");
+
+s.make_ascii_lowercase();
+
+assert_eq!("grÜße, jÜrgen ❤", s);
+
1.34.0

pub fn escape_debug(&self) -> EscapeDebug<'_>

Return an iterator that escapes each char in self with [char::escape_debug].

+

Note: only extended grapheme codepoints that begin the string will be +escaped.

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_debug() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_debug());
+

Both are equivalent to:

+ +
println!("❤\\n!");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
+
1.34.0

pub fn escape_default(&self) -> EscapeDefault<'_>

Return an iterator that escapes each char in self with [char::escape_default].

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_default() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_default());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\n!");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
+
1.34.0

pub fn escape_unicode(&self) -> EscapeUnicode<'_>

Return an iterator that escapes each char in self with [char::escape_unicode].

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_unicode() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_unicode());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
+

Trait Implementations§

source§

impl<const N: usize> AsRef<[u8]> for String<N>

source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize> AsRef<str> for String<N>

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize> Clone for String<N>

source§

fn clone(&self) -> String<N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<const N: usize> Debug for String<N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<const N: usize> Default for String<N>

source§

fn default() -> String<N>

Returns the “default value” for a type. Read more
source§

impl<const N: usize> Deref for String<N>

§

type Target = str

The resulting type after dereferencing.
source§

fn deref(&self) -> &str

Dereferences the value.
source§

impl<const N: usize> DerefMut for String<N>

source§

fn deref_mut(&mut self) -> &mut str

Mutably dereferences the value.
source§

impl<const N: usize> Display for String<N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<'a, const N: usize> From<&'a str> for String<N>

source§

fn from(s: &'a str) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i16> for String<N>

source§

fn from(s: i16) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i32> for String<N>

source§

fn from(s: i32) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i64> for String<N>

source§

fn from(s: i64) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i8> for String<N>

source§

fn from(s: i8) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u16> for String<N>

source§

fn from(s: u16) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u32> for String<N>

source§

fn from(s: u32) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u64> for String<N>

source§

fn from(s: u64) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u8> for String<N>

source§

fn from(s: u8) -> String<N>

Converts to this type from the input type.
source§

impl<'a, const N: usize> FromIterator<&'a char> for String<N>

source§

fn from_iter<T>(iter: T) -> String<N>where + T: IntoIterator<Item = &'a char>,

Creates a value from an iterator. Read more
source§

impl<'a, const N: usize> FromIterator<&'a str> for String<N>

source§

fn from_iter<T>(iter: T) -> String<N>where + T: IntoIterator<Item = &'a str>,

Creates a value from an iterator. Read more
source§

impl<const N: usize> FromIterator<char> for String<N>

source§

fn from_iter<T>(iter: T) -> String<N>where + T: IntoIterator<Item = char>,

Creates a value from an iterator. Read more
source§

impl<const N: usize> FromStr for String<N>

§

type Err = ()

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<String<N>, <String<N> as FromStr>::Err>

Parses a string s to return a value of this type. Read more
source§

impl<const N: usize> Hash for String<N>

source§

fn hash<H>(&self, hasher: &mut H)where + H: Hasher,

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl<const N: usize> Hash for String<N>

source§

fn hash<H>(&self, hasher: &mut H)where + H: Hasher,

Feeds this value into the given Hasher.
source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.
source§

impl<const N: usize> Ord for String<N>

source§

fn cmp(&self, other: &String<N>) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<const N: usize> PartialEq<&str> for String<N>

source§

fn eq(&self, other: &&str) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &&str) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<String<N>> for &str

source§

fn eq(&self, other: &String<N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &String<N>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<String<N>> for str

source§

fn eq(&self, other: &String<N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &String<N>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N1: usize, const N2: usize> PartialEq<String<N2>> for String<N1>

source§

fn eq(&self, rhs: &String<N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, rhs: &String<N2>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<str> for String<N>

source§

fn eq(&self, other: &str) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &str) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N1: usize, const N2: usize> PartialOrd<String<N2>> for String<N1>

source§

fn partial_cmp(&self, other: &String<N2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl<const N: usize> Write for String<N>

source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write +succeeded. Read more
source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a [char] into this writer, returning whether the write succeeded. Read more
1.0.0§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the [write!] macro with implementors of this trait. Read more
source§

impl<const N: usize> Eq for String<N>

Auto Trait Implementations§

§

impl<const N: usize> RefUnwindSafe for String<N>

§

impl<const N: usize> Send for String<N>

§

impl<const N: usize> Sync for String<N>

§

impl<const N: usize> Unpin for String<N>

§

impl<const N: usize> UnwindSafe for String<N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.VacantEntry.html b/docs/doc/arduboy_rust/heapless/struct.VacantEntry.html new file mode 100644 index 0000000..82844a1 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.VacantEntry.html @@ -0,0 +1,24 @@ +VacantEntry in arduboy_rust::heapless - Rust
pub struct VacantEntry<'a, K, V, const N: usize> { /* private fields */ }
Expand description

A view into an empty slot in the underlying map

+

Implementations§

source§

impl<'a, K, V, const N: usize> VacantEntry<'a, K, V, N>where + K: Eq + Hash,

source

pub fn key(&self) -> &K

Get the key associated with this entry

+
source

pub fn into_key(self) -> K

Consumes this entry to yield to key associated with it

+
source

pub fn insert(self, value: V) -> Result<&'a mut V, V>

Inserts this entry into to underlying map, yields a mutable reference to the inserted value. +If the map is at capacity the value is returned instead.

+

Auto Trait Implementations§

§

impl<'a, K, V, const N: usize> RefUnwindSafe for VacantEntry<'a, K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<'a, K, V, const N: usize> Send for VacantEntry<'a, K, V, N>where + K: Send, + V: Send,

§

impl<'a, K, V, const N: usize> Sync for VacantEntry<'a, K, V, N>where + K: Sync, + V: Sync,

§

impl<'a, K, V, const N: usize> Unpin for VacantEntry<'a, K, V, N>where + K: Unpin,

§

impl<'a, K, V, const N: usize> !UnwindSafe for VacantEntry<'a, K, V, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/struct.Vec.html b/docs/doc/arduboy_rust/heapless/struct.Vec.html new file mode 100644 index 0000000..3367040 --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/struct.Vec.html @@ -0,0 +1,2527 @@ +Vec in arduboy_rust::heapless - Rust

Struct arduboy_rust::heapless::Vec

source ·
pub struct Vec<T, const N: usize> { /* private fields */ }
Expand description

A fixed capacity Vec

+

Examples

+
use heapless::Vec;
+
+
+// A vector with a fixed capacity of 8 elements allocated on the stack
+let mut vec = Vec::<_, 8>::new();
+vec.push(1);
+vec.push(2);
+
+assert_eq!(vec.len(), 2);
+assert_eq!(vec[0], 1);
+
+assert_eq!(vec.pop(), Some(2));
+assert_eq!(vec.len(), 1);
+
+vec[0] = 7;
+assert_eq!(vec[0], 7);
+
+vec.extend([1, 2, 3].iter().cloned());
+
+for x in &vec {
+    println!("{}", x);
+}
+assert_eq!(*vec, [7, 1, 2, 3]);
+

Implementations§

source§

impl<T, const N: usize> Vec<T, N>

source

pub const fn new() -> Vec<T, N>

Constructs a new, empty vector with a fixed capacity of N

+
Examples
+
use heapless::Vec;
+
+// allocate the vector on the stack
+let mut x: Vec<u8, 16> = Vec::new();
+
+// allocate the vector in a static variable
+static mut X: Vec<u8, 16> = Vec::new();
+

Vec const constructor; wrap the returned value in Vec

+
source

pub fn from_slice(other: &[T]) -> Result<Vec<T, N>, ()>where + T: Clone,

Constructs a new vector with a fixed capacity of N and fills it +with the provided slice.

+

This is equivalent to the following code:

+ +
use heapless::Vec;
+
+let mut v: Vec<u8, 16> = Vec::new();
+v.extend_from_slice(&[1, 2, 3]).unwrap();
+
source

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the vector’s buffer.

+
source

pub fn as_mut_ptr(&mut self) -> *mut T

Returns a raw pointer to the vector’s buffer, which may be mutated through.

+
source

pub fn as_slice(&self) -> &[T]

Extracts a slice containing the entire vector.

+

Equivalent to &s[..].

+
Examples
+
use heapless::Vec;
+let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
+
source

pub fn into_array<const M: usize>(self) -> Result<[T; M], Vec<T, N>>

Returns the contents of the vector as an array of length M if the length +of the vector is exactly M, otherwise returns Err(self).

+
Examples
+
use heapless::Vec;
+let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+let array: [u8; 5] = buffer.into_array().unwrap();
+assert_eq!(array, [1, 2, 3, 5, 8]);
+
source

pub const fn capacity(&self) -> usize

Returns the maximum number of elements the vector can hold.

+
source

pub fn clear(&mut self)

Clears the vector, removing all values.

+
source

pub fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends the vec from an iterator.

+
Panic
+

Panics if the vec cannot hold all elements of the iterator.

+
source

pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>where + T: Clone,

Clones and appends all elements in a slice to the Vec.

+

Iterates over the slice other, clones each element, and then appends +it to this Vec. The other vector is traversed in-order.

+
Examples
+
use heapless::Vec;
+
+let mut vec = Vec::<u8, 8>::new();
+vec.push(1).unwrap();
+vec.extend_from_slice(&[2, 3, 4]).unwrap();
+assert_eq!(*vec, [1, 2, 3, 4]);
+
source

pub fn pop(&mut self) -> Option<T>

Removes the last element from a vector and returns it, or None if it’s empty

+
source

pub fn push(&mut self, item: T) -> Result<(), T>

Appends an item to the back of the collection

+

Returns back the item if the vector is full

+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Removes the last element from a vector and returns it

+
Safety
+

This assumes the vec to have at least one element.

+
source

pub unsafe fn push_unchecked(&mut self, item: T)

Appends an item to the back of the collection

+
Safety
+

This assumes the vec is not full.

+
source

pub fn truncate(&mut self, len: usize)

Shortens the vector, keeping the first len elements and dropping the rest.

+
source

pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>where + T: Clone,

Resizes the Vec in-place so that len is equal to new_len.

+

If new_len is greater than len, the Vec is extended by the +difference, with each additional slot filled with value. If +new_len is less than len, the Vec is simply truncated.

+

See also resize_default.

+
source

pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>where + T: Clone + Default,

Resizes the Vec in-place so that len is equal to new_len.

+

If new_len is greater than len, the Vec is extended by the +difference, with each additional slot filled with Default::default(). +If new_len is less than len, the Vec is simply truncated.

+

See also resize.

+
source

pub unsafe fn set_len(&mut self, new_len: usize)

Forces the length of the vector to new_len.

+

This is a low-level operation that maintains none of the normal +invariants of the type. Normally changing the length of a vector +is done using one of the safe operations instead, such as +truncate, resize, extend, or clear.

+
Safety
+
    +
  • new_len must be less than or equal to capacity().
  • +
  • The elements at old_len..new_len must be initialized.
  • +
+
Examples
+

This method can be useful for situations in which the vector +is serving as a buffer for other code, particularly over FFI:

+ +
use heapless::Vec;
+
+pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
+    // Per the FFI method's docs, "32768 bytes is always enough".
+    let mut dict = Vec::new();
+    let mut dict_length = 0;
+    // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
+    // 1. `dict_length` elements were initialized.
+    // 2. `dict_length` <= the capacity (32_768)
+    // which makes `set_len` safe to call.
+    unsafe {
+        // Make the FFI call...
+        let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
+        if r == Z_OK {
+            // ...and update the length to what was initialized.
+            dict.set_len(dict_length);
+            Some(dict)
+        } else {
+            None
+        }
+    }
+}
+

While the following example is sound, there is a memory leak since +the inner vectors were not freed prior to the set_len call:

+ +
use core::iter::FromIterator;
+use heapless::Vec;
+
+let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
+    [
+        Vec::from_iter([1, 0, 0].iter().cloned()),
+        Vec::from_iter([0, 1, 0].iter().cloned()),
+        Vec::from_iter([0, 0, 1].iter().cloned()),
+    ]
+    .iter()
+    .cloned()
+);
+// SAFETY:
+// 1. `old_len..0` is empty so no elements need to be initialized.
+// 2. `0 <= capacity` always holds whatever `capacity` is.
+unsafe {
+    vec.set_len(0);
+}
+

Normally, here, one would use clear instead to correctly drop +the contents and thus not leak memory.

+
source

pub fn swap_remove(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

+

The removed element is replaced by the last element of the vector.

+

This does not preserve ordering, but is O(1).

+
Panics
+

Panics if index is out of bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::new();
+v.push("foo").unwrap();
+v.push("bar").unwrap();
+v.push("baz").unwrap();
+v.push("qux").unwrap();
+
+assert_eq!(v.swap_remove(1), "bar");
+assert_eq!(&*v, ["foo", "qux", "baz"]);
+
+assert_eq!(v.swap_remove(0), "foo");
+assert_eq!(&*v, ["baz", "qux"]);
+
source

pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

+

The removed element is replaced by the last element of the vector.

+

This does not preserve ordering, but is O(1).

+
Safety
+

Assumes index within bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::new();
+v.push("foo").unwrap();
+v.push("bar").unwrap();
+v.push("baz").unwrap();
+v.push("qux").unwrap();
+
+assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
+assert_eq!(&*v, ["foo", "qux", "baz"]);
+
+assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
+assert_eq!(&*v, ["baz", "qux"]);
+
source

pub fn is_full(&self) -> bool

Returns true if the vec is full

+
source

pub fn is_empty(&self) -> bool

Returns true if the vec is empty

+
source

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the Vec.

+

Always returns true if needle is an empty slice.

+
Examples
+
use heapless::Vec;
+
+let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+assert_eq!(v.starts_with(b""), true);
+assert_eq!(v.starts_with(b"ab"), true);
+assert_eq!(v.starts_with(b"bc"), false);
+
source

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the Vec.

+

Always returns true if needle is an empty slice.

+
Examples
+
use heapless::Vec;
+
+let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+assert_eq!(v.ends_with(b""), true);
+assert_eq!(v.ends_with(b"ab"), false);
+assert_eq!(v.ends_with(b"bc"), true);
+
source

pub fn insert(&mut self, index: usize, element: T) -> Result<(), T>

Inserts an element at position index within the vector, shifting all +elements after it to the right.

+

Returns back the element if the vector is full.

+
Panics
+

Panics if index > len.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+vec.insert(1, 4);
+assert_eq!(vec, [1, 4, 2, 3]);
+vec.insert(4, 5);
+assert_eq!(vec, [1, 4, 2, 3, 5]);
+
source

pub fn remove(&mut self, index: usize) -> T

Removes and returns the element at position index within the vector, +shifting all elements after it to the left.

+

Note: Because this shifts over the remaining elements, it has a +worst-case performance of O(n). If you don’t need the order of +elements to be preserved, use swap_remove instead. If you’d like to +remove elements from the beginning of the Vec, consider using +Deque::pop_front instead.

+
Panics
+

Panics if index is out of bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+assert_eq!(v.remove(1), 2);
+assert_eq!(v, [1, 3]);
+
source

pub fn retain<F>(&mut self, f: F)where + F: FnMut(&T) -> bool,

Retains only the elements specified by the predicate.

+

In other words, remove all elements e for which f(&e) returns false. +This method operates in place, visiting each element exactly once in the +original order, and preserves the order of the retained elements.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+vec.retain(|&x| x % 2 == 0);
+assert_eq!(vec, [2, 4]);
+

Because the elements are visited exactly once in the original order, +external state may be used to decide which elements to keep.

+ +
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4, 5]).unwrap();
+let keep = [false, true, true, false, true];
+let mut iter = keep.iter();
+vec.retain(|_| *iter.next().unwrap());
+assert_eq!(vec, [2, 3, 5]);
+
source

pub fn retain_mut<F>(&mut self, f: F)where + F: FnMut(&mut T) -> bool,

Retains only the elements specified by the predicate, passing a mutable reference to it.

+

In other words, remove all elements e such that f(&mut e) returns false. +This method operates in place, visiting each element exactly once in the +original order, and preserves the order of the retained elements.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+vec.retain_mut(|x| if *x <= 3 {
+    *x += 1;
+    true
+} else {
+    false
+});
+assert_eq!(vec, [2, 3, 4]);
+

Methods from Deref<Target = [T]>§

1.23.0

pub fn is_ascii(&self) -> bool

Checks if all bytes in this slice are within the ASCII range.

+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this slice is_ascii, returns it as a slice of +ASCII characters, otherwise returns None.

+

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this slice of bytes into a slice of ASCII characters, +without checking whether they’re valid.

+
Safety
+

Every byte in the slice must be in 0..=127, or else this is UB.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool

Checks that two slices are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
1.23.0

pub fn make_ascii_uppercase(&mut self)

Converts this slice to its ASCII upper case equivalent in-place.

+

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, +but non-ASCII letters are unchanged.

+

To return a new uppercased value without modifying the existing one, use +to_ascii_uppercase.

+
1.23.0

pub fn make_ascii_lowercase(&mut self)

Converts this slice to its ASCII lower case equivalent in-place.

+

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, +but non-ASCII letters are unchanged.

+

To return a new lowercased value without modifying the existing one, use +to_ascii_lowercase.

+
1.60.0

pub fn escape_ascii(&self) -> EscapeAscii<'_>

Returns an iterator that produces an escaped version of this slice, +treating it as an ASCII string.

+
Examples
+

+let s = b"0\t\r\n'\"\\\x9d";
+let escaped = s.escape_ascii().to_string();
+assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
+

pub fn trim_ascii_start(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
+assert_eq!(b"  ".trim_ascii_start(), b"");
+assert_eq!(b"".trim_ascii_start(), b"");
+

pub fn trim_ascii_end(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with trailing ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
+assert_eq!(b"  ".trim_ascii_end(), b"");
+assert_eq!(b"".trim_ascii_end(), b"");
+

pub fn trim_ascii(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading and trailing ASCII whitespace bytes +removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
+assert_eq!(b"  ".trim_ascii(), b"");
+assert_eq!(b"".trim_ascii(), b"");
+

pub fn as_str(&self) -> &str

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a UTF-8 str.

+

pub fn as_bytes(&self) -> &[u8]

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a slice of u8 bytes.

+

pub fn flatten(&self) -> &[T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &[[T; N]], and flattens it to a &[T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
+
+assert_eq!(
+    [[1, 2, 3], [4, 5, 6]].flatten(),
+    [[1, 2], [3, 4], [5, 6]].flatten(),
+);
+
+let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
+assert!(slice_of_empty_arrays.flatten().is_empty());
+
+let empty_slice_of_arrays: &[[u32; 10]] = &[];
+assert!(empty_slice_of_arrays.flatten().is_empty());
+

pub fn flatten_mut(&mut self) -> &mut [T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &mut [[T; N]], and flattens it to a &mut [T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+fn add_5_to_all(slice: &mut [i32]) {
+    for i in slice {
+        *i += 5;
+    }
+}
+
+let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
+add_5_to_all(array.flatten_mut());
+assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
+
1.0.0

pub fn len(&self) -> usize

Returns the number of elements in the slice.

+
Examples
+
let a = [1, 2, 3];
+assert_eq!(a.len(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if the slice has a length of 0.

+
Examples
+
let a = [1, 2, 3];
+assert!(!a.is_empty());
+
1.0.0

pub fn first(&self) -> Option<&T>

Returns the first element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&10), v.first());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.first());
+
1.0.0

pub fn first_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the first element of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(first) = x.first_mut() {
+    *first = 5;
+}
+assert_eq!(x, &[5, 1, 2]);
+
1.5.0

pub fn split_first(&self) -> Option<(&T, &[T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first() {
+    assert_eq!(first, &0);
+    assert_eq!(elements, &[1, 2]);
+}
+
1.5.0

pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_mut() {
+    *first = 3;
+    elements[0] = 4;
+    elements[1] = 5;
+}
+assert_eq!(x, &[3, 4, 5]);
+
1.5.0

pub fn split_last(&self) -> Option<(&T, &[T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last() {
+    assert_eq!(last, &2);
+    assert_eq!(elements, &[0, 1]);
+}
+
1.5.0

pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_mut() {
+    *last = 3;
+    elements[0] = 4;
+    elements[1] = 5;
+}
+assert_eq!(x, &[4, 5, 3]);
+
1.0.0

pub fn last(&self) -> Option<&T>

Returns the last element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&30), v.last());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.last());
+
1.0.0

pub fn last_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the last item in the slice.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(last) = x.last_mut() {
+    *last = 10;
+}
+assert_eq!(x, &[0, 1, 10]);
+

pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice, or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.first_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.first_chunk::<0>());
+

pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable reference to the first N elements of the slice, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some(first) = x.first_chunk_mut::<2>() {
+    first[0] = 5;
+    first[1] = 4;
+}
+assert_eq!(x, &[5, 4, 2]);
+

pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk::<2>() {
+    assert_eq!(first, &[0, 1]);
+    assert_eq!(elements, &[2]);
+}
+

pub fn split_first_chunk_mut<const N: usize>( + &mut self +) -> Option<(&mut [T; N], &mut [T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable reference to the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
+    first[0] = 3;
+    first[1] = 4;
+    elements[0] = 5;
+}
+assert_eq!(x, &[3, 4, 5]);
+

pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk::<2>() {
+    assert_eq!(last, &[1, 2]);
+    assert_eq!(elements, &[0]);
+}
+

pub fn split_last_chunk_mut<const N: usize>( + &mut self +) -> Option<(&mut [T; N], &mut [T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk_mut::<2>() {
+    last[0] = 3;
+    last[1] = 4;
+    elements[0] = 5;
+}
+assert_eq!(x, &[5, 3, 4]);
+

pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last element of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.last_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.last_chunk::<0>());
+

pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable pointer to the last item in the slice.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some(last) = x.last_chunk_mut::<2>() {
+    last[0] = 10;
+    last[1] = 20;
+}
+assert_eq!(x, &[0, 10, 20]);
+
1.0.0

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a reference to an element or subslice depending on the type of +index.

+
    +
  • If given a position, returns a reference to the element at that +position or None if out of bounds.
  • +
  • If given a range, returns the subslice corresponding to that range, +or None if out of bounds.
  • +
+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&40), v.get(1));
+assert_eq!(Some(&[10, 40][..]), v.get(0..2));
+assert_eq!(None, v.get(3));
+assert_eq!(None, v.get(0..4));
+
1.0.0

pub fn get_mut<I>( + &mut self, + index: I +) -> Option<&mut <I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice depending on the +type of index (see get) or None if the index is out of bounds.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(elem) = x.get_mut(1) {
+    *elem = 42;
+}
+assert_eq!(x, &[0, 42, 2]);
+
1.0.0

pub unsafe fn get_unchecked<I>( + &self, + index: I +) -> &<I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a reference to an element or subslice, without doing bounds +checking.

+

For a safe alternative see get.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &[1, 2, 4];
+
+unsafe {
+    assert_eq!(x.get_unchecked(1), &2);
+}
+
1.0.0

pub unsafe fn get_unchecked_mut<I>( + &mut self, + index: I +) -> &mut <I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice, without doing +bounds checking.

+

For a safe alternative see get_mut.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &mut [1, 2, 4];
+
+unsafe {
+    let elem = x.get_unchecked_mut(1);
+    *elem = 13;
+}
+assert_eq!(x, &[1, 13, 4]);
+
1.0.0

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

The caller must also ensure that the memory the pointer (non-transitively) points to +is never written to (except inside an UnsafeCell) using this pointer or any pointer +derived 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 +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &[1, 2, 4];
+let x_ptr = x.as_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
+    }
+}
+
1.0.0

pub fn as_mut_ptr(&mut self) -> *mut T

Returns an unsafe mutable pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

Modifying the container referenced by this slice may cause its buffer +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &mut [1, 2, 4];
+let x_ptr = x.as_mut_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        *x_ptr.add(i) += 2;
+    }
+}
+assert_eq!(x, &[3, 4, 6]);
+
1.48.0

pub fn as_ptr_range(&self) -> Range<*const T>

Returns the two raw pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_ptr for warnings on using these pointers. The end pointer +requires extra caution, as it does not point to a valid element in the +slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+

It can also be useful to check if a pointer to an element refers to an +element of this slice:

+ +
let a = [1, 2, 3];
+let x = &a[1] as *const _;
+let y = &5 as *const _;
+
+assert!(a.as_ptr_range().contains(&x));
+assert!(!a.as_ptr_range().contains(&y));
+
1.48.0

pub fn as_mut_ptr_range(&mut self) -> Range<*mut T>

Returns the two unsafe mutable pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_mut_ptr for warnings on using these pointers. The end +pointer requires extra caution, as it does not point to a valid element +in the slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+
1.0.0

pub fn swap(&mut self, a: usize, b: usize)

Swaps two elements in the slice.

+

If a equals to b, it’s guaranteed that elements won’t change value.

+
Arguments
+
    +
  • a - The index of the first element
  • +
  • b - The index of the second element
  • +
+
Panics
+

Panics if a or b are out of bounds.

+
Examples
+
let mut v = ["a", "b", "c", "d", "e"];
+v.swap(2, 4);
+assert!(v == ["a", "b", "e", "d", "c"]);
+

pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)

🔬This is a nightly-only experimental API. (slice_swap_unchecked)

Swaps two elements in the slice, without doing bounds checking.

+

For a safe alternative see swap.

+
Arguments
+
    +
  • a - The index of the first element
  • +
  • b - The index of the second element
  • +
+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior. +The caller has to ensure that a < self.len() and b < self.len().

+
Examples
+
#![feature(slice_swap_unchecked)]
+
+let mut v = ["a", "b", "c", "d"];
+// SAFETY: we know that 1 and 3 are both indices of the slice
+unsafe { v.swap_unchecked(1, 3) };
+assert!(v == ["a", "d", "c", "b"]);
+
1.0.0

pub fn reverse(&mut self)

Reverses the order of elements in the slice, in place.

+
Examples
+
let mut v = [1, 2, 3];
+v.reverse();
+assert!(v == [3, 2, 1]);
+
1.0.0

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the slice.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &[1, 2, 4];
+let mut iterator = x.iter();
+
+assert_eq!(iterator.next(), Some(&1));
+assert_eq!(iterator.next(), Some(&2));
+assert_eq!(iterator.next(), Some(&4));
+assert_eq!(iterator.next(), None);
+
1.0.0

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns an iterator that allows modifying each value.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &mut [1, 2, 4];
+for elem in x.iter_mut() {
+    *elem += 2;
+}
+assert_eq!(x, &[3, 4, 6]);
+
1.0.0

pub fn windows(&self, size: usize) -> Windows<'_, T>

Returns an iterator over all contiguous windows of length +size. The windows overlap. If the slice is shorter than +size, the iterator returns no values.

+
Panics
+

Panics if size is 0.

+
Examples
+
let slice = ['r', 'u', 's', 't'];
+let mut iter = slice.windows(2);
+assert_eq!(iter.next().unwrap(), &['r', 'u']);
+assert_eq!(iter.next().unwrap(), &['u', 's']);
+assert_eq!(iter.next().unwrap(), &['s', 't']);
+assert!(iter.next().is_none());
+

If the slice is shorter than size:

+ +
let slice = ['f', 'o', 'o'];
+let mut iter = slice.windows(4);
+assert!(iter.next().is_none());
+

There’s no windows_mut, as that existing would let safe code violate the +“only one &mut at a time to the same thing” rule. However, you can sometimes +use Cell::as_slice_of_cells in +conjunction with windows to accomplish something similar:

+ +
use std::cell::Cell;
+
+let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
+let slice = &mut array[..];
+let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
+for w in slice_of_cells.windows(3) {
+    Cell::swap(&w[0], &w[2]);
+}
+assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
+
1.0.0

pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and rchunks for the same iterator but starting at the end of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert_eq!(iter.next().unwrap(), &['m']);
+assert!(iter.next().is_none());
+
1.0.0

pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length 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 +exactly chunk_size elements, and rchunks_mut for the same iterator but starting at +the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.chunks_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 3]);
+
1.31.0

pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of chunks.

+

See chunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and rchunks_exact for the same iterator but starting at the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+
1.31.0

pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length of the slice, then the last up to chunk_size-1 elements will be omitted and can be +retrieved from the into_remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting 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 +smaller chunk, and rchunks_exact_mut for the same iterator but starting at the end of +the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.chunks_exact_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 0]);
+

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &[[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &[[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
+

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (chunks, remainder) = slice.as_chunks();
+assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
+assert_eq!(remainder, &['m']);
+

If you expect the slice to be an exact multiple, you can combine +let-else with an empty slice pattern:

+ +
#![feature(slice_as_chunks)]
+let slice = ['R', 'u', 's', 't'];
+let (chunks, []) = slice.as_chunks::<2>() else {
+    panic!("slice didn't have even length")
+};
+assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
+

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (remainder, chunks) = slice.as_rchunks();
+assert_eq!(remainder, &['l']);
+assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
+

pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are array references and do not overlap. If N does not divide the +length of the slice, then the last up to N-1 elements will be omitted and can be +retrieved from the remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.array_chunks();
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub unsafe fn as_chunks_unchecked_mut<const N: usize>( + &mut self +) -> &mut [[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &mut [[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked_mut() };
+chunks[0] = ['L'];
+assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &mut [[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked_mut() };
+chunks[1] = ['a', 'x', '?'];
+assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
+

pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+let (chunks, remainder) = v.as_chunks_mut();
+remainder[0] = 9;
+for chunk in chunks {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 9]);
+

pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+let (remainder, chunks) = v.as_rchunks_mut();
+remainder[0] = 9;
+for chunk in chunks {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[9, 1, 1, 2, 2]);
+

pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable array references and do not overlap. If N does not divide +the length of the slice, then the last up to N-1 elements will be omitted and +can be retrieved from the into_remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact_mut.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.array_chunks_mut() {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 0]);
+

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>

🔬This is a nightly-only experimental API. (array_windows)

Returns an iterator over overlapping windows of N elements of a slice, +starting 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
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_windows)]
+let slice = [0, 1, 2, 3];
+let mut iter = slice.array_windows();
+assert_eq!(iter.next().unwrap(), &[0, 1]);
+assert_eq!(iter.next().unwrap(), &[1, 2]);
+assert_eq!(iter.next().unwrap(), &[2, 3]);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and chunks for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert_eq!(iter.next().unwrap(), &['l']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length 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 +exactly chunk_size elements, and chunks_mut for the same iterator but starting at the +beginning of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.rchunks_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[3, 2, 2, 1, 1]);
+
1.31.0

pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +end of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of rchunks.

+

See rchunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and chunks_exact for the same iterator but starting at the beginning of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['l']);
+
1.31.0

pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length of the slice, then the last up to chunk_size-1 elements will be omitted and can be +retrieved from the into_remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting 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 +smaller chunk, and chunks_exact_mut for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.rchunks_exact_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[0, 2, 2, 1, 1]);
+

pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping runs +of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&[3, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+

pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping mutable +runs of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by_mut(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&mut [3, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by_mut(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+
1.0.0

pub fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let v = [1, 2, 3, 4, 5, 6];
+
+{
+   let (left, right) = v.split_at(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+
1.0.0

pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])

Divides one mutable slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let mut v = [1, 0, 3, 0, 5, 6];
+let (left, right) = v.split_at_mut(2);
+assert_eq!(left, [1, 0]);
+assert_eq!(right, [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let v = [1, 2, 3, 4, 5, 6];
+
+unsafe {
+   let (left, right) = v.split_at_unchecked(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub unsafe fn split_at_mut_unchecked( + &mut self, + mid: usize +) -> (&mut [T], &mut [T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one mutable slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at_mut.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let mut v = [1, 0, 3, 0, 5, 6];
+// scoped to restrict the lifetime of the borrows
+unsafe {
+    let (left, right) = v.split_at_mut_unchecked(2);
+    assert_eq!(left, [1, 0]);
+    assert_eq!(right, [3, 0, 5, 6]);
+    left[1] = 2;
+    right[1] = 4;
+}
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.split_array_ref::<0>();
+   assert_eq!(left, &[]);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<2>();
+    assert_eq!(left, &[1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<6>();
+    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T])

🔬This is a nightly-only experimental API. (split_array)

Divides one mutable slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let mut v = &mut [1, 0, 3, 0, 5, 6][..];
+let (left, right) = v.split_array_mut::<2>();
+assert_eq!(left, &mut [1, 0]);
+assert_eq!(right, [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index from +the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index len - N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.rsplit_array_ref::<0>();
+   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+   assert_eq!(right, &[]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<2>();
+    assert_eq!(left, [1, 2, 3, 4]);
+    assert_eq!(right, &[5, 6]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<6>();
+    assert_eq!(left, []);
+    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
+}
+

pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one mutable slice into an array and a remainder slice at an +index from the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let mut v = &mut [1, 0, 3, 0, 5, 6][..];
+let (left, right) = v.rsplit_array_mut::<4>();
+assert_eq!(left, [1, 0]);
+assert_eq!(right, &mut [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+
1.0.0

pub fn split<F>(&self, pred: F) -> Split<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is not contained in the subslices.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the first element is matched, an empty slice will be the first item +returned by the iterator. Similarly, if the last element in the slice +is matched, an empty slice will be the last item returned by the +iterator:

+ +
let slice = [10, 40, 33];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert!(iter.next().is_none());
+

If two matched elements are directly adjacent, an empty slice will be +present between them:

+ +
let slice = [10, 6, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+
1.0.0

pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred. The matched element is not contained in the subslices.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.split_mut(|num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(v, [1, 40, 30, 1, 60, 1]);
+
1.51.0

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is contained in the end of the previous +subslice as a terminator.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the last element of the slice is matched, +that element will be considered the terminator of the preceding slice. +That slice will be the last item returned by the iterator.

+ +
let slice = [3, 10, 40, 33];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[3]);
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert!(iter.next().is_none());
+
1.51.0

pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred. The matched element is contained in the previous +subslice as a terminator.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
+    let terminator_idx = group.len()-1;
+    group[terminator_idx] = 1;
+}
+assert_eq!(v, [10, 40, 1, 20, 1, 1]);
+
1.27.0

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, starting at the end of the slice and working backwards. +The matched element is not contained in the subslices.

+
Examples
+
let slice = [11, 22, 33, 0, 44, 55];
+let mut iter = slice.rsplit(|num| *num == 0);
+
+assert_eq!(iter.next().unwrap(), &[44, 55]);
+assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
+assert_eq!(iter.next(), None);
+

As with split(), if the first or last element is matched, an empty +slice will be the first (or last) item returned by the iterator.

+ +
let v = &[0, 1, 1, 2, 3, 5, 8];
+let mut it = v.rsplit(|n| *n % 2 == 0);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next().unwrap(), &[3, 5]);
+assert_eq!(it.next().unwrap(), &[1, 1]);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next(), None);
+
1.27.0

pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred, starting at the end of the slice and working +backwards. The matched element is not contained in the subslices.

+
Examples
+
let mut v = [100, 400, 300, 200, 600, 500];
+
+let mut count = 0;
+for group in v.rsplit_mut(|num| *num % 3 == 0) {
+    count += 1;
+    group[0] = count;
+}
+assert_eq!(v, [3, 400, 300, 2, 600, 1]);
+
1.0.0

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once by numbers divisible by 3 (i.e., [10, 40], +[20, 60, 50]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn_mut(2, |num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(v, [1, 40, 30, 1, 60, 50]);
+
1.0.0

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once, starting from the end, by numbers divisible +by 3 (i.e., [50], [10, 40, 30, 20]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.rsplitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+
let mut s = [10, 40, 30, 20, 60, 50];
+
+for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(s, [1, 40, 30, 20, 60, 1]);
+
1.0.0

pub fn contains(&self, x: &T) -> boolwhere + T: PartialEq<T>,

Returns true if the slice contains an element with the given value.

+

This operation is O(n).

+

Note that if you have a sorted slice, binary_search may be faster.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.contains(&30));
+assert!(!v.contains(&50));
+

If you do not have a &T, but some other value that you can compare +with one (for example, String implements PartialEq<str>), you can +use iter().any:

+ +
let v = [String::from("hello"), String::from("world")]; // slice of `String`
+assert!(v.iter().any(|e| e == "hello")); // search with `&str`
+assert!(!v.iter().any(|e| e == "hi"));
+
1.0.0

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.starts_with(&[10]));
+assert!(v.starts_with(&[10, 40]));
+assert!(!v.starts_with(&[50]));
+assert!(!v.starts_with(&[10, 50]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.starts_with(&[]));
+let v: &[u8] = &[];
+assert!(v.starts_with(&[]));
+
1.0.0

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.ends_with(&[30]));
+assert!(v.ends_with(&[40, 30]));
+assert!(!v.ends_with(&[50]));
+assert!(!v.ends_with(&[50, 30]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.ends_with(&[]));
+let v: &[u8] = &[];
+assert!(v.ends_with(&[]));
+
1.51.0

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the prefix removed.

+

If the slice starts with prefix, returns the subslice after the prefix, wrapped in Some. +If prefix is empty, simply returns the original slice.

+

If the slice does not start with prefix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
+assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
+assert_eq!(v.strip_prefix(&[50]), None);
+assert_eq!(v.strip_prefix(&[10, 50]), None);
+
+let prefix : &str = "he";
+assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
+           Some(b"llo".as_ref()));
+
1.51.0

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the suffix removed.

+

If the slice ends with suffix, returns the subslice before the suffix, wrapped in Some. +If suffix is empty, simply returns the original slice.

+

If the slice does not end with suffix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
+assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
+assert_eq!(v.strip_suffix(&[50]), None);
+assert_eq!(v.strip_suffix(&[50, 30]), None);
+

Binary searches this slice for a given element. +If the slice is not sorted, the returned result is unspecified and +meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search_by, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+assert_eq!(s.binary_search(&13),  Ok(9));
+assert_eq!(s.binary_search(&4),   Err(7));
+assert_eq!(s.binary_search(&100), Err(13));
+let r = s.binary_search(&1);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+

If you want to find that whole range of matching items, rather than +an 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];
+
+let low = s.partition_point(|x| x < &1);
+assert_eq!(low, 1);
+let high = s.partition_point(|x| x <= &1);
+assert_eq!(high, 5);
+let r = s.binary_search(&1);
+assert!((low..high).contains(&r.unwrap()));
+
+assert!(s[..low].iter().all(|&x| x < 1));
+assert!(s[low..high].iter().all(|&x| x == 1));
+assert!(s[high..].iter().all(|&x| x > 1));
+
+// For something not found, the "range" of equal items is empty
+assert_eq!(s.partition_point(|x| x < &11), 9);
+assert_eq!(s.partition_point(|x| x <= &11), 9);
+assert_eq!(s.binary_search(&11), Err(9));
+

If you want to insert an item to a sorted vector, while maintaining +sort order, consider using partition_point:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+
1.0.0

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where + F: FnMut(&'a T) -> Ordering,

Binary searches this slice with a comparator function.

+

The comparator function should return an order code that indicates +whether its argument is Less, Equal or Greater the desired +target. +If the slice is not sorted or if the comparator function does not +implement an order consistent with the sort order of the underlying +slice, the returned result is unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+let seek = 13;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
+let seek = 4;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
+let seek = 100;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
+let seek = 1;
+let r = s.binary_search_by(|probe| probe.cmp(&seek));
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.10.0

pub fn binary_search_by_key<'a, B, F>( + &'a self, + b: &B, + f: F +) -> Result<usize, usize>where + F: FnMut(&'a T) -> B, + B: Ord,

Binary searches this slice with a key extraction function.

+

Assumes that the slice is sorted by the key, for instance with +sort_by_key using the same key extraction function. +If the slice is not sorted by the key, the returned result is +unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by, and partition_point.

+
Examples
+

Looks up a series of four elements in a slice of pairs sorted by +their second elements. The first is found, with a uniquely +determined position; the second and third are not found; the +fourth could match any position in [1, 4].

+ +
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
+         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
+         (1, 21), (2, 34), (4, 55)];
+
+assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
+assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
+assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
+let r = s.binary_search_by_key(&1, |&(a, b)| b);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.20.0

pub fn sort_unstable(&mut self)where + T: Ord,

Sorts the slice, but might not preserve the order of equal elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(n * log(n)) worst-case.

+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

It is typically faster than stable sorting, except in a few special cases, e.g., when the +slice consists of several concatenated sorted sequences.

+
Examples
+
let mut v = [-5, 4, 1, -3, 2];
+
+v.sort_unstable();
+assert!(v == [-5, -3, 1, 2, 4]);
+
1.20.0

pub fn sort_unstable_by<F>(&mut self, compare: F)where + F: FnMut(&T, &T) -> Ordering,

Sorts the slice with a comparator function, but might not preserve the order of equal +elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(n * log(n)) worst-case.

+

The comparator function must define a total ordering for the elements in the slice. If +the ordering is not total, the order of the elements is unspecified. An order is a +total order if it is (for all a, b and c):

+
    +
  • total and antisymmetric: exactly one of a < b, a == b or a > b is true, and
  • +
  • transitive, a < b and b < c implies a < c. The same must hold for both == and >.
  • +
+

For example, while [f64] doesn’t implement [Ord] because NaN != NaN, we can use +partial_cmp as our sort function when we know the slice doesn’t contain a NaN.

+ +
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
+floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
+assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

It is typically faster than stable sorting, except in a few special cases, e.g., when the +slice consists of several concatenated sorted sequences.

+
Examples
+
let mut v = [5, 4, 1, 3, 2];
+v.sort_unstable_by(|a, b| a.cmp(b));
+assert!(v == [1, 2, 3, 4, 5]);
+
+// reverse sorting
+v.sort_unstable_by(|a, b| b.cmp(a));
+assert!(v == [5, 4, 3, 2, 1]);
+
1.20.0

pub fn sort_unstable_by_key<K, F>(&mut self, f: F)where + F: FnMut(&T) -> K, + K: Ord,

Sorts the slice with a key extraction function, but might not preserve the order of equal +elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(m * n * log(n)) worst-case, where the key function is +O(m).

+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

Due to its key calling strategy, sort_unstable_by_key +is likely to be slower than sort_by_cached_key in +cases where the key function is expensive.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+v.sort_unstable_by_key(|k| k.abs());
+assert!(v == [1, 2, -3, 4, -5]);
+
1.49.0

pub fn select_nth_unstable( + &mut self, + index: usize +) -> (&mut [T], &mut T, &mut [T])where + T: Ord,

Reorder the slice such that the element at index is at its final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index. Additionally, this reordering is +unstable (i.e. any number of equal elements may end up at position index), in-place +(i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from the reordered slice: +the subslice prior to index, the element at index, and the subslice after index; +accordingly, the values in those two subslices will respectively all be less-than-or-equal-to +and greater-than-or-equal-to the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Find the median
+v.select_nth_unstable(2);
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [-3, -5, 1, 2, 4] ||
+        v == [-5, -3, 1, 2, 4] ||
+        v == [-3, -5, 1, 4, 2] ||
+        v == [-5, -3, 1, 4, 2]);
+
1.49.0

pub fn select_nth_unstable_by<F>( + &mut self, + index: usize, + compare: F +) -> (&mut [T], &mut T, &mut [T])where + F: FnMut(&T, &T) -> Ordering,

Reorder the slice with a comparator function such that the element at index is at its +final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index using the comparator function. +Additionally, this reordering is unstable (i.e. any number of equal elements may end up at +position index), in-place (i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from +the slice reordered according to the provided comparator function: the subslice prior to +index, the element at index, and the subslice after index; accordingly, the values in +those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to +the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Find the median as if the slice were sorted in descending order.
+v.select_nth_unstable_by(2, |a, b| b.cmp(a));
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [2, 4, 1, -5, -3] ||
+        v == [2, 4, 1, -3, -5] ||
+        v == [4, 2, 1, -5, -3] ||
+        v == [4, 2, 1, -3, -5]);
+
1.49.0

pub fn select_nth_unstable_by_key<K, F>( + &mut self, + index: usize, + f: F +) -> (&mut [T], &mut T, &mut [T])where + F: FnMut(&T) -> K, + K: Ord,

Reorder the slice with a key extraction function such that the element at index is at its +final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index using the key extraction function. +Additionally, this reordering is unstable (i.e. any number of equal elements may end up at +position index), in-place (i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from +the slice reordered according to the provided key extraction function: the subslice prior to +index, the element at index, and the subslice after index; accordingly, the values in +those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to +the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Return the median as if the array were sorted according to absolute value.
+v.select_nth_unstable_by_key(2, |a| a.abs());
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [1, 2, -3, 4, -5] ||
+        v == [1, 2, -3, -5, 4] ||
+        v == [2, 1, -3, 4, -5] ||
+        v == [2, 1, -3, -5, 4]);
+

pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where + T: PartialEq<T>,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all consecutive repeated elements to the end of the slice according to the +[PartialEq] trait implementation.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
+
+let (dedup, duplicates) = slice.partition_dedup();
+
+assert_eq!(dedup, [1, 2, 3, 2, 1]);
+assert_eq!(duplicates, [2, 3, 1]);
+

pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])where + F: FnMut(&mut T, &mut T) -> bool,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice satisfying +a given equality relation.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

The same_bucket function is passed references to two elements from the slice and +must determine if the elements compare equal. The elements are passed in opposite order +from their order in the slice, so if same_bucket(a, b) returns true, a is moved +at the end of the slice.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
+
+let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
+
+assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
+assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
+

pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])where + F: FnMut(&mut T) -> K, + K: PartialEq<K>,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice that resolve +to the same key.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
+
+let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
+
+assert_eq!(dedup, [10, 20, 30, 20, 11]);
+assert_eq!(duplicates, [21, 30, 13]);
+
1.26.0

pub fn rotate_left(&mut self, mid: usize)

Rotates the slice in-place such that the first mid elements of the +slice move to the end while the last self.len() - mid elements move to +the front. After calling rotate_left, the element previously at index +mid will become the first element in the slice.

+
Panics
+

This function will panic if mid is greater than the length of the +slice. Note that mid == self.len() does not panic and is a no-op +rotation.

+
Complexity
+

Takes linear (in self.len()) time.

+
Examples
+
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a.rotate_left(2);
+assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
+

Rotating a subslice:

+ +
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a[1..5].rotate_left(1);
+assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
+
1.26.0

pub fn rotate_right(&mut self, k: usize)

Rotates the slice in-place such that the first self.len() - k +elements of the slice move to the end while the last k elements move +to the front. After calling rotate_right, the element previously at +index self.len() - k will become the first element in the slice.

+
Panics
+

This function will panic if k is greater than the length of the +slice. Note that k == self.len() does not panic and is a no-op +rotation.

+
Complexity
+

Takes linear (in self.len()) time.

+
Examples
+
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a.rotate_right(2);
+assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
+

Rotate a subslice:

+ +
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a[1..5].rotate_right(1);
+assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
+
1.50.0

pub fn fill(&mut self, value: T)where + T: Clone,

Fills self with elements by cloning value.

+
Examples
+
let mut buf = vec![0; 10];
+buf.fill(1);
+assert_eq!(buf, vec![1; 10]);
+
1.51.0

pub fn fill_with<F>(&mut self, f: F)where + F: FnMut() -> T,

Fills self with elements returned by calling a closure repeatedly.

+

This method uses a closure to create new values. If you’d rather +[Clone] a given value, use fill. If you want to use the [Default] +trait to generate values, you can pass [Default::default] as the +argument.

+
Examples
+
let mut buf = vec![1; 10];
+buf.fill_with(Default::default);
+assert_eq!(buf, vec![0; 10]);
+
1.7.0

pub fn clone_from_slice(&mut self, src: &[T])where + T: Clone,

Copies the elements from src into self.

+

The length of src must be the same as self.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Examples
+

Cloning two elements from a slice into another:

+ +
let src = [1, 2, 3, 4];
+let mut dst = [0, 0];
+
+// Because the slices have to be the same length,
+// we slice the source slice from four elements
+// to two. It will panic if we don't do this.
+dst.clone_from_slice(&src[2..]);
+
+assert_eq!(src, [1, 2, 3, 4]);
+assert_eq!(dst, [3, 4]);
+

Rust enforces that there can only be one mutable reference with no +immutable references to a particular piece of data in a particular +scope. Because of this, attempting to use clone_from_slice on a +single slice will result in a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+slice[..2].clone_from_slice(&slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.clone_from_slice(&right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 4, 5]);
+
1.9.0

pub fn copy_from_slice(&mut self, src: &[T])where + T: Copy,

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.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Examples
+

Copying two elements from a slice into another:

+ +
let src = [1, 2, 3, 4];
+let mut dst = [0, 0];
+
+// Because the slices have to be the same length,
+// we slice the source slice from four elements
+// to two. It will panic if we don't do this.
+dst.copy_from_slice(&src[2..]);
+
+assert_eq!(src, [1, 2, 3, 4]);
+assert_eq!(dst, [3, 4]);
+

Rust enforces that there can only be one mutable reference with no +immutable references to a particular piece of data in a particular +scope. Because of this, attempting to use copy_from_slice on a +single slice will result in a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+slice[..2].copy_from_slice(&slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.copy_from_slice(&right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 4, 5]);
+
1.37.0

pub fn copy_within<R>(&mut self, src: R, dest: usize)where + R: RangeBounds<usize>, + T: Copy,

Copies elements from one part of the slice to another part of itself, +using a memmove.

+

src is the range within self to copy from. dest is the starting +index of the range within self to copy to, which will have the same +length as src. The two ranges may overlap. The ends of the two ranges +must be less than or equal to self.len().

+
Panics
+

This function will panic if either range exceeds the end of the slice, +or if the end of src is before the start.

+
Examples
+

Copying four bytes within a slice:

+ +
let mut bytes = *b"Hello, World!";
+
+bytes.copy_within(1..5, 8);
+
+assert_eq!(&bytes, b"Hello, Wello!");
+
1.27.0

pub fn swap_with_slice(&mut self, other: &mut [T])

Swaps all elements in self with those in other.

+

The length of other must be the same as self.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Example
+

Swapping two elements across slices:

+ +
let mut slice1 = [0, 0];
+let mut slice2 = [1, 2, 3, 4];
+
+slice1.swap_with_slice(&mut slice2[2..]);
+
+assert_eq!(slice1, [3, 4]);
+assert_eq!(slice2, [1, 2, 0, 0]);
+

Rust enforces that there can only be one mutable reference to a +particular piece of data in a particular scope. Because of this, +attempting to use swap_with_slice on a single slice will result in +a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +mutable sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.swap_with_slice(&mut right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 1, 2]);
+
1.30.0

pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])

Transmute the slice to a slice of another type, ensuring alignment of the types is +maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+
1.30.0

pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])

Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the +types is maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])where + Simd<T, LANES>: AsRef<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

+

This is a safe wrapper around [slice::align_to], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+
Examples
+
#![feature(portable_simd)]
+use core::simd::SimdFloat;
+
+let short = &[1, 2, 3];
+let (prefix, middle, suffix) = short.as_simd::<4>();
+assert_eq!(middle, []); // Not enough elements for anything in the middle
+
+// They might be split in any possible way between prefix and suffix
+let it = prefix.iter().chain(suffix).copied();
+assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
+
+fn basic_simd_sum(x: &[f32]) -> f32 {
+    use std::ops::Add;
+    use std::simd::f32x4;
+    let (prefix, middle, suffix) = x.as_simd();
+    let sums = f32x4::from_array([
+        prefix.iter().copied().sum(),
+        0.0,
+        0.0,
+        suffix.iter().copied().sum(),
+    ]);
+    let sums = middle.iter().copied().fold(sums, f32x4::add);
+    sums.reduce_sum()
+}
+
+let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
+assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
+

pub fn as_simd_mut<const LANES: usize>( + &mut self +) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])where + Simd<T, LANES>: AsMut<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, +and a mutable suffix.

+

This is a safe wrapper around [slice::align_to_mut], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+

This is the mutable version of [slice::as_simd]; see that for examples.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+

pub fn is_sorted(&self) -> boolwhere + T: PartialOrd<T>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted.

+

That is, for each element a and its following element b, a <= b must hold. If the +slice yields exactly zero or one element, true is returned.

+

Note that if Self::Item is only PartialOrd, but not Ord, the above definition +implies that this function returns false if any two consecutive items are not +comparable.

+
Examples
+
#![feature(is_sorted)]
+let empty: [i32; 0] = [];
+
+assert!([1, 2, 2, 9].is_sorted());
+assert!(![1, 3, 2, 4].is_sorted());
+assert!([0].is_sorted());
+assert!(empty.is_sorted());
+assert!(![0.0, 1.0, f32::NAN].is_sorted());
+

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> boolwhere + F: FnMut(&'a T, &'a T) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given comparator function.

+

Instead of using PartialOrd::partial_cmp, this function uses the given compare +function to determine the ordering of two elements. Apart from that, it’s equivalent to +is_sorted; see its documentation for more information.

+

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> boolwhere + F: FnMut(&'a T) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given key extraction function.

+

Instead of comparing the slice’s elements directly, this function compares the keys of the +elements, as determined by f. Apart from that, it’s equivalent to is_sorted; see its +documentation for more information.

+
Examples
+
#![feature(is_sorted)]
+
+assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
+assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
+
1.52.0

pub fn partition_point<P>(&self, pred: P) -> usizewhere + P: FnMut(&T) -> bool,

Returns the index of the partition point according to the given predicate +(the index of the first element of the second partition).

+

The slice is assumed to be partitioned according to the given predicate. +This means that all elements for which the predicate returns true are at the start of the slice +and all elements for which the predicate returns false are at the end. +For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 +(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, +as this method performs a kind of binary search.

+

See also binary_search, binary_search_by, and binary_search_by_key.

+
Examples
+
let v = [1, 2, 3, 3, 5, 6, 7];
+let i = v.partition_point(|&x| x < 5);
+
+assert_eq!(i, 4);
+assert!(v[..i].iter().all(|&x| x < 5));
+assert!(v[i..].iter().all(|&x| !(x < 5)));
+

If all elements of the slice match the predicate, including if the slice +is empty, then the length of the slice will be returned:

+ +
let a = [2, 4, 8];
+assert_eq!(a.partition_point(|x| x < &100), a.len());
+let a: [i32; 0] = [];
+assert_eq!(a.partition_point(|x| x < &100), 0);
+

If you want to insert an item to a sorted vector, while maintaining +sort order:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+

pub fn take<R, 'a>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where + R: OneSidedRange<usize>,

🔬This is a nightly-only experimental API. (slice_take)

Removes the subslice corresponding to the given range +and returns a reference to it.

+

Returns None and does not modify the slice if the given +range is out of bounds.

+

Note that this method only accepts one-sided ranges such as +2.. or ..6, but not 2..6.

+
Examples
+

Taking the first three elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+let mut first_three = slice.take(..3).unwrap();
+
+assert_eq!(slice, &['d']);
+assert_eq!(first_three, &['a', 'b', 'c']);
+

Taking the last two elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+let mut tail = slice.take(2..).unwrap();
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(tail, &['c', 'd']);
+

Getting None when range is out of bounds:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+
+assert_eq!(None, slice.take(5..));
+assert_eq!(None, slice.take(..5));
+assert_eq!(None, slice.take(..=4));
+let expected: &[char] = &['a', 'b', 'c', 'd'];
+assert_eq!(Some(expected), slice.take(..4));
+

pub fn take_mut<R, 'a>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>where + R: OneSidedRange<usize>,

🔬This is a nightly-only experimental API. (slice_take)

Removes the subslice corresponding to the given range +and returns a mutable reference to it.

+

Returns None and does not modify the slice if the given +range is out of bounds.

+

Note that this method only accepts one-sided ranges such as +2.. or ..6, but not 2..6.

+
Examples
+

Taking the first three elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+let mut first_three = slice.take_mut(..3).unwrap();
+
+assert_eq!(slice, &mut ['d']);
+assert_eq!(first_three, &mut ['a', 'b', 'c']);
+

Taking the last two elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+let mut tail = slice.take_mut(2..).unwrap();
+
+assert_eq!(slice, &mut ['a', 'b']);
+assert_eq!(tail, &mut ['c', 'd']);
+

Getting None when range is out of bounds:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+
+assert_eq!(None, slice.take_mut(5..));
+assert_eq!(None, slice.take_mut(..5));
+assert_eq!(None, slice.take_mut(..=4));
+let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+assert_eq!(Some(expected), slice.take_mut(..4));
+

pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the first element of the slice and returns a reference +to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c'];
+let first = slice.take_first().unwrap();
+
+assert_eq!(slice, &['b', 'c']);
+assert_eq!(first, &'a');
+

pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the first element of the slice and returns a mutable +reference to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
+let first = slice.take_first_mut().unwrap();
+*first = 'd';
+
+assert_eq!(slice, &['b', 'c']);
+assert_eq!(first, &'d');
+

pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the last element of the slice and returns a reference +to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c'];
+let last = slice.take_last().unwrap();
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(last, &'c');
+

pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the last element of the slice and returns a mutable +reference to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
+let last = slice.take_last_mut().unwrap();
+*last = 'd';
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(last, &'d');
+

pub unsafe fn get_many_unchecked_mut<const N: usize>( + &mut self, + indices: [usize; N] +) -> [&mut T; N]

🔬This is a nightly-only experimental API. (get_many_mut)

Returns mutable references to many indices at once, without doing any checks.

+

For a safe alternative see get_many_mut.

+
Safety
+

Calling this method with overlapping or out-of-bounds indices is undefined behavior +even if the resulting references are not used.

+
Examples
+
#![feature(get_many_mut)]
+
+let x = &mut [1, 2, 4];
+
+unsafe {
+    let [a, b] = x.get_many_unchecked_mut([0, 2]);
+    *a *= 10;
+    *b *= 100;
+}
+assert_eq!(x, &[10, 2, 400]);
+

pub fn get_many_mut<const N: usize>( + &mut self, + indices: [usize; N] +) -> Result<[&mut T; N], GetManyMutError<N>>

🔬This is a nightly-only experimental API. (get_many_mut)

Returns mutable references to many indices at once.

+

Returns an error if any index is out-of-bounds, or if the same index was +passed more than once.

+
Examples
+
#![feature(get_many_mut)]
+
+let v = &mut [1, 2, 3];
+if let Ok([a, b]) = v.get_many_mut([0, 2]) {
+    *a = 413;
+    *b = 612;
+}
+assert_eq!(v, &[413, 2, 612]);
+

pub fn sort_floats(&mut self)

🔬This is a nightly-only experimental API. (sort_floats)

Sorts the slice of floats.

+

This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses +the ordering defined by [f32::total_cmp].

+
Current implementation
+

This uses the same sorting algorithm as sort_unstable_by.

+
Examples
+
#![feature(sort_floats)]
+let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
+
+v.sort_floats();
+let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
+assert_eq!(&v[..8], &sorted[..8]);
+assert!(v[8].is_nan());
+

pub fn sort_floats(&mut self)

🔬This is a nightly-only experimental API. (sort_floats)

Sorts the slice of floats.

+

This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses +the ordering defined by [f64::total_cmp].

+
Current implementation
+

This uses the same sorting algorithm as sort_unstable_by.

+
Examples
+
#![feature(sort_floats)]
+let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
+
+v.sort_floats();
+let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
+assert_eq!(&v[..8], &sorted[..8]);
+assert!(v[8].is_nan());
+

Trait Implementations§

source§

impl<T, const N: usize> AsMut<[T]> for Vec<T, N>

source§

fn as_mut(&mut self) -> &mut [T]

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N>

source§

fn as_mut(&mut self) -> &mut Vec<T, N>

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsRef<[T]> for Vec<T, N>

source§

fn as_ref(&self) -> &[T]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N>

source§

fn as_ref(&self) -> &Vec<T, N>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> Clone for Vec<T, N>where + T: Clone,

source§

fn clone(&self) -> Vec<T, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, const N: usize> Debug for Vec<T, N>where + T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for Vec<T, N>

source§

fn default() -> Vec<T, N>

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Deref for Vec<T, N>

§

type Target = [T]

The resulting type after dereferencing.
source§

fn deref(&self) -> &[T]

Dereferences the value.
source§

impl<T, const N: usize> DerefMut for Vec<T, N>

source§

fn deref_mut(&mut self) -> &mut [T]

Mutably dereferences the value.
source§

impl<T, const N: usize> Drop for Vec<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>where + T: 'a + Copy,

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> Extend<T> for Vec<T, N>

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> FromIterator<T> for Vec<T, N>

source§

fn from_iter<I>(iter: I) -> Vec<T, N>where + I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
source§

impl<T, const N: usize> Hash for Vec<T, N>where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl<T, const N: usize> Hash for Vec<T, N>where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

Feeds this value into the given Hasher.
source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.
source§

impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a Vec<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a mut Vec<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> IntoIterator for Vec<T, N>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <Vec<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> Ord for Vec<T, N>where + T: Ord,

source§

fn cmp(&self, other: &Vec<T, N>) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&[B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&[B; M]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&mut [B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &[B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &[B; M]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<B, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>where + T: PartialOrd<T>,

source§

fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl<'a, T, const N: usize> TryFrom<&'a [T]> for Vec<T, N>where + T: Clone,

§

type Error = ()

The type returned in the event of a conversion error.
source§

fn try_from( + slice: &'a [T] +) -> Result<Vec<T, N>, <Vec<T, N> as TryFrom<&'a [T]>>::Error>

Performs the conversion.
source§

impl<const N: usize> Write for Vec<u8, N>

source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write +succeeded. Read more
1.1.0§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a [char] into this writer, returning whether the write succeeded. Read more
1.0.0§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the [write!] macro with implementors of this trait. Read more
source§

impl<T, const N: usize> Eq for Vec<T, N>where + T: Eq,

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for Vec<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for Vec<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for Vec<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for Vec<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for Vec<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/type.FnvIndexMap.html b/docs/doc/arduboy_rust/heapless/type.FnvIndexMap.html new file mode 100644 index 0000000..ba644ee --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/type.FnvIndexMap.html @@ -0,0 +1,38 @@ +FnvIndexMap in arduboy_rust::heapless - Rust

Type Definition arduboy_rust::heapless::FnvIndexMap

source ·
pub type FnvIndexMap<K, V, const N: usize> = IndexMap<K, V, BuildHasherDefault<Hasher>, N>;
Expand description

A heapless::IndexMap using the default FNV hasher

+

A list of all Methods and Traits available for FnvIndexMap can be found in +the heapless::IndexMap documentation.

+

Examples

+
use heapless::FnvIndexMap;
+
+// A hash map with a capacity of 16 key-value pairs allocated on the stack
+let mut book_reviews = FnvIndexMap::<_, _, 16>::new();
+
+// review some books.
+book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.").unwrap();
+book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.").unwrap();
+book_reviews.insert("Pride and Prejudice",               "Very enjoyable.").unwrap();
+book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.").unwrap();
+
+// check for a specific one.
+if !book_reviews.contains_key("Les Misérables") {
+    println!("We've got {} reviews, but Les Misérables ain't one.",
+             book_reviews.len());
+}
+
+// oops, this review has a lot of spelling mistakes, let's delete it.
+book_reviews.remove("The Adventures of Sherlock Holmes");
+
+// look up the values associated with some keys.
+let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
+for book in &to_find {
+    match book_reviews.get(book) {
+        Some(review) => println!("{}: {}", book, review),
+        None => println!("{} is unreviewed.", book)
+    }
+}
+
+// iterate over everything.
+for (book, review) in &book_reviews {
+    println!("{}: \"{}\"", book, review);
+}
+
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/heapless/type.FnvIndexSet.html b/docs/doc/arduboy_rust/heapless/type.FnvIndexSet.html new file mode 100644 index 0000000..9f032bc --- /dev/null +++ b/docs/doc/arduboy_rust/heapless/type.FnvIndexSet.html @@ -0,0 +1,30 @@ +FnvIndexSet in arduboy_rust::heapless - Rust

Type Definition arduboy_rust::heapless::FnvIndexSet

source ·
pub type FnvIndexSet<T, const N: usize> = IndexSet<T, BuildHasherDefault<Hasher>, N>;
Expand description

A heapless::IndexSet using the +default FNV hasher. +A list of all Methods and Traits available for FnvIndexSet can be found in +the heapless::IndexSet documentation.

+

Examples

+
use heapless::FnvIndexSet;
+
+// A hash set with a capacity of 16 elements allocated on the stack
+let mut books = FnvIndexSet::<_, 16>::new();
+
+// Add some books.
+books.insert("A Dance With Dragons").unwrap();
+books.insert("To Kill a Mockingbird").unwrap();
+books.insert("The Odyssey").unwrap();
+books.insert("The Great Gatsby").unwrap();
+
+// Check for a specific one.
+if !books.contains("The Winds of Winter") {
+    println!("We have {} books, but The Winds of Winter ain't one.",
+             books.len());
+}
+
+// Remove a book.
+books.remove("The Odyssey");
+
+// Iterate over everything.
+for book in &books {
+    println!("{}", book);
+}
+
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/index.html b/docs/doc/arduboy_rust/index.html index b2c70f2..5ac54d6 100644 --- a/docs/doc/arduboy_rust/index.html +++ b/docs/doc/arduboy_rust/index.html @@ -1,4 +1,4 @@ -arduboy_rust - Rust

Crate arduboy_rust

source ·
Expand description

This is the arduboy_rust crate +arduboy_rust - Rust

Crate arduboy_rust

source ·
Expand description

This is the arduboy_rust crate To get started import the prelude to your project.

Import the module:

@@ -18,4 +18,4 @@ Just comment the unused library definition out.

To get an idea, the ArduboyTones Library needs additional 2-3% of the flash memory.

Here is the link to the GitHub Repo

-

Modules

  • This is the Module to interact in a save way with the Arduboy2 C++ library.
  • This is the Module to interact in a save way with the ArduboyTones C++ library.
  • This is the Module to interact in a save way with the Arduino C++ library.
  • Clib functions you can use on the Arduboy
  • This is the Module to interact in a save way with the Arduboy hardware.
  • This is the important one to use this library effective in your project
  • This is the module to interact in a save way with the Sprites C++ library.

Macros

  • This is the way to go if you want print some random text
  • Create a const raw pointer to a sprite as u8, without creating an intermediate reference.
  • Create a const raw pointer to a [u8;_] that saves text, without creating an intermediate reference.
  • Create a const raw pointer to a sprite as u16, without creating an intermediate reference.
  • Create a space for Progmem variable

Structs

  • This is the struct to interact in a save way with the Arduboy2 C++ library.
  • This is the struct to interact in a save way with the ArduboyTones C++ library.
  • This is the struct to store and read structs objects to/from eeprom memory.
  • Use this struct to store and read single bytes to/from eeprom memory.

Enums

  • This item is to chose between Black or White

Constants

  • The standard font size of the arduboy
  • The standard height of the arduboy
  • The standard width of the arduboy
\ No newline at end of file +

Modules

  • This is the Module to interact in a save way with the Arduboy2 C++ library.
  • This is the Module to interact in a save way with the ArduboyTones C++ library.
  • This is the Module to interact in a save way with the Arduino C++ library.
  • Clib functions you can use on the Arduboy
  • This is the Module to interact in a save way with the Arduboy hardware.
  • static friendly data structures that don’t require dynamic memory allocation
  • This is the important one to use this library effective in your project
  • This is the module to interact in a save way with the Sprites C++ library.

Macros

  • This is the way to go if you want print some random text
  • Create a const raw pointer to a sprite as u8, without creating an intermediate reference.
  • Create a const raw pointer to a [u8;_] that saves text, without creating an intermediate reference.
  • Create a const raw pointer to a sprite as u16, without creating an intermediate reference.
  • Create a space for Progmem variable

Structs

  • This is the struct to interact in a save way with the Arduboy2 C++ library.
  • This is the struct to interact in a save way with the ArduboyTones C++ library.
  • This is the struct to store and read structs objects to/from eeprom memory.
  • Use this struct to store and read single bytes to/from eeprom memory.

Enums

  • This item is to chose between Black or White

Constants

  • The standard font size of the arduboy
  • The standard height of the arduboy
  • The standard width of the arduboy
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/macro.f.html b/docs/doc/arduboy_rust/macro.f.html index 2238e52..f92f937 100644 --- a/docs/doc/arduboy_rust/macro.f.html +++ b/docs/doc/arduboy_rust/macro.f.html @@ -1,4 +1,4 @@ -f in arduboy_rust - Rust

Macro arduboy_rust::f

source ·
macro_rules! f {
+f in arduboy_rust - Rust

Macro arduboy_rust::f

source ·
macro_rules! f {
     ($string_literal:literal) => { ... };
 }
Expand description

This is the way to go if you want print some random text

This doesn’t waste the 2kb ram it saves to progmem (28kb) diff --git a/docs/doc/arduboy_rust/macro.get_sprite_addr.html b/docs/doc/arduboy_rust/macro.get_sprite_addr.html index 4219a79..52c4559 100644 --- a/docs/doc/arduboy_rust/macro.get_sprite_addr.html +++ b/docs/doc/arduboy_rust/macro.get_sprite_addr.html @@ -1,4 +1,4 @@ -get_sprite_addr in arduboy_rust - Rust

macro_rules! get_sprite_addr {
+get_sprite_addr in arduboy_rust - Rust
macro_rules! get_sprite_addr {
     ( $s:expr ) => { ... };
 }
Expand description

Create a const raw pointer to a sprite as u8, without creating an intermediate reference.

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/macro.get_string_addr.html b/docs/doc/arduboy_rust/macro.get_string_addr.html index 17514b1..005da09 100644 --- a/docs/doc/arduboy_rust/macro.get_string_addr.html +++ b/docs/doc/arduboy_rust/macro.get_string_addr.html @@ -1,4 +1,4 @@ -get_string_addr in arduboy_rust - Rust
macro_rules! get_string_addr {
+get_string_addr in arduboy_rust - Rust
macro_rules! get_string_addr {
     ( $s:expr ) => { ... };
 }
Expand description

Create a const raw pointer to a [u8;_] that saves text, without creating an intermediate reference.

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/macro.get_tones_addr.html b/docs/doc/arduboy_rust/macro.get_tones_addr.html index 6e5b67b..cab6573 100644 --- a/docs/doc/arduboy_rust/macro.get_tones_addr.html +++ b/docs/doc/arduboy_rust/macro.get_tones_addr.html @@ -1,4 +1,4 @@ -get_tones_addr in arduboy_rust - Rust
macro_rules! get_tones_addr {
+get_tones_addr in arduboy_rust - Rust
macro_rules! get_tones_addr {
     ( $s:expr ) => { ... };
 }
Expand description

Create a const raw pointer to a sprite as u16, without creating an intermediate reference.

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/macro.progmem.html b/docs/doc/arduboy_rust/macro.progmem.html index 1c4851f..e5ef149 100644 --- a/docs/doc/arduboy_rust/macro.progmem.html +++ b/docs/doc/arduboy_rust/macro.progmem.html @@ -1,9 +1,24 @@ -progmem in arduboy_rust - Rust

Macro arduboy_rust::progmem

source ·
macro_rules! progmem {
+progmem in arduboy_rust - Rust

Macro arduboy_rust::progmem

source ·
macro_rules! progmem {
     (
         $( #[$attr:meta] )*
         $v:vis $id:ident $name:ident: [$ty:ty; _] = $value:expr;
         $($rest:tt)*
     ) => { ... };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident mut $name:ident: [$ty:ty; _] = $value:expr;
+        $($rest:tt)*
+    ) => { ... };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident $name:ident: $ty:ty = $value:expr;
+        $($rest:tt)*
+    ) => { ... };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident mut $name:ident: $ty:ty = $value:expr;
+        $($rest:tt)*
+    ) => { ... };
     () => { ... };
 }
Expand description

Create a space for Progmem variable

Example

@@ -20,5 +35,10 @@ //for for bitmap progmem!( static image: [u8; _] = [8, 8, 0x81, 0x00, 0x12, 0x40, 0x04, 0x11, 0x00, 0x04]; +); + +// for a Vector +progmem!( + static mut walls: Vec<Player, 100> = Vec::new(); );
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/fn.constrain.html b/docs/doc/arduboy_rust/prelude/fn.constrain.html index fb8b2cd..c64fd20 100644 --- a/docs/doc/arduboy_rust/prelude/fn.constrain.html +++ b/docs/doc/arduboy_rust/prelude/fn.constrain.html @@ -1 +1 @@ -constrain in arduboy_rust::prelude - Rust
pub fn constrain<T: Ord>(x: T, a: T, b: T) -> T
\ No newline at end of file +constrain in arduboy_rust::prelude - Rust
pub fn constrain<T: Ord>(x: T, a: T, b: T) -> T
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/index.html b/docs/doc/arduboy_rust/prelude/index.html index 0d02efb..e1afcea 100644 --- a/docs/doc/arduboy_rust/prelude/index.html +++ b/docs/doc/arduboy_rust/prelude/index.html @@ -1,7 +1,7 @@ -arduboy_rust::prelude - Rust

Module arduboy_rust::prelude

source ·
Expand description

This is the important one to use this library effective in your project

+arduboy_rust::prelude - Rust

Module arduboy_rust::prelude

source ·
Expand description

This is the important one to use this library effective in your project

Import the module:

use arduboy_rust::prelude::*;
-

Modules

  • This is the Module to interact in a save way with the Arduboy2 C++ library.
  • This is the Module to interact in a save way with the ArduboyTones C++ library.
  • A list of all six buttons available on the Arduboy
  • A list of all LED variables available
  • This is the module to interact in a save way with the Sprites C++ library.

Macros

  • This is the way to go if you want print some random text
  • Create a const raw pointer to a sprite as u8, without creating an intermediate reference.
  • Create a const raw pointer to a [u8;_] that saves text, without creating an intermediate reference.
  • Create a const raw pointer to a sprite as u16, without creating an intermediate reference.
  • Create a space for Progmem variable

Structs

  • This is the struct to interact in a save way with the Arduboy2 C++ library.
  • This is the struct to interact in a save way with the ArduboyTones C++ library.
  • This struct gives the library a understanding what Buttons on the Arduboy are.
  • This is the struct to store and read structs objects to/from eeprom memory.
  • Use this struct to store and read single bytes to/from eeprom memory.
  • This struct is used by a few Arduboy functions.
  • This struct is used by a few Arduboy functions.

Enums

  • This item is to chose between Black or White

Constants

  • Just a const for the A button
  • Just a const for the A button
  • Just a const for the B button
  • Just a const for the blue led
  • Just a const for the B button
  • Just a const for the DOWN button
  • Just a const for the DOWN button
  • The standard font size of the arduboy
  • Just a const for the green led
  • The standard height of the arduboy
  • Just a const for the LEFT button
  • Just a const for the LEFT button
  • Just a const for the red led
  • Just a const for led off
  • Just a const for led on
  • Just a const for the RIGHT button
  • Just a const for the RIGHT button
  • Just a const for the UP button
  • Just a const for the UP button
  • The standard width of the arduboy

Traits

Functions

  • A Arduino function to pause the cpu circles for a given amount of ms
  • A Arduino function to get a random number between 2 numbers +

Modules

  • This is the Module to interact in a save way with the Arduboy2 C++ library.
  • This is the Module to interact in a save way with the ArduboyTones C++ library.
  • A list of all six buttons available on the Arduboy
  • A list of all LED variables available
  • This is the module to interact in a save way with the Sprites C++ library.

Macros

  • This is the way to go if you want print some random text
  • Create a const raw pointer to a sprite as u8, without creating an intermediate reference.
  • Create a const raw pointer to a [u8;_] that saves text, without creating an intermediate reference.
  • Create a const raw pointer to a sprite as u16, without creating an intermediate reference.
  • Create a space for Progmem variable

Structs

  • This is the struct to interact in a save way with the Arduboy2 C++ library.
  • This is the struct to interact in a save way with the ArduboyTones C++ library.
  • This struct gives the library a understanding what Buttons on the Arduboy are.
  • This is the struct to store and read structs objects to/from eeprom memory.
  • Use this struct to store and read single bytes to/from eeprom memory.
  • A fixed capacity map / dictionary that performs lookups via linear search
  • This struct is used by a few Arduboy functions.
  • This struct is used by a few Arduboy functions.
  • A fixed capacity String
  • A fixed capacity Vec

Enums

  • This item is to chose between Black or White

Constants

  • Just a const for the A button
  • Just a const for the A button
  • Just a const for the B button
  • Just a const for the blue led
  • Just a const for the B button
  • Just a const for the DOWN button
  • Just a const for the DOWN button
  • The standard font size of the arduboy
  • Just a const for the green led
  • The standard height of the arduboy
  • Just a const for the LEFT button
  • Just a const for the LEFT button
  • Just a const for the red led
  • Just a const for led off
  • Just a const for led on
  • Just a const for the RIGHT button
  • Just a const for the RIGHT button
  • Just a const for the UP button
  • Just a const for the UP button
  • The standard width of the arduboy

Traits

Functions

  • A Arduino function to pause the cpu circles for a given amount of ms
  • A Arduino function to get a random number between 2 numbers seed based
  • A Arduino function to get a random number smaller than the number given seed based
  • A C function to get the length of a string

Type Definitions

  • c_size_tExperimental
    Equivalent to C’s size_t type, from stddef.h (or cstddef for C++).
  • Equivalent to C’s char type.
  • Equivalent to C’s double type.
  • Equivalent to C’s float type.
  • Equivalent to C’s signed int (int) type.
  • Equivalent to C’s signed long (long) type.
  • Equivalent to C’s signed long long (long long) type.
  • Equivalent to C’s unsigned char type.
  • Equivalent to C’s unsigned int type.
  • Equivalent to C’s unsigned long type.
  • Equivalent to C’s unsigned long long type.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/macro.f.html b/docs/doc/arduboy_rust/prelude/macro.f.html index 2299585..5550033 100644 --- a/docs/doc/arduboy_rust/prelude/macro.f.html +++ b/docs/doc/arduboy_rust/prelude/macro.f.html @@ -1,4 +1,4 @@ -f in arduboy_rust::prelude - Rust

Macro arduboy_rust::prelude::f

source ·
macro_rules! f {
+f in arduboy_rust::prelude - Rust

Macro arduboy_rust::prelude::f

source ·
macro_rules! f {
     ($string_literal:literal) => { ... };
 }
Expand description

This is the way to go if you want print some random text

This doesn’t waste the 2kb ram it saves to progmem (28kb) diff --git a/docs/doc/arduboy_rust/prelude/macro.get_sprite_addr.html b/docs/doc/arduboy_rust/prelude/macro.get_sprite_addr.html index 95bd30b..dd11a6a 100644 --- a/docs/doc/arduboy_rust/prelude/macro.get_sprite_addr.html +++ b/docs/doc/arduboy_rust/prelude/macro.get_sprite_addr.html @@ -1,4 +1,4 @@ -get_sprite_addr in arduboy_rust::prelude - Rust

macro_rules! get_sprite_addr {
+get_sprite_addr in arduboy_rust::prelude - Rust
macro_rules! get_sprite_addr {
     ( $s:expr ) => { ... };
 }
Expand description

Create a const raw pointer to a sprite as u8, without creating an intermediate reference.

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/macro.get_string_addr.html b/docs/doc/arduboy_rust/prelude/macro.get_string_addr.html index 5b0e89f..620bff6 100644 --- a/docs/doc/arduboy_rust/prelude/macro.get_string_addr.html +++ b/docs/doc/arduboy_rust/prelude/macro.get_string_addr.html @@ -1,4 +1,4 @@ -get_string_addr in arduboy_rust::prelude - Rust
macro_rules! get_string_addr {
+get_string_addr in arduboy_rust::prelude - Rust
macro_rules! get_string_addr {
     ( $s:expr ) => { ... };
 }
Expand description

Create a const raw pointer to a [u8;_] that saves text, without creating an intermediate reference.

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/macro.get_tones_addr.html b/docs/doc/arduboy_rust/prelude/macro.get_tones_addr.html index 9d613c3..43460fe 100644 --- a/docs/doc/arduboy_rust/prelude/macro.get_tones_addr.html +++ b/docs/doc/arduboy_rust/prelude/macro.get_tones_addr.html @@ -1,4 +1,4 @@ -get_tones_addr in arduboy_rust::prelude - Rust
macro_rules! get_tones_addr {
+get_tones_addr in arduboy_rust::prelude - Rust
macro_rules! get_tones_addr {
     ( $s:expr ) => { ... };
 }
Expand description

Create a const raw pointer to a sprite as u16, without creating an intermediate reference.

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/macro.progmem.html b/docs/doc/arduboy_rust/prelude/macro.progmem.html index 54904d3..5185d2c 100644 --- a/docs/doc/arduboy_rust/prelude/macro.progmem.html +++ b/docs/doc/arduboy_rust/prelude/macro.progmem.html @@ -1,9 +1,24 @@ -progmem in arduboy_rust::prelude - Rust
macro_rules! progmem {
+progmem in arduboy_rust::prelude - Rust
macro_rules! progmem {
     (
         $( #[$attr:meta] )*
         $v:vis $id:ident $name:ident: [$ty:ty; _] = $value:expr;
         $($rest:tt)*
     ) => { ... };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident mut $name:ident: [$ty:ty; _] = $value:expr;
+        $($rest:tt)*
+    ) => { ... };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident $name:ident: $ty:ty = $value:expr;
+        $($rest:tt)*
+    ) => { ... };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident mut $name:ident: $ty:ty = $value:expr;
+        $($rest:tt)*
+    ) => { ... };
     () => { ... };
 }
Expand description

Create a space for Progmem variable

Example

@@ -20,5 +35,10 @@ //for for bitmap progmem!( static image: [u8; _] = [8, 8, 0x81, 0x00, 0x12, 0x40, 0x04, 0x11, 0x00, 0x04]; +); + +// for a Vector +progmem!( + static mut walls: Vec<Player, 100> = Vec::new(); );
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/sidebar-items.js b/docs/doc/arduboy_rust/prelude/sidebar-items.js index 582c640..47307ee 100644 --- a/docs/doc/arduboy_rust/prelude/sidebar-items.js +++ b/docs/doc/arduboy_rust/prelude/sidebar-items.js @@ -1 +1 @@ -window.SIDEBAR_ITEMS = {"constant":["A","A_BUTTON","B","BLUE_LED","B_BUTTON","DOWN","DOWN_BUTTON","FONT_SIZE","GREEN_LED","HEIGHT","LEFT","LEFT_BUTTON","RED_LED","RGB_OFF","RGB_ON","RIGHT","RIGHT_BUTTON","UP","UP_BUTTON","WIDTH"],"enum":["Base","Color"],"fn":["constrain","delay","random_between","random_less_than","strlen"],"macro":["f","get_sprite_addr","get_string_addr","get_tones_addr","progmem"],"mod":["arduboy2","arduboy_tone","buttons","led","sprites"],"struct":["Arduboy2","ArduboyTones","ButtonSet","EEPROM","EEPROMBYTE","Point","Rect"],"trait":["Printable"],"type":["c_char","c_double","c_float","c_int","c_long","c_longlong","c_size_t","c_uchar","c_uint","c_ulong","c_ulonglong"]}; \ No newline at end of file +window.SIDEBAR_ITEMS = {"constant":["A","A_BUTTON","B","BLUE_LED","B_BUTTON","DOWN","DOWN_BUTTON","FONT_SIZE","GREEN_LED","HEIGHT","LEFT","LEFT_BUTTON","RED_LED","RGB_OFF","RGB_ON","RIGHT","RIGHT_BUTTON","UP","UP_BUTTON","WIDTH"],"enum":["Base","Color"],"fn":["constrain","delay","random_between","random_less_than","strlen"],"macro":["f","get_sprite_addr","get_string_addr","get_tones_addr","progmem"],"mod":["arduboy2","arduboy_tone","buttons","led","sprites"],"struct":["Arduboy2","ArduboyTones","ButtonSet","EEPROM","EEPROMBYTE","LinearMap","Point","Rect","String","Vec"],"trait":["Printable"],"type":["c_char","c_double","c_float","c_int","c_long","c_longlong","c_size_t","c_uchar","c_uint","c_ulong","c_ulonglong"]}; \ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/struct.LinearMap.html b/docs/doc/arduboy_rust/prelude/struct.LinearMap.html new file mode 100644 index 0000000..5a82406 --- /dev/null +++ b/docs/doc/arduboy_rust/prelude/struct.LinearMap.html @@ -0,0 +1,214 @@ +LinearMap in arduboy_rust::prelude - Rust
pub struct LinearMap<K, V, const N: usize> { /* private fields */ }
Expand description

A fixed capacity map / dictionary that performs lookups via linear search

+

Note that as this map doesn’t use hashing so most operations are O(N) instead of O(1)

+

Implementations§

source§

impl<K, V, const N: usize> LinearMap<K, V, N>

source

pub const fn new() -> LinearMap<K, V, N>

Creates an empty LinearMap

+
Examples
+
use heapless::LinearMap;
+
+// allocate the map on the stack
+let mut map: LinearMap<&str, isize, 8> = LinearMap::new();
+
+// allocate the map in a static variable
+static mut MAP: LinearMap<&str, isize, 8> = LinearMap::new();
+
source§

impl<K, V, const N: usize> LinearMap<K, V, N>where + K: Eq,

source

pub fn capacity(&self) -> usize

Returns the number of elements that the map can hold

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let map: LinearMap<&str, isize, 8> = LinearMap::new();
+assert_eq!(map.capacity(), 8);
+
source

pub fn clear(&mut self)

Clears the map, removing all key-value pairs

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+map.clear();
+assert!(map.is_empty());
+
source

pub fn contains_key(&self, key: &K) -> bool

Returns true if the map contains a value for the specified key.

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.contains_key(&1), true);
+assert_eq!(map.contains_key(&2), false);
+
source

pub fn get<Q>(&self, key: &Q) -> Option<&V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Returns a reference to the value corresponding to the key

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.get(&1), Some(&"a"));
+assert_eq!(map.get(&2), None);
+
source

pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Returns a mutable reference to the value corresponding to the key

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+if let Some(x) = map.get_mut(&1) {
+    *x = "b";
+}
+assert_eq!(map[&1], "b");
+
source

pub fn len(&self) -> usize

Returns the number of elements in this map

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut a: LinearMap<_, _, 8> = LinearMap::new();
+assert_eq!(a.len(), 0);
+a.insert(1, "a").unwrap();
+assert_eq!(a.len(), 1);
+
source

pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)>

Inserts a key-value pair into the map.

+

If the map did not have this key present, None is returned.

+

If the map did have this key present, the value is updated, and the old value is returned.

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+assert_eq!(map.insert(37, "a").unwrap(), None);
+assert_eq!(map.is_empty(), false);
+
+map.insert(37, "b").unwrap();
+assert_eq!(map.insert(37, "c").unwrap(), Some("b"));
+assert_eq!(map[&37], "c");
+
source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut a: LinearMap<_, _, 8> = LinearMap::new();
+assert!(a.is_empty());
+a.insert(1, "a").unwrap();
+assert!(!a.is_empty());
+
source

pub fn iter(&self) -> Iter<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order.

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (key, val) in map.iter() {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the +values

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+// Update all values
+for (_, val) in map.iter_mut() {
+    *val = 2;
+}
+
+for (key, val) in &map {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn keys(&self) -> impl Iterator<Item = &K>

An iterator visiting all keys in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for key in map.keys() {
+    println!("{}", key);
+}
+
source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Removes a key from the map, returning the value at the key if the key was previously in the +map

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.remove(&1), Some("a"));
+assert_eq!(map.remove(&1), None);
+
source

pub fn values(&self) -> impl Iterator<Item = &V>

An iterator visiting all values in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V>

An iterator visiting all values mutably in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values_mut() {
+    *val += 10;
+}
+
+for val in map.values() {
+    println!("{}", val);
+}
+

Trait Implementations§

source§

impl<K, V, const N: usize> Clone for LinearMap<K, V, N>where + K: Eq + Clone, + V: Clone,

source§

fn clone(&self) -> LinearMap<K, V, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K, V, const N: usize> Debug for LinearMap<K, V, N>where + K: Eq + Debug, + V: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<K, V, const N: usize> Default for LinearMap<K, V, N>where + K: Eq,

source§

fn default() -> LinearMap<K, V, N>

Returns the “default value” for a type. Read more
source§

impl<K, V, const N: usize> Drop for LinearMap<K, V, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<K, V, const N: usize> FromIterator<(K, V)> for LinearMap<K, V, N>where + K: Eq,

source§

fn from_iter<I>(iter: I) -> LinearMap<K, V, N>where + I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl<'a, K, V, Q, const N: usize> Index<&'a Q> for LinearMap<K, V, N>where + K: Borrow<Q> + Eq, + Q: Eq + ?Sized,

§

type Output = V

The returned type after indexing.
source§

fn index(&self, key: &Q) -> &V

Performs the indexing (container[index]) operation. Read more
source§

impl<'a, K, V, Q, const N: usize> IndexMut<&'a Q> for LinearMap<K, V, N>where + K: Borrow<Q> + Eq, + Q: Eq + ?Sized,

source§

fn index_mut(&mut self, key: &Q) -> &mut V

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, K, V, const N: usize> IntoIterator for &'a LinearMap<K, V, N>where + K: Eq,

§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a LinearMap<K, V, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, const N: usize, const N2: usize> PartialEq<LinearMap<K, V, N2>> for LinearMap<K, V, N>where + K: Eq, + V: PartialEq<V>,

source§

fn eq(&self, other: &LinearMap<K, V, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<K, V, const N: usize> Eq for LinearMap<K, V, N>where + K: Eq, + V: PartialEq<V>,

Auto Trait Implementations§

§

impl<K, V, const N: usize> RefUnwindSafe for LinearMap<K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<K, V, const N: usize> Send for LinearMap<K, V, N>where + K: Send, + V: Send,

§

impl<K, V, const N: usize> Sync for LinearMap<K, V, N>where + K: Sync, + V: Sync,

§

impl<K, V, const N: usize> Unpin for LinearMap<K, V, N>where + K: Unpin, + V: Unpin,

§

impl<K, V, const N: usize> UnwindSafe for LinearMap<K, V, N>where + K: UnwindSafe, + V: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/struct.String.html b/docs/doc/arduboy_rust/prelude/struct.String.html new file mode 100644 index 0000000..5c0b207 --- /dev/null +++ b/docs/doc/arduboy_rust/prelude/struct.String.html @@ -0,0 +1,1373 @@ +String in arduboy_rust::prelude - Rust
pub struct String<const N: usize> { /* private fields */ }
Expand description

A fixed capacity String

+

Implementations§

source§

impl<const N: usize> String<N>

source

pub const fn new() -> String<N>

Constructs a new, empty String with a fixed capacity of N bytes

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+// allocate the string on the stack
+let mut s: String<4> = String::new();
+
+// allocate the string in a static variable
+static mut S: String<4> = String::new();
+
source

pub fn into_bytes(self) -> Vec<u8, N>

Converts a String into a byte vector.

+

This consumes the String, so we do not need to copy its contents.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let s: String<4> = String::from("ab");
+let b = s.into_bytes();
+assert!(b.len() == 2);
+
+assert_eq!(&['a' as u8, 'b' as u8], &b[..]);
+
source

pub fn as_str(&self) -> &str

Extracts a string slice containing the entire string.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::from("ab");
+assert!(s.as_str() == "ab");
+
+let _s = s.as_str();
+// s.push('c'); // <- cannot borrow `s` as mutable because it is also borrowed as immutable
+
source

pub fn as_mut_str(&mut self) -> &mut str

Converts a String into a mutable string slice.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::from("ab");
+let s = s.as_mut_str();
+s.make_ascii_uppercase();
+
source

pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, N>

Returns a mutable reference to the contents of this String.

+
Safety
+

This function is unsafe because it does not check that the bytes passed +to it are valid UTF-8. If this constraint is violated, it may cause +memory unsafety issues with future users of the String, as the rest of +the library assumes that Strings are valid UTF-8.

+
Examples
+

Basic usage:

+ +
let mut s = String::from("hello");
+
+unsafe {
+    let vec = s.as_mut_vec();
+    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
+
+    vec.reverse();
+}
+assert_eq!(s, "olleh");
+
source

pub fn push_str(&mut self, string: &str) -> Result<(), ()>

Appends a given string slice onto the end of this String.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+assert!(s.push_str("bar").is_ok());
+
+assert_eq!("foobar", s);
+
+assert!(s.push_str("tender").is_err());
+
source

pub fn capacity(&self) -> usize

Returns the maximum number of elements the String can hold

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::new();
+assert!(s.capacity() == 4);
+
source

pub fn push(&mut self, c: char) -> Result<(), ()>

Appends the given char to the end of this String.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("abc");
+
+s.push('1').unwrap();
+s.push('2').unwrap();
+s.push('3').unwrap();
+
+assert!("abc123" == s.as_str());
+
+assert_eq!("abc123", s);
+
source

pub fn truncate(&mut self, new_len: usize)

Shortens this String to the specified length.

+

If new_len is greater than the string’s current length, this has no +effect.

+

Note that this method has no effect on the allocated capacity +of the string

+
Panics
+

Panics if new_len does not lie on a char boundary.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("hello");
+
+s.truncate(2);
+
+assert_eq!("he", s);
+
source

pub fn pop(&mut self) -> Option<char>

Removes the last character from the string buffer and returns it.

+

Returns None if this String is empty.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+assert_eq!(s.pop(), Some('o'));
+assert_eq!(s.pop(), Some('o'));
+assert_eq!(s.pop(), Some('f'));
+
+assert_eq!(s.pop(), None);
+
source

pub fn clear(&mut self)

Truncates this String, removing all contents.

+

While this means the String will have a length of zero, it does not +touch its capacity.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+s.clear();
+
+assert!(s.is_empty());
+assert_eq!(0, s.len());
+assert_eq!(8, s.capacity());
+

Methods from Deref<Target = str>§

1.0.0

pub fn len(&self) -> usize

Returns the length of self.

+

This length is in bytes, not chars or graphemes. In other words, +it might not be what a human considers the length of the string.

+
Examples
+
let len = "foo".len();
+assert_eq!(3, len);
+
+assert_eq!("ƒoo".len(), 4); // fancy f!
+assert_eq!("ƒoo".chars().count(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

+
Examples
+
let s = "";
+assert!(s.is_empty());
+
+let s = "not empty";
+assert!(!s.is_empty());
+
1.9.0

pub fn is_char_boundary(&self, index: usize) -> bool

Checks that index-th byte is the first byte in a UTF-8 code point +sequence or the end of the string.

+

The start and end of the string (when index == self.len()) are +considered to be boundaries.

+

Returns false if index is greater than self.len().

+
Examples
+
let s = "Löwe 老虎 Léopard";
+assert!(s.is_char_boundary(0));
+// start of `老`
+assert!(s.is_char_boundary(6));
+assert!(s.is_char_boundary(s.len()));
+
+// second byte of `ö`
+assert!(!s.is_char_boundary(2));
+
+// third byte of `老`
+assert!(!s.is_char_boundary(8));
+

pub fn floor_char_boundary(&self, index: usize) -> usize

🔬This is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not exceeding index where is_char_boundary(x) is true.

+

This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t +exceed a given number of bytes. Note that this is done purely at the character level +and can still visually split graphemes, even though the underlying characters aren’t +split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only +includes 🧑 (person) instead.

+
Examples
+
#![feature(round_char_boundary)]
+let s = "❤️🧡💛💚💙💜";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.floor_char_boundary(13);
+assert_eq!(closest, 10);
+assert_eq!(&s[..closest], "❤️🧡");
+

pub fn ceil_char_boundary(&self, index: usize) -> usize

🔬This is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not below index where is_char_boundary(x) is true.

+

This method is the natural complement to floor_char_boundary. See that method +for more details.

+
Panics
+

Panics if index > self.len().

+
Examples
+
#![feature(round_char_boundary)]
+let s = "❤️🧡💛💚💙💜";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.ceil_char_boundary(13);
+assert_eq!(closest, 14);
+assert_eq!(&s[..closest], "❤️🧡💛");
+
1.0.0

pub fn as_bytes(&self) -> &[u8]

Converts a string slice to a byte slice. To convert the byte slice back +into a string slice, use the [from_utf8] function.

+
Examples
+
let bytes = "bors".as_bytes();
+assert_eq!(b"bors", bytes);
+
1.20.0

pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8]

Converts a mutable string slice to a mutable byte slice.

+
Safety
+

The caller must ensure that the content of the slice is valid UTF-8 +before the borrow ends and the underlying str is used.

+

Use of a str whose contents are not valid UTF-8 is undefined behavior.

+
Examples
+

Basic usage:

+ +
let mut s = String::from("Hello");
+let bytes = unsafe { s.as_bytes_mut() };
+
+assert_eq!(b"Hello", bytes);
+

Mutability:

+ +
let mut s = String::from("🗻∈🌏");
+
+unsafe {
+    let bytes = s.as_bytes_mut();
+
+    bytes[0] = 0xF0;
+    bytes[1] = 0x9F;
+    bytes[2] = 0x8D;
+    bytes[3] = 0x94;
+}
+
+assert_eq!("🍔∈🌏", s);
+
1.0.0

pub fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +[u8]. This pointer will be pointing to the first byte of the string +slice.

+

The caller must ensure that the returned pointer is never written to. +If you need to mutate the contents of the string slice, use as_mut_ptr.

+
Examples
+
let s = "Hello";
+let ptr = s.as_ptr();
+
1.36.0

pub fn as_mut_ptr(&mut self) -> *mut u8

Converts a mutable string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +[u8]. This pointer will be pointing to the first byte of the string +slice.

+

It is your responsibility to make sure that the string slice only gets +modified in a way that it remains valid UTF-8.

+
1.20.0

pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where + I: SliceIndex<str>,

Returns a subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +[None] whenever equivalent indexing operation would panic.

+
Examples
+
let v = String::from("🗻∈🌏");
+
+assert_eq!(Some("🗻"), v.get(0..4));
+
+// indices not on UTF-8 sequence boundaries
+assert!(v.get(1..).is_none());
+assert!(v.get(..8).is_none());
+
+// out of bounds
+assert!(v.get(..42).is_none());
+
1.20.0

pub fn get_mut<I>( + &mut self, + i: I +) -> Option<&mut <I as SliceIndex<str>>::Output>where + I: SliceIndex<str>,

Returns a mutable subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +[None] whenever equivalent indexing operation would panic.

+
Examples
+
let mut v = String::from("hello");
+// correct length
+assert!(v.get_mut(0..5).is_some());
+// out of bounds
+assert!(v.get_mut(..42).is_none());
+assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
+
+assert_eq!("hello", v);
+{
+    let s = v.get_mut(0..2);
+    let s = s.map(|s| {
+        s.make_ascii_uppercase();
+        &*s
+    });
+    assert_eq!(Some("HE"), s);
+}
+assert_eq!("HEllo", v);
+
1.20.0

pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere + I: SliceIndex<str>,

Returns an unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
Safety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
Examples
+
let v = "🗻∈🌏";
+unsafe {
+    assert_eq!("🗻", v.get_unchecked(0..4));
+    assert_eq!("∈", v.get_unchecked(4..7));
+    assert_eq!("🌏", v.get_unchecked(7..11));
+}
+
1.20.0

pub unsafe fn get_unchecked_mut<I>( + &mut self, + i: I +) -> &mut <I as SliceIndex<str>>::Outputwhere + I: SliceIndex<str>,

Returns a mutable, unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
Safety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
Examples
+
let mut v = String::from("🗻∈🌏");
+unsafe {
+    assert_eq!("🗻", v.get_unchecked_mut(0..4));
+    assert_eq!("∈", v.get_unchecked_mut(4..7));
+    assert_eq!("🌏", v.get_unchecked_mut(7..11));
+}
+
1.0.0

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

👎Deprecated since 1.29.0: use get_unchecked(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks.

+

This is generally not recommended, use with caution! For a safe +alternative see [str] and Index.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get a mutable string slice instead, see the +slice_mut_unchecked method.

+
Safety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
Examples
+
let s = "Löwe 老虎 Léopard";
+
+unsafe {
+    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
+}
+
+let s = "Hello, world!";
+
+unsafe {
+    assert_eq!("world", s.slice_unchecked(7, 12));
+}
+
1.5.0

pub unsafe fn slice_mut_unchecked( + &mut self, + begin: usize, + end: usize +) -> &mut str

👎Deprecated since 1.29.0: use get_unchecked_mut(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks. +This is generally not recommended, use with caution! For a safe +alternative see [str] and IndexMut.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get an immutable string slice instead, see the +slice_unchecked method.

+
Safety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
1.4.0

pub fn split_at(&self, mid: usize) -> (&str, &str)

Divide one string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get mutable string slices instead, see the split_at_mut +method.

+
Panics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is +past the end of the last code point of the string slice.

+
Examples
+
let s = "Per Martin-Löf";
+
+let (first, last) = s.split_at(3);
+
+assert_eq!("Per", first);
+assert_eq!(" Martin-Löf", last);
+
1.4.0

pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)

Divide one mutable string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get immutable string slices instead, see the split_at method.

+
Panics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is +past the end of the last code point of the string slice.

+
Examples
+
let mut s = "Per Martin-Löf".to_string();
+{
+    let (first, last) = s.split_at_mut(3);
+    first.make_ascii_uppercase();
+    assert_eq!("PER", first);
+    assert_eq!(" Martin-Löf", last);
+}
+assert_eq!("PER Martin-Löf", s);
+
1.0.0

pub fn chars(&self) -> Chars<'_>

Returns an iterator over the chars of a string slice.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns such an iterator.

+

It’s important to remember that char represents a Unicode Scalar +Value, and might not match your idea of what a ‘character’ is. Iteration +over grapheme clusters may be what you actually want. This functionality +is not provided by Rust’s standard library, check crates.io instead.

+
Examples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.chars().count();
+assert_eq!(7, count);
+
+let mut chars = word.chars();
+
+assert_eq!(Some('g'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('d'), chars.next());
+assert_eq!(Some('b'), chars.next());
+assert_eq!(Some('y'), chars.next());
+assert_eq!(Some('e'), chars.next());
+
+assert_eq!(None, chars.next());
+

Remember, chars might not match your intuition about characters:

+ +
let y = "y̆";
+
+let mut chars = y.chars();
+
+assert_eq!(Some('y'), chars.next()); // not 'y̆'
+assert_eq!(Some('\u{0306}'), chars.next());
+
+assert_eq!(None, chars.next());
+
1.0.0

pub fn char_indices(&self) -> CharIndices<'_>

Returns an iterator over the chars of a string slice, and their +positions.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns an iterator of both +these chars, as well as their byte positions.

+

The iterator yields tuples. The position is first, the char is +second.

+
Examples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.char_indices().count();
+assert_eq!(7, count);
+
+let mut char_indices = word.char_indices();
+
+assert_eq!(Some((0, 'g')), char_indices.next());
+assert_eq!(Some((1, 'o')), char_indices.next());
+assert_eq!(Some((2, 'o')), char_indices.next());
+assert_eq!(Some((3, 'd')), char_indices.next());
+assert_eq!(Some((4, 'b')), char_indices.next());
+assert_eq!(Some((5, 'y')), char_indices.next());
+assert_eq!(Some((6, 'e')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+

Remember, chars might not match your intuition about characters:

+ +
let yes = "y̆es";
+
+let mut char_indices = yes.char_indices();
+
+assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
+assert_eq!(Some((1, '\u{0306}')), char_indices.next());
+
+// note the 3 here - the last character took up two bytes
+assert_eq!(Some((3, 'e')), char_indices.next());
+assert_eq!(Some((4, 's')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+
1.0.0

pub fn bytes(&self) -> Bytes<'_>

An iterator over the bytes of a string slice.

+

As a string slice consists of a sequence of bytes, we can iterate +through a string slice by byte. This method returns such an iterator.

+
Examples
+
let mut bytes = "bors".bytes();
+
+assert_eq!(Some(b'b'), bytes.next());
+assert_eq!(Some(b'o'), bytes.next());
+assert_eq!(Some(b'r'), bytes.next());
+assert_eq!(Some(b's'), bytes.next());
+
+assert_eq!(None, bytes.next());
+
1.1.0

pub fn split_whitespace(&self) -> SplitWhitespace<'_>

Splits a string slice by whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of whitespace.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space. If you only want to split on ASCII whitespace +instead, use split_ascii_whitespace.

+
Examples
+

Basic usage:

+ +
let mut iter = "A few words".split_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of whitespace are considered:

+ +
let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_whitespace().next(), None);
+assert_eq!("   ".split_whitespace().next(), None);
+
1.34.0

pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>

Splits a string slice by ASCII whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of ASCII whitespace.

+

To split by Unicode Whitespace instead, use split_whitespace.

+
Examples
+

Basic usage:

+ +
let mut iter = "A few words".split_ascii_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of ASCII whitespace are considered:

+ +
let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all ASCII whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_ascii_whitespace().next(), None);
+assert_eq!("   ".split_ascii_whitespace().next(), None);
+
1.0.0

pub fn lines(&self) -> Lines<'_>

An iterator over the lines of a string, as string slices.

+

Lines are split at line endings that are either newlines (\n) or +sequences of a carriage return followed by a line feed (\r\n).

+

Line terminators are not included in the lines returned by the iterator.

+

The final line ending is optional. A string that ends with a final line +ending will return the same lines as an otherwise identical string +without a final line ending.

+
Examples
+

Basic usage:

+ +
let text = "foo\r\nbar\n\nbaz\n";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+

The final line ending isn’t required:

+ +
let text = "foo\nbar\n\r\nbaz";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+
1.0.0

pub fn lines_any(&self) -> LinesAny<'_>

👎Deprecated since 1.4.0: use lines() instead now

An iterator over the lines of a string.

+
1.8.0

pub fn encode_utf16(&self) -> EncodeUtf16<'_>

Returns an iterator of u16 over the string encoded as UTF-16.

+
Examples
+
let text = "Zażółć gęślą jaźń";
+
+let utf8_len = text.len();
+let utf16_len = text.encode_utf16().count();
+
+assert!(utf16_len <= utf8_len);
+
1.0.0

pub fn contains<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>,

Returns true if the given pattern matches a sub-slice of +this string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.contains("nana"));
+assert!(!bananas.contains("apples"));
+
1.0.0

pub fn starts_with<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>,

Returns true if the given pattern matches a prefix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.starts_with("bana"));
+assert!(!bananas.starts_with("nana"));
+
1.0.0

pub fn ends_with<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns true if the given pattern matches a suffix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.ends_with("anas"));
+assert!(!bananas.ends_with("nana"));
+
1.0.0

pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>where + P: Pattern<'a>,

Returns the byte index of the first character of this string slice that +matches the pattern.

+

Returns [None] if the pattern doesn’t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
let s = "Löwe 老虎 Léopard Gepardi";
+
+assert_eq!(s.find('L'), Some(0));
+assert_eq!(s.find('é'), Some(14));
+assert_eq!(s.find("pard"), Some(17));
+

More complex patterns using point-free style and closures:

+ +
let s = "Löwe 老虎 Léopard";
+
+assert_eq!(s.find(char::is_whitespace), Some(5));
+assert_eq!(s.find(char::is_lowercase), Some(1));
+assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
+assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
+

Not finding the pattern:

+ +
let s = "Löwe 老虎 Léopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.find(x), None);
+
1.0.0

pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns the byte index for the first character of the last match of the pattern in +this string slice.

+

Returns [None] if the pattern doesn’t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
let s = "Löwe 老虎 Léopard Gepardi";
+
+assert_eq!(s.rfind('L'), Some(13));
+assert_eq!(s.rfind('é'), Some(14));
+assert_eq!(s.rfind("pard"), Some(24));
+

More complex patterns with closures:

+ +
let s = "Löwe 老虎 Léopard";
+
+assert_eq!(s.rfind(char::is_whitespace), Some(12));
+assert_eq!(s.rfind(char::is_lowercase), Some(20));
+

Not finding the pattern:

+ +
let s = "Löwe 老虎 Léopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.rfind(x), None);
+
1.0.0

pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P>where + P: Pattern<'a>,

An iterator over substrings of this string slice, separated by +characters matched by a pattern.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rsplit method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
+assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
+
+let v: Vec<&str> = "".split('X').collect();
+assert_eq!(v, [""]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
+assert_eq!(v, ["lion", "", "tiger", "leopard"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
+assert_eq!(v, ["lion", "tiger", "leopard"]);
+
+let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
+assert_eq!(v, ["abc", "def", "ghi"]);
+
+let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
+assert_eq!(v, ["lion", "tiger", "leopard"]);
+

If the pattern is a slice of chars, split on each occurrence of any of the characters:

+ +
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
+assert_eq!(v, ["2020", "11", "03", "23", "59"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["abc", "def", "ghi"]);
+

If a string contains multiple contiguous separators, you will end up +with empty strings in the output:

+ +
let x = "||||a||b|c".to_string();
+let d: Vec<_> = x.split('|').collect();
+
+assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
+

Contiguous separators are separated by the empty string.

+ +
let x = "(///)".to_string();
+let d: Vec<_> = x.split('/').collect();
+
+assert_eq!(d, &["(", "", "", ")"]);
+

Separators at the start or end of a string are neighbored +by empty strings.

+ +
let d: Vec<_> = "010".split("0").collect();
+assert_eq!(d, &["", "1", ""]);
+

When the empty string is used as a separator, it separates +every character in the string, along with the beginning +and end of the string.

+ +
let f: Vec<_> = "rust".split("").collect();
+assert_eq!(f, &["", "r", "u", "s", "t", ""]);
+

Contiguous separators can lead to possibly surprising behavior +when whitespace is used as the separator. This code is correct:

+ +
let x = "    a  b c".to_string();
+let d: Vec<_> = x.split(' ').collect();
+
+assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
+

It does not give you:

+ +
assert_eq!(d, &["a", "b", "c"]);
+

Use split_whitespace for this behavior.

+
1.51.0

pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P>where + P: Pattern<'a>,

An iterator over substrings of this string slice, separated by +characters matched by a pattern. Differs from the iterator produced by +split in that split_inclusive leaves the matched part as the +terminator of the substring.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
+

If the last element of the string is matched, +that element will be considered the terminator of the preceding substring. +That substring will be the last item returned by the iterator.

+ +
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
+
1.0.0

pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of the given string slice, separated by +characters matched by a pattern and yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the split method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
+assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
+
+let v: Vec<&str> = "".rsplit('X').collect();
+assert_eq!(v, [""]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
+assert_eq!(v, ["leopard", "tiger", "", "lion"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
+assert_eq!(v, ["leopard", "tiger", "lion"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["ghi", "def", "abc"]);
+
1.0.0

pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P>where + P: Pattern<'a>,

An iterator over substrings of the given string slice, separated by +characters matched by a pattern.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring +is skipped if empty.

+

This method can be used for string data that is terminated, +rather than separated by a pattern.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rsplit_terminator method can be used.

+
Examples
+
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
+assert_eq!(v, ["A", "B"]);
+
+let v: Vec<&str> = "A..B..".split_terminator(".").collect();
+assert_eq!(v, ["A", "", "B", ""]);
+
+let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
+assert_eq!(v, ["A", "B", "C", "D"]);
+
1.0.0

pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of self, separated by characters +matched by a pattern and yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring is +skipped if empty.

+

This method can be used for string data that is terminated, +rather than separated by a pattern.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a +reverse search, and it will be double ended if a forward/reverse +search yields the same elements.

+

For iterating from the front, the split_terminator method can be +used.

+
Examples
+
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
+assert_eq!(v, ["B", "A"]);
+
+let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
+assert_eq!(v, ["", "B", "", "A"]);
+
+let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
+assert_eq!(v, ["D", "C", "B", "A"]);
+
1.0.0

pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P>where + P: Pattern<'a>,

An iterator over substrings of the given string slice, separated by a +pattern, restricted to returning at most n items.

+

If n substrings are returned, the last substring (the nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will not be double ended, because it is +not efficient to support.

+

If the pattern allows a reverse search, the rsplitn method can be +used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
+assert_eq!(v, ["Mary", "had", "a little lambda"]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
+assert_eq!(v, ["lion", "", "tigerXleopard"]);
+
+let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
+assert_eq!(v, ["abcXdef"]);
+
+let v: Vec<&str> = "".splitn(1, 'X').collect();
+assert_eq!(v, [""]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["abc", "defXghi"]);
+
1.0.0

pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of this string slice, separated by a +pattern, starting from the end of the string, restricted to returning +at most n items.

+

If n substrings are returned, the last substring (the nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will not be double ended, because it is not +efficient to support.

+

For splitting from the front, the splitn method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
+assert_eq!(v, ["lamb", "little", "Mary had a"]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
+assert_eq!(v, ["leopard", "tiger", "lionX"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
+assert_eq!(v, ["leopard", "lion::tiger"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["ghi", "abc1def"]);
+
1.52.0

pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where + P: Pattern<'a>,

Splits the string on the first occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
Examples
+
assert_eq!("cfg".split_once('='), None);
+assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
+assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
+
1.52.0

pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Splits the string on the last occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
Examples
+
assert_eq!("cfg".rsplit_once('='), None);
+assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
+
1.2.0

pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P>where + P: Pattern<'a>,

An iterator over the disjoint matches of a pattern within the given string +slice.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rmatches method can be used.

+
Examples
+
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
+assert_eq!(v, ["abc", "abc", "abc"]);
+
+let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
+assert_eq!(v, ["1", "2", "3"]);
+
1.2.0

pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over the disjoint matches of a pattern within this string slice, +yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the matches method can be used.

+
Examples
+
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
+assert_eq!(v, ["abc", "abc", "abc"]);
+
+let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
+assert_eq!(v, ["3", "2", "1"]);
+
1.5.0

pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P>where + P: Pattern<'a>,

An iterator over the disjoint matches of a pattern within this string +slice as well as the index that the match starts at.

+

For matches of pat within self that overlap, only the indices +corresponding to the first match are returned.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rmatch_indices method can be used.

+
Examples
+
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
+assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
+
+let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
+assert_eq!(v, [(1, "abc"), (4, "abc")]);
+
+let v: Vec<_> = "ababa".match_indices("aba").collect();
+assert_eq!(v, [(0, "aba")]); // only the first `aba`
+
1.5.0

pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over the disjoint matches of a pattern within self, +yielded in reverse order along with the index of the match.

+

For matches of pat within self that overlap, only the indices +corresponding to the last match are returned.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the match_indices method can be used.

+
Examples
+
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
+assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
+
+let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
+assert_eq!(v, [(4, "abc"), (1, "abc")]);
+
+let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
+assert_eq!(v, [(2, "aba")]); // only the last `aba`
+
1.0.0

pub fn trim(&self) -> &str

Returns a string slice with leading and trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Examples
+
let s = "\n Hello\tworld\t\n";
+
+assert_eq!("Hello\tworld", s.trim());
+
1.30.0

pub fn trim_start(&self) -> &str

Returns a string slice with leading whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Text directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
Examples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("Hello\tworld\t\n", s.trim_start());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('E') == s.trim_start().chars().next());
+
+let s = "  עברית  ";
+assert!(Some('ע') == s.trim_start().chars().next());
+
1.30.0

pub fn trim_end(&self) -> &str

Returns a string slice with trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Text directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
Examples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("\n Hello\tworld", s.trim_end());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('h') == s.trim_end().chars().rev().next());
+
+let s = "  עברית  ";
+assert!(Some('ת') == s.trim_end().chars().rev().next());
+
1.0.0

pub fn trim_left(&self) -> &str

👎Deprecated since 1.33.0: superseded by trim_start

Returns a string slice with leading whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
Text directionality
+

A string is a sequence of bytes. ‘Left’ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the right side, not the left.

+
Examples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!("Hello\tworld\t", s.trim_left());
+

Directionality:

+ +
let s = "  English";
+assert!(Some('E') == s.trim_left().chars().next());
+
+let s = "  עברית";
+assert!(Some('ע') == s.trim_left().chars().next());
+
1.0.0

pub fn trim_right(&self) -> &str

👎Deprecated since 1.33.0: superseded by trim_end

Returns a string slice with trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
Text directionality
+

A string is a sequence of bytes. ‘Right’ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the left side, not the right.

+
Examples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!(" Hello\tworld", s.trim_right());
+

Directionality:

+ +
let s = "English  ";
+assert!(Some('h') == s.trim_right().chars().rev().next());
+
+let s = "עברית  ";
+assert!(Some('ת') == s.trim_right().chars().rev().next());
+
1.0.0

pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,

Returns a string slice with all prefixes and suffixes that match a +pattern repeatedly removed.

+

The pattern can be a char, a slice of chars, or a function +or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
+assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
+
1.30.0

pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>,

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
Examples
+
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
+
1.45.0

pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>where + P: Pattern<'a>,

Returns a string slice with the prefix removed.

+

If the string starts with the pattern prefix, returns substring after the prefix, wrapped +in Some. Unlike trim_start_matches, this method removes the prefix exactly once.

+

If the string does not start with prefix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
+assert_eq!("foo:bar".strip_prefix("bar"), None);
+assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
+
1.45.0

pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns a string slice with the suffix removed.

+

If the string ends with the pattern suffix, returns the substring before the suffix, +wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.

+

If the string does not end with suffix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
+assert_eq!("bar:foo".strip_suffix("bar"), None);
+assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
+
1.30.0

pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.0.0

pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>,

👎Deprecated since 1.33.0: superseded by trim_start_matches

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. ‘Left’ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the right side, not the left.

+
Examples
+
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
+
1.0.0

pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

👎Deprecated since 1.33.0: superseded by trim_end_matches

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. ‘Right’ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the left side, not the right.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.0.0

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where + F: FromStr,

Parses this string slice into another type.

+

Because parse is so general, it can cause problems with type +inference. As such, parse is one of the few times you’ll see +the syntax affectionately known as the ‘turbofish’: ::<>. This +helps the inference algorithm understand specifically which type +you’re trying to parse into.

+

parse can parse into any type that implements the [FromStr] trait.

+
Errors
+

Will return Err if it’s not possible to parse this string slice into +the desired type.

+
Examples
+

Basic usage

+ +
let four: u32 = "4".parse().unwrap();
+
+assert_eq!(4, four);
+

Using the ‘turbofish’ instead of annotating four:

+ +
let four = "4".parse::<u32>();
+
+assert_eq!(Ok(4), four);
+

Failing to parse:

+ +
let nope = "j".parse::<u32>();
+
+assert!(nope.is_err());
+
1.23.0

pub fn is_ascii(&self) -> bool

Checks if all characters in this string are within the ASCII range.

+
Examples
+
let ascii = "hello!\n";
+let non_ascii = "Grüße, Jürgen ❤";
+
+assert!(ascii.is_ascii());
+assert!(!non_ascii.is_ascii());
+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this string slice is_ascii, returns it as a slice +of ASCII characters, otherwise returns None.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &str) -> bool

Checks that two strings are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
Examples
+
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
+assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
+assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
+
1.23.0

pub fn make_ascii_uppercase(&mut self)

Converts this string to its ASCII upper case equivalent in-place.

+

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, +but non-ASCII letters are unchanged.

+

To return a new uppercased value without modifying the existing one, use +to_ascii_uppercase().

+
Examples
+
let mut s = String::from("Grüße, Jürgen ❤");
+
+s.make_ascii_uppercase();
+
+assert_eq!("GRüßE, JüRGEN ❤", s);
+
1.23.0

pub fn make_ascii_lowercase(&mut self)

Converts this string to its ASCII lower case equivalent in-place.

+

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, +but non-ASCII letters are unchanged.

+

To return a new lowercased value without modifying the existing one, use +to_ascii_lowercase().

+
Examples
+
let mut s = String::from("GRÜßE, JÜRGEN ❤");
+
+s.make_ascii_lowercase();
+
+assert_eq!("grÜße, jÜrgen ❤", s);
+
1.34.0

pub fn escape_debug(&self) -> EscapeDebug<'_>

Return an iterator that escapes each char in self with [char::escape_debug].

+

Note: only extended grapheme codepoints that begin the string will be +escaped.

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_debug() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_debug());
+

Both are equivalent to:

+ +
println!("❤\\n!");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
+
1.34.0

pub fn escape_default(&self) -> EscapeDefault<'_>

Return an iterator that escapes each char in self with [char::escape_default].

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_default() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_default());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\n!");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
+
1.34.0

pub fn escape_unicode(&self) -> EscapeUnicode<'_>

Return an iterator that escapes each char in self with [char::escape_unicode].

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_unicode() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_unicode());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
+

Trait Implementations§

source§

impl<const N: usize> AsRef<[u8]> for String<N>

source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize> AsRef<str> for String<N>

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize> Clone for String<N>

source§

fn clone(&self) -> String<N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<const N: usize> Debug for String<N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<const N: usize> Default for String<N>

source§

fn default() -> String<N>

Returns the “default value” for a type. Read more
source§

impl<const N: usize> Deref for String<N>

§

type Target = str

The resulting type after dereferencing.
source§

fn deref(&self) -> &str

Dereferences the value.
source§

impl<const N: usize> DerefMut for String<N>

source§

fn deref_mut(&mut self) -> &mut str

Mutably dereferences the value.
source§

impl<const N: usize> Display for String<N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<'a, const N: usize> From<&'a str> for String<N>

source§

fn from(s: &'a str) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i16> for String<N>

source§

fn from(s: i16) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i32> for String<N>

source§

fn from(s: i32) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i64> for String<N>

source§

fn from(s: i64) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<i8> for String<N>

source§

fn from(s: i8) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u16> for String<N>

source§

fn from(s: u16) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u32> for String<N>

source§

fn from(s: u32) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u64> for String<N>

source§

fn from(s: u64) -> String<N>

Converts to this type from the input type.
source§

impl<const N: usize> From<u8> for String<N>

source§

fn from(s: u8) -> String<N>

Converts to this type from the input type.
source§

impl<'a, const N: usize> FromIterator<&'a char> for String<N>

source§

fn from_iter<T>(iter: T) -> String<N>where + T: IntoIterator<Item = &'a char>,

Creates a value from an iterator. Read more
source§

impl<'a, const N: usize> FromIterator<&'a str> for String<N>

source§

fn from_iter<T>(iter: T) -> String<N>where + T: IntoIterator<Item = &'a str>,

Creates a value from an iterator. Read more
source§

impl<const N: usize> FromIterator<char> for String<N>

source§

fn from_iter<T>(iter: T) -> String<N>where + T: IntoIterator<Item = char>,

Creates a value from an iterator. Read more
source§

impl<const N: usize> FromStr for String<N>

§

type Err = ()

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<String<N>, <String<N> as FromStr>::Err>

Parses a string s to return a value of this type. Read more
source§

impl<const N: usize> Hash for String<N>

source§

fn hash<H>(&self, hasher: &mut H)where + H: Hasher,

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl<const N: usize> Hash for String<N>

source§

fn hash<H>(&self, hasher: &mut H)where + H: Hasher,

Feeds this value into the given Hasher.
source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.
source§

impl<const N: usize> Ord for String<N>

source§

fn cmp(&self, other: &String<N>) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<const N: usize> PartialEq<&str> for String<N>

source§

fn eq(&self, other: &&str) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &&str) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<String<N>> for &str

source§

fn eq(&self, other: &String<N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &String<N>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<String<N>> for str

source§

fn eq(&self, other: &String<N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &String<N>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N1: usize, const N2: usize> PartialEq<String<N2>> for String<N1>

source§

fn eq(&self, rhs: &String<N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, rhs: &String<N2>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<str> for String<N>

source§

fn eq(&self, other: &str) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &str) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N1: usize, const N2: usize> PartialOrd<String<N2>> for String<N1>

source§

fn partial_cmp(&self, other: &String<N2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl<const N: usize> Write for String<N>

source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write +succeeded. Read more
source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a [char] into this writer, returning whether the write succeeded. Read more
1.0.0§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the [write!] macro with implementors of this trait. Read more
source§

impl<const N: usize> Eq for String<N>

Auto Trait Implementations§

§

impl<const N: usize> RefUnwindSafe for String<N>

§

impl<const N: usize> Send for String<N>

§

impl<const N: usize> Sync for String<N>

§

impl<const N: usize> Unpin for String<N>

§

impl<const N: usize> UnwindSafe for String<N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/struct.Vec.html b/docs/doc/arduboy_rust/prelude/struct.Vec.html new file mode 100644 index 0000000..cbdcab9 --- /dev/null +++ b/docs/doc/arduboy_rust/prelude/struct.Vec.html @@ -0,0 +1,2527 @@ +Vec in arduboy_rust::prelude - Rust

Struct arduboy_rust::prelude::Vec

source ·
pub struct Vec<T, const N: usize> { /* private fields */ }
Expand description

A fixed capacity Vec

+

Examples

+
use heapless::Vec;
+
+
+// A vector with a fixed capacity of 8 elements allocated on the stack
+let mut vec = Vec::<_, 8>::new();
+vec.push(1);
+vec.push(2);
+
+assert_eq!(vec.len(), 2);
+assert_eq!(vec[0], 1);
+
+assert_eq!(vec.pop(), Some(2));
+assert_eq!(vec.len(), 1);
+
+vec[0] = 7;
+assert_eq!(vec[0], 7);
+
+vec.extend([1, 2, 3].iter().cloned());
+
+for x in &vec {
+    println!("{}", x);
+}
+assert_eq!(*vec, [7, 1, 2, 3]);
+

Implementations§

source§

impl<T, const N: usize> Vec<T, N>

source

pub const fn new() -> Vec<T, N>

Constructs a new, empty vector with a fixed capacity of N

+
Examples
+
use heapless::Vec;
+
+// allocate the vector on the stack
+let mut x: Vec<u8, 16> = Vec::new();
+
+// allocate the vector in a static variable
+static mut X: Vec<u8, 16> = Vec::new();
+

Vec const constructor; wrap the returned value in Vec

+
source

pub fn from_slice(other: &[T]) -> Result<Vec<T, N>, ()>where + T: Clone,

Constructs a new vector with a fixed capacity of N and fills it +with the provided slice.

+

This is equivalent to the following code:

+ +
use heapless::Vec;
+
+let mut v: Vec<u8, 16> = Vec::new();
+v.extend_from_slice(&[1, 2, 3]).unwrap();
+
source

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the vector’s buffer.

+
source

pub fn as_mut_ptr(&mut self) -> *mut T

Returns a raw pointer to the vector’s buffer, which may be mutated through.

+
source

pub fn as_slice(&self) -> &[T]

Extracts a slice containing the entire vector.

+

Equivalent to &s[..].

+
Examples
+
use heapless::Vec;
+let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
+
source

pub fn into_array<const M: usize>(self) -> Result<[T; M], Vec<T, N>>

Returns the contents of the vector as an array of length M if the length +of the vector is exactly M, otherwise returns Err(self).

+
Examples
+
use heapless::Vec;
+let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+let array: [u8; 5] = buffer.into_array().unwrap();
+assert_eq!(array, [1, 2, 3, 5, 8]);
+
source

pub const fn capacity(&self) -> usize

Returns the maximum number of elements the vector can hold.

+
source

pub fn clear(&mut self)

Clears the vector, removing all values.

+
source

pub fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends the vec from an iterator.

+
Panic
+

Panics if the vec cannot hold all elements of the iterator.

+
source

pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>where + T: Clone,

Clones and appends all elements in a slice to the Vec.

+

Iterates over the slice other, clones each element, and then appends +it to this Vec. The other vector is traversed in-order.

+
Examples
+
use heapless::Vec;
+
+let mut vec = Vec::<u8, 8>::new();
+vec.push(1).unwrap();
+vec.extend_from_slice(&[2, 3, 4]).unwrap();
+assert_eq!(*vec, [1, 2, 3, 4]);
+
source

pub fn pop(&mut self) -> Option<T>

Removes the last element from a vector and returns it, or None if it’s empty

+
source

pub fn push(&mut self, item: T) -> Result<(), T>

Appends an item to the back of the collection

+

Returns back the item if the vector is full

+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Removes the last element from a vector and returns it

+
Safety
+

This assumes the vec to have at least one element.

+
source

pub unsafe fn push_unchecked(&mut self, item: T)

Appends an item to the back of the collection

+
Safety
+

This assumes the vec is not full.

+
source

pub fn truncate(&mut self, len: usize)

Shortens the vector, keeping the first len elements and dropping the rest.

+
source

pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>where + T: Clone,

Resizes the Vec in-place so that len is equal to new_len.

+

If new_len is greater than len, the Vec is extended by the +difference, with each additional slot filled with value. If +new_len is less than len, the Vec is simply truncated.

+

See also resize_default.

+
source

pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>where + T: Clone + Default,

Resizes the Vec in-place so that len is equal to new_len.

+

If new_len is greater than len, the Vec is extended by the +difference, with each additional slot filled with Default::default(). +If new_len is less than len, the Vec is simply truncated.

+

See also resize.

+
source

pub unsafe fn set_len(&mut self, new_len: usize)

Forces the length of the vector to new_len.

+

This is a low-level operation that maintains none of the normal +invariants of the type. Normally changing the length of a vector +is done using one of the safe operations instead, such as +truncate, resize, extend, or clear.

+
Safety
+
    +
  • new_len must be less than or equal to capacity().
  • +
  • The elements at old_len..new_len must be initialized.
  • +
+
Examples
+

This method can be useful for situations in which the vector +is serving as a buffer for other code, particularly over FFI:

+ +
use heapless::Vec;
+
+pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
+    // Per the FFI method's docs, "32768 bytes is always enough".
+    let mut dict = Vec::new();
+    let mut dict_length = 0;
+    // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
+    // 1. `dict_length` elements were initialized.
+    // 2. `dict_length` <= the capacity (32_768)
+    // which makes `set_len` safe to call.
+    unsafe {
+        // Make the FFI call...
+        let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
+        if r == Z_OK {
+            // ...and update the length to what was initialized.
+            dict.set_len(dict_length);
+            Some(dict)
+        } else {
+            None
+        }
+    }
+}
+

While the following example is sound, there is a memory leak since +the inner vectors were not freed prior to the set_len call:

+ +
use core::iter::FromIterator;
+use heapless::Vec;
+
+let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
+    [
+        Vec::from_iter([1, 0, 0].iter().cloned()),
+        Vec::from_iter([0, 1, 0].iter().cloned()),
+        Vec::from_iter([0, 0, 1].iter().cloned()),
+    ]
+    .iter()
+    .cloned()
+);
+// SAFETY:
+// 1. `old_len..0` is empty so no elements need to be initialized.
+// 2. `0 <= capacity` always holds whatever `capacity` is.
+unsafe {
+    vec.set_len(0);
+}
+

Normally, here, one would use clear instead to correctly drop +the contents and thus not leak memory.

+
source

pub fn swap_remove(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

+

The removed element is replaced by the last element of the vector.

+

This does not preserve ordering, but is O(1).

+
Panics
+

Panics if index is out of bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::new();
+v.push("foo").unwrap();
+v.push("bar").unwrap();
+v.push("baz").unwrap();
+v.push("qux").unwrap();
+
+assert_eq!(v.swap_remove(1), "bar");
+assert_eq!(&*v, ["foo", "qux", "baz"]);
+
+assert_eq!(v.swap_remove(0), "foo");
+assert_eq!(&*v, ["baz", "qux"]);
+
source

pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

+

The removed element is replaced by the last element of the vector.

+

This does not preserve ordering, but is O(1).

+
Safety
+

Assumes index within bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::new();
+v.push("foo").unwrap();
+v.push("bar").unwrap();
+v.push("baz").unwrap();
+v.push("qux").unwrap();
+
+assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
+assert_eq!(&*v, ["foo", "qux", "baz"]);
+
+assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
+assert_eq!(&*v, ["baz", "qux"]);
+
source

pub fn is_full(&self) -> bool

Returns true if the vec is full

+
source

pub fn is_empty(&self) -> bool

Returns true if the vec is empty

+
source

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the Vec.

+

Always returns true if needle is an empty slice.

+
Examples
+
use heapless::Vec;
+
+let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+assert_eq!(v.starts_with(b""), true);
+assert_eq!(v.starts_with(b"ab"), true);
+assert_eq!(v.starts_with(b"bc"), false);
+
source

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the Vec.

+

Always returns true if needle is an empty slice.

+
Examples
+
use heapless::Vec;
+
+let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+assert_eq!(v.ends_with(b""), true);
+assert_eq!(v.ends_with(b"ab"), false);
+assert_eq!(v.ends_with(b"bc"), true);
+
source

pub fn insert(&mut self, index: usize, element: T) -> Result<(), T>

Inserts an element at position index within the vector, shifting all +elements after it to the right.

+

Returns back the element if the vector is full.

+
Panics
+

Panics if index > len.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+vec.insert(1, 4);
+assert_eq!(vec, [1, 4, 2, 3]);
+vec.insert(4, 5);
+assert_eq!(vec, [1, 4, 2, 3, 5]);
+
source

pub fn remove(&mut self, index: usize) -> T

Removes and returns the element at position index within the vector, +shifting all elements after it to the left.

+

Note: Because this shifts over the remaining elements, it has a +worst-case performance of O(n). If you don’t need the order of +elements to be preserved, use swap_remove instead. If you’d like to +remove elements from the beginning of the Vec, consider using +Deque::pop_front instead.

+
Panics
+

Panics if index is out of bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+assert_eq!(v.remove(1), 2);
+assert_eq!(v, [1, 3]);
+
source

pub fn retain<F>(&mut self, f: F)where + F: FnMut(&T) -> bool,

Retains only the elements specified by the predicate.

+

In other words, remove all elements e for which f(&e) returns false. +This method operates in place, visiting each element exactly once in the +original order, and preserves the order of the retained elements.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+vec.retain(|&x| x % 2 == 0);
+assert_eq!(vec, [2, 4]);
+

Because the elements are visited exactly once in the original order, +external state may be used to decide which elements to keep.

+ +
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4, 5]).unwrap();
+let keep = [false, true, true, false, true];
+let mut iter = keep.iter();
+vec.retain(|_| *iter.next().unwrap());
+assert_eq!(vec, [2, 3, 5]);
+
source

pub fn retain_mut<F>(&mut self, f: F)where + F: FnMut(&mut T) -> bool,

Retains only the elements specified by the predicate, passing a mutable reference to it.

+

In other words, remove all elements e such that f(&mut e) returns false. +This method operates in place, visiting each element exactly once in the +original order, and preserves the order of the retained elements.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+vec.retain_mut(|x| if *x <= 3 {
+    *x += 1;
+    true
+} else {
+    false
+});
+assert_eq!(vec, [2, 3, 4]);
+

Methods from Deref<Target = [T]>§

1.23.0

pub fn is_ascii(&self) -> bool

Checks if all bytes in this slice are within the ASCII range.

+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this slice is_ascii, returns it as a slice of +ASCII characters, otherwise returns None.

+

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this slice of bytes into a slice of ASCII characters, +without checking whether they’re valid.

+
Safety
+

Every byte in the slice must be in 0..=127, or else this is UB.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool

Checks that two slices are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
1.23.0

pub fn make_ascii_uppercase(&mut self)

Converts this slice to its ASCII upper case equivalent in-place.

+

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, +but non-ASCII letters are unchanged.

+

To return a new uppercased value without modifying the existing one, use +to_ascii_uppercase.

+
1.23.0

pub fn make_ascii_lowercase(&mut self)

Converts this slice to its ASCII lower case equivalent in-place.

+

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, +but non-ASCII letters are unchanged.

+

To return a new lowercased value without modifying the existing one, use +to_ascii_lowercase.

+
1.60.0

pub fn escape_ascii(&self) -> EscapeAscii<'_>

Returns an iterator that produces an escaped version of this slice, +treating it as an ASCII string.

+
Examples
+

+let s = b"0\t\r\n'\"\\\x9d";
+let escaped = s.escape_ascii().to_string();
+assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
+

pub fn trim_ascii_start(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
+assert_eq!(b"  ".trim_ascii_start(), b"");
+assert_eq!(b"".trim_ascii_start(), b"");
+

pub fn trim_ascii_end(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with trailing ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
+assert_eq!(b"  ".trim_ascii_end(), b"");
+assert_eq!(b"".trim_ascii_end(), b"");
+

pub fn trim_ascii(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading and trailing ASCII whitespace bytes +removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
+assert_eq!(b"  ".trim_ascii(), b"");
+assert_eq!(b"".trim_ascii(), b"");
+

pub fn as_str(&self) -> &str

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a UTF-8 str.

+

pub fn as_bytes(&self) -> &[u8]

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a slice of u8 bytes.

+

pub fn flatten(&self) -> &[T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &[[T; N]], and flattens it to a &[T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
+
+assert_eq!(
+    [[1, 2, 3], [4, 5, 6]].flatten(),
+    [[1, 2], [3, 4], [5, 6]].flatten(),
+);
+
+let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
+assert!(slice_of_empty_arrays.flatten().is_empty());
+
+let empty_slice_of_arrays: &[[u32; 10]] = &[];
+assert!(empty_slice_of_arrays.flatten().is_empty());
+

pub fn flatten_mut(&mut self) -> &mut [T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &mut [[T; N]], and flattens it to a &mut [T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+fn add_5_to_all(slice: &mut [i32]) {
+    for i in slice {
+        *i += 5;
+    }
+}
+
+let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
+add_5_to_all(array.flatten_mut());
+assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
+
1.0.0

pub fn len(&self) -> usize

Returns the number of elements in the slice.

+
Examples
+
let a = [1, 2, 3];
+assert_eq!(a.len(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if the slice has a length of 0.

+
Examples
+
let a = [1, 2, 3];
+assert!(!a.is_empty());
+
1.0.0

pub fn first(&self) -> Option<&T>

Returns the first element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&10), v.first());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.first());
+
1.0.0

pub fn first_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the first element of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(first) = x.first_mut() {
+    *first = 5;
+}
+assert_eq!(x, &[5, 1, 2]);
+
1.5.0

pub fn split_first(&self) -> Option<(&T, &[T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first() {
+    assert_eq!(first, &0);
+    assert_eq!(elements, &[1, 2]);
+}
+
1.5.0

pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_mut() {
+    *first = 3;
+    elements[0] = 4;
+    elements[1] = 5;
+}
+assert_eq!(x, &[3, 4, 5]);
+
1.5.0

pub fn split_last(&self) -> Option<(&T, &[T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last() {
+    assert_eq!(last, &2);
+    assert_eq!(elements, &[0, 1]);
+}
+
1.5.0

pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_mut() {
+    *last = 3;
+    elements[0] = 4;
+    elements[1] = 5;
+}
+assert_eq!(x, &[4, 5, 3]);
+
1.0.0

pub fn last(&self) -> Option<&T>

Returns the last element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&30), v.last());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.last());
+
1.0.0

pub fn last_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the last item in the slice.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(last) = x.last_mut() {
+    *last = 10;
+}
+assert_eq!(x, &[0, 1, 10]);
+

pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice, or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.first_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.first_chunk::<0>());
+

pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable reference to the first N elements of the slice, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some(first) = x.first_chunk_mut::<2>() {
+    first[0] = 5;
+    first[1] = 4;
+}
+assert_eq!(x, &[5, 4, 2]);
+

pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk::<2>() {
+    assert_eq!(first, &[0, 1]);
+    assert_eq!(elements, &[2]);
+}
+

pub fn split_first_chunk_mut<const N: usize>( + &mut self +) -> Option<(&mut [T; N], &mut [T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable reference to the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
+    first[0] = 3;
+    first[1] = 4;
+    elements[0] = 5;
+}
+assert_eq!(x, &[3, 4, 5]);
+

pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk::<2>() {
+    assert_eq!(last, &[1, 2]);
+    assert_eq!(elements, &[0]);
+}
+

pub fn split_last_chunk_mut<const N: usize>( + &mut self +) -> Option<(&mut [T; N], &mut [T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk_mut::<2>() {
+    last[0] = 3;
+    last[1] = 4;
+    elements[0] = 5;
+}
+assert_eq!(x, &[5, 3, 4]);
+

pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last element of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.last_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.last_chunk::<0>());
+

pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable pointer to the last item in the slice.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some(last) = x.last_chunk_mut::<2>() {
+    last[0] = 10;
+    last[1] = 20;
+}
+assert_eq!(x, &[0, 10, 20]);
+
1.0.0

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a reference to an element or subslice depending on the type of +index.

+
    +
  • If given a position, returns a reference to the element at that +position or None if out of bounds.
  • +
  • If given a range, returns the subslice corresponding to that range, +or None if out of bounds.
  • +
+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&40), v.get(1));
+assert_eq!(Some(&[10, 40][..]), v.get(0..2));
+assert_eq!(None, v.get(3));
+assert_eq!(None, v.get(0..4));
+
1.0.0

pub fn get_mut<I>( + &mut self, + index: I +) -> Option<&mut <I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice depending on the +type of index (see get) or None if the index is out of bounds.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(elem) = x.get_mut(1) {
+    *elem = 42;
+}
+assert_eq!(x, &[0, 42, 2]);
+
1.0.0

pub unsafe fn get_unchecked<I>( + &self, + index: I +) -> &<I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a reference to an element or subslice, without doing bounds +checking.

+

For a safe alternative see get.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &[1, 2, 4];
+
+unsafe {
+    assert_eq!(x.get_unchecked(1), &2);
+}
+
1.0.0

pub unsafe fn get_unchecked_mut<I>( + &mut self, + index: I +) -> &mut <I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice, without doing +bounds checking.

+

For a safe alternative see get_mut.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &mut [1, 2, 4];
+
+unsafe {
+    let elem = x.get_unchecked_mut(1);
+    *elem = 13;
+}
+assert_eq!(x, &[1, 13, 4]);
+
1.0.0

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

The caller must also ensure that the memory the pointer (non-transitively) points to +is never written to (except inside an UnsafeCell) using this pointer or any pointer +derived 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 +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &[1, 2, 4];
+let x_ptr = x.as_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
+    }
+}
+
1.0.0

pub fn as_mut_ptr(&mut self) -> *mut T

Returns an unsafe mutable pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

Modifying the container referenced by this slice may cause its buffer +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &mut [1, 2, 4];
+let x_ptr = x.as_mut_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        *x_ptr.add(i) += 2;
+    }
+}
+assert_eq!(x, &[3, 4, 6]);
+
1.48.0

pub fn as_ptr_range(&self) -> Range<*const T>

Returns the two raw pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_ptr for warnings on using these pointers. The end pointer +requires extra caution, as it does not point to a valid element in the +slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+

It can also be useful to check if a pointer to an element refers to an +element of this slice:

+ +
let a = [1, 2, 3];
+let x = &a[1] as *const _;
+let y = &5 as *const _;
+
+assert!(a.as_ptr_range().contains(&x));
+assert!(!a.as_ptr_range().contains(&y));
+
1.48.0

pub fn as_mut_ptr_range(&mut self) -> Range<*mut T>

Returns the two unsafe mutable pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_mut_ptr for warnings on using these pointers. The end +pointer requires extra caution, as it does not point to a valid element +in the slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+
1.0.0

pub fn swap(&mut self, a: usize, b: usize)

Swaps two elements in the slice.

+

If a equals to b, it’s guaranteed that elements won’t change value.

+
Arguments
+
    +
  • a - The index of the first element
  • +
  • b - The index of the second element
  • +
+
Panics
+

Panics if a or b are out of bounds.

+
Examples
+
let mut v = ["a", "b", "c", "d", "e"];
+v.swap(2, 4);
+assert!(v == ["a", "b", "e", "d", "c"]);
+

pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)

🔬This is a nightly-only experimental API. (slice_swap_unchecked)

Swaps two elements in the slice, without doing bounds checking.

+

For a safe alternative see swap.

+
Arguments
+
    +
  • a - The index of the first element
  • +
  • b - The index of the second element
  • +
+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior. +The caller has to ensure that a < self.len() and b < self.len().

+
Examples
+
#![feature(slice_swap_unchecked)]
+
+let mut v = ["a", "b", "c", "d"];
+// SAFETY: we know that 1 and 3 are both indices of the slice
+unsafe { v.swap_unchecked(1, 3) };
+assert!(v == ["a", "d", "c", "b"]);
+
1.0.0

pub fn reverse(&mut self)

Reverses the order of elements in the slice, in place.

+
Examples
+
let mut v = [1, 2, 3];
+v.reverse();
+assert!(v == [3, 2, 1]);
+
1.0.0

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the slice.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &[1, 2, 4];
+let mut iterator = x.iter();
+
+assert_eq!(iterator.next(), Some(&1));
+assert_eq!(iterator.next(), Some(&2));
+assert_eq!(iterator.next(), Some(&4));
+assert_eq!(iterator.next(), None);
+
1.0.0

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns an iterator that allows modifying each value.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &mut [1, 2, 4];
+for elem in x.iter_mut() {
+    *elem += 2;
+}
+assert_eq!(x, &[3, 4, 6]);
+
1.0.0

pub fn windows(&self, size: usize) -> Windows<'_, T>

Returns an iterator over all contiguous windows of length +size. The windows overlap. If the slice is shorter than +size, the iterator returns no values.

+
Panics
+

Panics if size is 0.

+
Examples
+
let slice = ['r', 'u', 's', 't'];
+let mut iter = slice.windows(2);
+assert_eq!(iter.next().unwrap(), &['r', 'u']);
+assert_eq!(iter.next().unwrap(), &['u', 's']);
+assert_eq!(iter.next().unwrap(), &['s', 't']);
+assert!(iter.next().is_none());
+

If the slice is shorter than size:

+ +
let slice = ['f', 'o', 'o'];
+let mut iter = slice.windows(4);
+assert!(iter.next().is_none());
+

There’s no windows_mut, as that existing would let safe code violate the +“only one &mut at a time to the same thing” rule. However, you can sometimes +use Cell::as_slice_of_cells in +conjunction with windows to accomplish something similar:

+ +
use std::cell::Cell;
+
+let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
+let slice = &mut array[..];
+let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
+for w in slice_of_cells.windows(3) {
+    Cell::swap(&w[0], &w[2]);
+}
+assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
+
1.0.0

pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and rchunks for the same iterator but starting at the end of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert_eq!(iter.next().unwrap(), &['m']);
+assert!(iter.next().is_none());
+
1.0.0

pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length 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 +exactly chunk_size elements, and rchunks_mut for the same iterator but starting at +the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.chunks_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 3]);
+
1.31.0

pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of chunks.

+

See chunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and rchunks_exact for the same iterator but starting at the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+
1.31.0

pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length of the slice, then the last up to chunk_size-1 elements will be omitted and can be +retrieved from the into_remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting 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 +smaller chunk, and rchunks_exact_mut for the same iterator but starting at the end of +the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.chunks_exact_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 0]);
+

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &[[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &[[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
+

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (chunks, remainder) = slice.as_chunks();
+assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
+assert_eq!(remainder, &['m']);
+

If you expect the slice to be an exact multiple, you can combine +let-else with an empty slice pattern:

+ +
#![feature(slice_as_chunks)]
+let slice = ['R', 'u', 's', 't'];
+let (chunks, []) = slice.as_chunks::<2>() else {
+    panic!("slice didn't have even length")
+};
+assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
+

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (remainder, chunks) = slice.as_rchunks();
+assert_eq!(remainder, &['l']);
+assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
+

pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are array references and do not overlap. If N does not divide the +length of the slice, then the last up to N-1 elements will be omitted and can be +retrieved from the remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.array_chunks();
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub unsafe fn as_chunks_unchecked_mut<const N: usize>( + &mut self +) -> &mut [[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &mut [[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked_mut() };
+chunks[0] = ['L'];
+assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &mut [[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked_mut() };
+chunks[1] = ['a', 'x', '?'];
+assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
+

pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+let (chunks, remainder) = v.as_chunks_mut();
+remainder[0] = 9;
+for chunk in chunks {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 9]);
+

pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+let (remainder, chunks) = v.as_rchunks_mut();
+remainder[0] = 9;
+for chunk in chunks {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[9, 1, 1, 2, 2]);
+

pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable array references and do not overlap. If N does not divide +the length of the slice, then the last up to N-1 elements will be omitted and +can be retrieved from the into_remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact_mut.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.array_chunks_mut() {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 0]);
+

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>

🔬This is a nightly-only experimental API. (array_windows)

Returns an iterator over overlapping windows of N elements of a slice, +starting 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
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_windows)]
+let slice = [0, 1, 2, 3];
+let mut iter = slice.array_windows();
+assert_eq!(iter.next().unwrap(), &[0, 1]);
+assert_eq!(iter.next().unwrap(), &[1, 2]);
+assert_eq!(iter.next().unwrap(), &[2, 3]);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and chunks for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert_eq!(iter.next().unwrap(), &['l']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length 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 +exactly chunk_size elements, and chunks_mut for the same iterator but starting at the +beginning of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.rchunks_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[3, 2, 2, 1, 1]);
+
1.31.0

pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +end of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of rchunks.

+

See rchunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and chunks_exact for the same iterator but starting at the beginning of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['l']);
+
1.31.0

pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length of the slice, then the last up to chunk_size-1 elements will be omitted and can be +retrieved from the into_remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting 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 +smaller chunk, and chunks_exact_mut for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.rchunks_exact_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[0, 2, 2, 1, 1]);
+

pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping runs +of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&[3, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+

pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping mutable +runs of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by_mut(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&mut [3, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by_mut(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+
1.0.0

pub fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let v = [1, 2, 3, 4, 5, 6];
+
+{
+   let (left, right) = v.split_at(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+
1.0.0

pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])

Divides one mutable slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let mut v = [1, 0, 3, 0, 5, 6];
+let (left, right) = v.split_at_mut(2);
+assert_eq!(left, [1, 0]);
+assert_eq!(right, [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let v = [1, 2, 3, 4, 5, 6];
+
+unsafe {
+   let (left, right) = v.split_at_unchecked(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub unsafe fn split_at_mut_unchecked( + &mut self, + mid: usize +) -> (&mut [T], &mut [T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one mutable slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at_mut.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let mut v = [1, 0, 3, 0, 5, 6];
+// scoped to restrict the lifetime of the borrows
+unsafe {
+    let (left, right) = v.split_at_mut_unchecked(2);
+    assert_eq!(left, [1, 0]);
+    assert_eq!(right, [3, 0, 5, 6]);
+    left[1] = 2;
+    right[1] = 4;
+}
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.split_array_ref::<0>();
+   assert_eq!(left, &[]);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<2>();
+    assert_eq!(left, &[1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<6>();
+    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T])

🔬This is a nightly-only experimental API. (split_array)

Divides one mutable slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let mut v = &mut [1, 0, 3, 0, 5, 6][..];
+let (left, right) = v.split_array_mut::<2>();
+assert_eq!(left, &mut [1, 0]);
+assert_eq!(right, [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index from +the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index len - N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.rsplit_array_ref::<0>();
+   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+   assert_eq!(right, &[]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<2>();
+    assert_eq!(left, [1, 2, 3, 4]);
+    assert_eq!(right, &[5, 6]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<6>();
+    assert_eq!(left, []);
+    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
+}
+

pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one mutable slice into an array and a remainder slice at an +index from the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let mut v = &mut [1, 0, 3, 0, 5, 6][..];
+let (left, right) = v.rsplit_array_mut::<4>();
+assert_eq!(left, [1, 0]);
+assert_eq!(right, &mut [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+
1.0.0

pub fn split<F>(&self, pred: F) -> Split<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is not contained in the subslices.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the first element is matched, an empty slice will be the first item +returned by the iterator. Similarly, if the last element in the slice +is matched, an empty slice will be the last item returned by the +iterator:

+ +
let slice = [10, 40, 33];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert!(iter.next().is_none());
+

If two matched elements are directly adjacent, an empty slice will be +present between them:

+ +
let slice = [10, 6, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+
1.0.0

pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred. The matched element is not contained in the subslices.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.split_mut(|num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(v, [1, 40, 30, 1, 60, 1]);
+
1.51.0

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is contained in the end of the previous +subslice as a terminator.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the last element of the slice is matched, +that element will be considered the terminator of the preceding slice. +That slice will be the last item returned by the iterator.

+ +
let slice = [3, 10, 40, 33];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[3]);
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert!(iter.next().is_none());
+
1.51.0

pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred. The matched element is contained in the previous +subslice as a terminator.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
+    let terminator_idx = group.len()-1;
+    group[terminator_idx] = 1;
+}
+assert_eq!(v, [10, 40, 1, 20, 1, 1]);
+
1.27.0

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, starting at the end of the slice and working backwards. +The matched element is not contained in the subslices.

+
Examples
+
let slice = [11, 22, 33, 0, 44, 55];
+let mut iter = slice.rsplit(|num| *num == 0);
+
+assert_eq!(iter.next().unwrap(), &[44, 55]);
+assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
+assert_eq!(iter.next(), None);
+

As with split(), if the first or last element is matched, an empty +slice will be the first (or last) item returned by the iterator.

+ +
let v = &[0, 1, 1, 2, 3, 5, 8];
+let mut it = v.rsplit(|n| *n % 2 == 0);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next().unwrap(), &[3, 5]);
+assert_eq!(it.next().unwrap(), &[1, 1]);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next(), None);
+
1.27.0

pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred, starting at the end of the slice and working +backwards. The matched element is not contained in the subslices.

+
Examples
+
let mut v = [100, 400, 300, 200, 600, 500];
+
+let mut count = 0;
+for group in v.rsplit_mut(|num| *num % 3 == 0) {
+    count += 1;
+    group[0] = count;
+}
+assert_eq!(v, [3, 400, 300, 2, 600, 1]);
+
1.0.0

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once by numbers divisible by 3 (i.e., [10, 40], +[20, 60, 50]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn_mut(2, |num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(v, [1, 40, 30, 1, 60, 50]);
+
1.0.0

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once, starting from the end, by numbers divisible +by 3 (i.e., [50], [10, 40, 30, 20]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.rsplitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+
let mut s = [10, 40, 30, 20, 60, 50];
+
+for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(s, [1, 40, 30, 20, 60, 1]);
+
1.0.0

pub fn contains(&self, x: &T) -> boolwhere + T: PartialEq<T>,

Returns true if the slice contains an element with the given value.

+

This operation is O(n).

+

Note that if you have a sorted slice, binary_search may be faster.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.contains(&30));
+assert!(!v.contains(&50));
+

If you do not have a &T, but some other value that you can compare +with one (for example, String implements PartialEq<str>), you can +use iter().any:

+ +
let v = [String::from("hello"), String::from("world")]; // slice of `String`
+assert!(v.iter().any(|e| e == "hello")); // search with `&str`
+assert!(!v.iter().any(|e| e == "hi"));
+
1.0.0

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.starts_with(&[10]));
+assert!(v.starts_with(&[10, 40]));
+assert!(!v.starts_with(&[50]));
+assert!(!v.starts_with(&[10, 50]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.starts_with(&[]));
+let v: &[u8] = &[];
+assert!(v.starts_with(&[]));
+
1.0.0

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.ends_with(&[30]));
+assert!(v.ends_with(&[40, 30]));
+assert!(!v.ends_with(&[50]));
+assert!(!v.ends_with(&[50, 30]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.ends_with(&[]));
+let v: &[u8] = &[];
+assert!(v.ends_with(&[]));
+
1.51.0

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the prefix removed.

+

If the slice starts with prefix, returns the subslice after the prefix, wrapped in Some. +If prefix is empty, simply returns the original slice.

+

If the slice does not start with prefix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
+assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
+assert_eq!(v.strip_prefix(&[50]), None);
+assert_eq!(v.strip_prefix(&[10, 50]), None);
+
+let prefix : &str = "he";
+assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
+           Some(b"llo".as_ref()));
+
1.51.0

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the suffix removed.

+

If the slice ends with suffix, returns the subslice before the suffix, wrapped in Some. +If suffix is empty, simply returns the original slice.

+

If the slice does not end with suffix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
+assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
+assert_eq!(v.strip_suffix(&[50]), None);
+assert_eq!(v.strip_suffix(&[50, 30]), None);
+

Binary searches this slice for a given element. +If the slice is not sorted, the returned result is unspecified and +meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search_by, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+assert_eq!(s.binary_search(&13),  Ok(9));
+assert_eq!(s.binary_search(&4),   Err(7));
+assert_eq!(s.binary_search(&100), Err(13));
+let r = s.binary_search(&1);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+

If you want to find that whole range of matching items, rather than +an 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];
+
+let low = s.partition_point(|x| x < &1);
+assert_eq!(low, 1);
+let high = s.partition_point(|x| x <= &1);
+assert_eq!(high, 5);
+let r = s.binary_search(&1);
+assert!((low..high).contains(&r.unwrap()));
+
+assert!(s[..low].iter().all(|&x| x < 1));
+assert!(s[low..high].iter().all(|&x| x == 1));
+assert!(s[high..].iter().all(|&x| x > 1));
+
+// For something not found, the "range" of equal items is empty
+assert_eq!(s.partition_point(|x| x < &11), 9);
+assert_eq!(s.partition_point(|x| x <= &11), 9);
+assert_eq!(s.binary_search(&11), Err(9));
+

If you want to insert an item to a sorted vector, while maintaining +sort order, consider using partition_point:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+
1.0.0

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where + F: FnMut(&'a T) -> Ordering,

Binary searches this slice with a comparator function.

+

The comparator function should return an order code that indicates +whether its argument is Less, Equal or Greater the desired +target. +If the slice is not sorted or if the comparator function does not +implement an order consistent with the sort order of the underlying +slice, the returned result is unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+let seek = 13;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
+let seek = 4;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
+let seek = 100;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
+let seek = 1;
+let r = s.binary_search_by(|probe| probe.cmp(&seek));
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.10.0

pub fn binary_search_by_key<'a, B, F>( + &'a self, + b: &B, + f: F +) -> Result<usize, usize>where + F: FnMut(&'a T) -> B, + B: Ord,

Binary searches this slice with a key extraction function.

+

Assumes that the slice is sorted by the key, for instance with +sort_by_key using the same key extraction function. +If the slice is not sorted by the key, the returned result is +unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by, and partition_point.

+
Examples
+

Looks up a series of four elements in a slice of pairs sorted by +their second elements. The first is found, with a uniquely +determined position; the second and third are not found; the +fourth could match any position in [1, 4].

+ +
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
+         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
+         (1, 21), (2, 34), (4, 55)];
+
+assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
+assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
+assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
+let r = s.binary_search_by_key(&1, |&(a, b)| b);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.20.0

pub fn sort_unstable(&mut self)where + T: Ord,

Sorts the slice, but might not preserve the order of equal elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(n * log(n)) worst-case.

+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

It is typically faster than stable sorting, except in a few special cases, e.g., when the +slice consists of several concatenated sorted sequences.

+
Examples
+
let mut v = [-5, 4, 1, -3, 2];
+
+v.sort_unstable();
+assert!(v == [-5, -3, 1, 2, 4]);
+
1.20.0

pub fn sort_unstable_by<F>(&mut self, compare: F)where + F: FnMut(&T, &T) -> Ordering,

Sorts the slice with a comparator function, but might not preserve the order of equal +elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(n * log(n)) worst-case.

+

The comparator function must define a total ordering for the elements in the slice. If +the ordering is not total, the order of the elements is unspecified. An order is a +total order if it is (for all a, b and c):

+
    +
  • total and antisymmetric: exactly one of a < b, a == b or a > b is true, and
  • +
  • transitive, a < b and b < c implies a < c. The same must hold for both == and >.
  • +
+

For example, while [f64] doesn’t implement [Ord] because NaN != NaN, we can use +partial_cmp as our sort function when we know the slice doesn’t contain a NaN.

+ +
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
+floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
+assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

It is typically faster than stable sorting, except in a few special cases, e.g., when the +slice consists of several concatenated sorted sequences.

+
Examples
+
let mut v = [5, 4, 1, 3, 2];
+v.sort_unstable_by(|a, b| a.cmp(b));
+assert!(v == [1, 2, 3, 4, 5]);
+
+// reverse sorting
+v.sort_unstable_by(|a, b| b.cmp(a));
+assert!(v == [5, 4, 3, 2, 1]);
+
1.20.0

pub fn sort_unstable_by_key<K, F>(&mut self, f: F)where + F: FnMut(&T) -> K, + K: Ord,

Sorts the slice with a key extraction function, but might not preserve the order of equal +elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(m * n * log(n)) worst-case, where the key function is +O(m).

+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

Due to its key calling strategy, sort_unstable_by_key +is likely to be slower than sort_by_cached_key in +cases where the key function is expensive.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+v.sort_unstable_by_key(|k| k.abs());
+assert!(v == [1, 2, -3, 4, -5]);
+
1.49.0

pub fn select_nth_unstable( + &mut self, + index: usize +) -> (&mut [T], &mut T, &mut [T])where + T: Ord,

Reorder the slice such that the element at index is at its final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index. Additionally, this reordering is +unstable (i.e. any number of equal elements may end up at position index), in-place +(i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from the reordered slice: +the subslice prior to index, the element at index, and the subslice after index; +accordingly, the values in those two subslices will respectively all be less-than-or-equal-to +and greater-than-or-equal-to the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Find the median
+v.select_nth_unstable(2);
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [-3, -5, 1, 2, 4] ||
+        v == [-5, -3, 1, 2, 4] ||
+        v == [-3, -5, 1, 4, 2] ||
+        v == [-5, -3, 1, 4, 2]);
+
1.49.0

pub fn select_nth_unstable_by<F>( + &mut self, + index: usize, + compare: F +) -> (&mut [T], &mut T, &mut [T])where + F: FnMut(&T, &T) -> Ordering,

Reorder the slice with a comparator function such that the element at index is at its +final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index using the comparator function. +Additionally, this reordering is unstable (i.e. any number of equal elements may end up at +position index), in-place (i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from +the slice reordered according to the provided comparator function: the subslice prior to +index, the element at index, and the subslice after index; accordingly, the values in +those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to +the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Find the median as if the slice were sorted in descending order.
+v.select_nth_unstable_by(2, |a, b| b.cmp(a));
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [2, 4, 1, -5, -3] ||
+        v == [2, 4, 1, -3, -5] ||
+        v == [4, 2, 1, -5, -3] ||
+        v == [4, 2, 1, -3, -5]);
+
1.49.0

pub fn select_nth_unstable_by_key<K, F>( + &mut self, + index: usize, + f: F +) -> (&mut [T], &mut T, &mut [T])where + F: FnMut(&T) -> K, + K: Ord,

Reorder the slice with a key extraction function such that the element at index is at its +final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index using the key extraction function. +Additionally, this reordering is unstable (i.e. any number of equal elements may end up at +position index), in-place (i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from +the slice reordered according to the provided key extraction function: the subslice prior to +index, the element at index, and the subslice after index; accordingly, the values in +those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to +the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Return the median as if the array were sorted according to absolute value.
+v.select_nth_unstable_by_key(2, |a| a.abs());
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [1, 2, -3, 4, -5] ||
+        v == [1, 2, -3, -5, 4] ||
+        v == [2, 1, -3, 4, -5] ||
+        v == [2, 1, -3, -5, 4]);
+

pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where + T: PartialEq<T>,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all consecutive repeated elements to the end of the slice according to the +[PartialEq] trait implementation.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
+
+let (dedup, duplicates) = slice.partition_dedup();
+
+assert_eq!(dedup, [1, 2, 3, 2, 1]);
+assert_eq!(duplicates, [2, 3, 1]);
+

pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])where + F: FnMut(&mut T, &mut T) -> bool,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice satisfying +a given equality relation.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

The same_bucket function is passed references to two elements from the slice and +must determine if the elements compare equal. The elements are passed in opposite order +from their order in the slice, so if same_bucket(a, b) returns true, a is moved +at the end of the slice.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
+
+let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
+
+assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
+assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
+

pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])where + F: FnMut(&mut T) -> K, + K: PartialEq<K>,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice that resolve +to the same key.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
+
+let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
+
+assert_eq!(dedup, [10, 20, 30, 20, 11]);
+assert_eq!(duplicates, [21, 30, 13]);
+
1.26.0

pub fn rotate_left(&mut self, mid: usize)

Rotates the slice in-place such that the first mid elements of the +slice move to the end while the last self.len() - mid elements move to +the front. After calling rotate_left, the element previously at index +mid will become the first element in the slice.

+
Panics
+

This function will panic if mid is greater than the length of the +slice. Note that mid == self.len() does not panic and is a no-op +rotation.

+
Complexity
+

Takes linear (in self.len()) time.

+
Examples
+
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a.rotate_left(2);
+assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
+

Rotating a subslice:

+ +
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a[1..5].rotate_left(1);
+assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
+
1.26.0

pub fn rotate_right(&mut self, k: usize)

Rotates the slice in-place such that the first self.len() - k +elements of the slice move to the end while the last k elements move +to the front. After calling rotate_right, the element previously at +index self.len() - k will become the first element in the slice.

+
Panics
+

This function will panic if k is greater than the length of the +slice. Note that k == self.len() does not panic and is a no-op +rotation.

+
Complexity
+

Takes linear (in self.len()) time.

+
Examples
+
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a.rotate_right(2);
+assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
+

Rotate a subslice:

+ +
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a[1..5].rotate_right(1);
+assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
+
1.50.0

pub fn fill(&mut self, value: T)where + T: Clone,

Fills self with elements by cloning value.

+
Examples
+
let mut buf = vec![0; 10];
+buf.fill(1);
+assert_eq!(buf, vec![1; 10]);
+
1.51.0

pub fn fill_with<F>(&mut self, f: F)where + F: FnMut() -> T,

Fills self with elements returned by calling a closure repeatedly.

+

This method uses a closure to create new values. If you’d rather +[Clone] a given value, use fill. If you want to use the [Default] +trait to generate values, you can pass [Default::default] as the +argument.

+
Examples
+
let mut buf = vec![1; 10];
+buf.fill_with(Default::default);
+assert_eq!(buf, vec![0; 10]);
+
1.7.0

pub fn clone_from_slice(&mut self, src: &[T])where + T: Clone,

Copies the elements from src into self.

+

The length of src must be the same as self.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Examples
+

Cloning two elements from a slice into another:

+ +
let src = [1, 2, 3, 4];
+let mut dst = [0, 0];
+
+// Because the slices have to be the same length,
+// we slice the source slice from four elements
+// to two. It will panic if we don't do this.
+dst.clone_from_slice(&src[2..]);
+
+assert_eq!(src, [1, 2, 3, 4]);
+assert_eq!(dst, [3, 4]);
+

Rust enforces that there can only be one mutable reference with no +immutable references to a particular piece of data in a particular +scope. Because of this, attempting to use clone_from_slice on a +single slice will result in a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+slice[..2].clone_from_slice(&slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.clone_from_slice(&right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 4, 5]);
+
1.9.0

pub fn copy_from_slice(&mut self, src: &[T])where + T: Copy,

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.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Examples
+

Copying two elements from a slice into another:

+ +
let src = [1, 2, 3, 4];
+let mut dst = [0, 0];
+
+// Because the slices have to be the same length,
+// we slice the source slice from four elements
+// to two. It will panic if we don't do this.
+dst.copy_from_slice(&src[2..]);
+
+assert_eq!(src, [1, 2, 3, 4]);
+assert_eq!(dst, [3, 4]);
+

Rust enforces that there can only be one mutable reference with no +immutable references to a particular piece of data in a particular +scope. Because of this, attempting to use copy_from_slice on a +single slice will result in a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+slice[..2].copy_from_slice(&slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.copy_from_slice(&right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 4, 5]);
+
1.37.0

pub fn copy_within<R>(&mut self, src: R, dest: usize)where + R: RangeBounds<usize>, + T: Copy,

Copies elements from one part of the slice to another part of itself, +using a memmove.

+

src is the range within self to copy from. dest is the starting +index of the range within self to copy to, which will have the same +length as src. The two ranges may overlap. The ends of the two ranges +must be less than or equal to self.len().

+
Panics
+

This function will panic if either range exceeds the end of the slice, +or if the end of src is before the start.

+
Examples
+

Copying four bytes within a slice:

+ +
let mut bytes = *b"Hello, World!";
+
+bytes.copy_within(1..5, 8);
+
+assert_eq!(&bytes, b"Hello, Wello!");
+
1.27.0

pub fn swap_with_slice(&mut self, other: &mut [T])

Swaps all elements in self with those in other.

+

The length of other must be the same as self.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Example
+

Swapping two elements across slices:

+ +
let mut slice1 = [0, 0];
+let mut slice2 = [1, 2, 3, 4];
+
+slice1.swap_with_slice(&mut slice2[2..]);
+
+assert_eq!(slice1, [3, 4]);
+assert_eq!(slice2, [1, 2, 0, 0]);
+

Rust enforces that there can only be one mutable reference to a +particular piece of data in a particular scope. Because of this, +attempting to use swap_with_slice on a single slice will result in +a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +mutable sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.swap_with_slice(&mut right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 1, 2]);
+
1.30.0

pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])

Transmute the slice to a slice of another type, ensuring alignment of the types is +maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+
1.30.0

pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])

Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the +types is maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])where + Simd<T, LANES>: AsRef<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

+

This is a safe wrapper around [slice::align_to], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+
Examples
+
#![feature(portable_simd)]
+use core::simd::SimdFloat;
+
+let short = &[1, 2, 3];
+let (prefix, middle, suffix) = short.as_simd::<4>();
+assert_eq!(middle, []); // Not enough elements for anything in the middle
+
+// They might be split in any possible way between prefix and suffix
+let it = prefix.iter().chain(suffix).copied();
+assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
+
+fn basic_simd_sum(x: &[f32]) -> f32 {
+    use std::ops::Add;
+    use std::simd::f32x4;
+    let (prefix, middle, suffix) = x.as_simd();
+    let sums = f32x4::from_array([
+        prefix.iter().copied().sum(),
+        0.0,
+        0.0,
+        suffix.iter().copied().sum(),
+    ]);
+    let sums = middle.iter().copied().fold(sums, f32x4::add);
+    sums.reduce_sum()
+}
+
+let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
+assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
+

pub fn as_simd_mut<const LANES: usize>( + &mut self +) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])where + Simd<T, LANES>: AsMut<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, +and a mutable suffix.

+

This is a safe wrapper around [slice::align_to_mut], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+

This is the mutable version of [slice::as_simd]; see that for examples.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+

pub fn is_sorted(&self) -> boolwhere + T: PartialOrd<T>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted.

+

That is, for each element a and its following element b, a <= b must hold. If the +slice yields exactly zero or one element, true is returned.

+

Note that if Self::Item is only PartialOrd, but not Ord, the above definition +implies that this function returns false if any two consecutive items are not +comparable.

+
Examples
+
#![feature(is_sorted)]
+let empty: [i32; 0] = [];
+
+assert!([1, 2, 2, 9].is_sorted());
+assert!(![1, 3, 2, 4].is_sorted());
+assert!([0].is_sorted());
+assert!(empty.is_sorted());
+assert!(![0.0, 1.0, f32::NAN].is_sorted());
+

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> boolwhere + F: FnMut(&'a T, &'a T) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given comparator function.

+

Instead of using PartialOrd::partial_cmp, this function uses the given compare +function to determine the ordering of two elements. Apart from that, it’s equivalent to +is_sorted; see its documentation for more information.

+

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> boolwhere + F: FnMut(&'a T) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given key extraction function.

+

Instead of comparing the slice’s elements directly, this function compares the keys of the +elements, as determined by f. Apart from that, it’s equivalent to is_sorted; see its +documentation for more information.

+
Examples
+
#![feature(is_sorted)]
+
+assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
+assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
+
1.52.0

pub fn partition_point<P>(&self, pred: P) -> usizewhere + P: FnMut(&T) -> bool,

Returns the index of the partition point according to the given predicate +(the index of the first element of the second partition).

+

The slice is assumed to be partitioned according to the given predicate. +This means that all elements for which the predicate returns true are at the start of the slice +and all elements for which the predicate returns false are at the end. +For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 +(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, +as this method performs a kind of binary search.

+

See also binary_search, binary_search_by, and binary_search_by_key.

+
Examples
+
let v = [1, 2, 3, 3, 5, 6, 7];
+let i = v.partition_point(|&x| x < 5);
+
+assert_eq!(i, 4);
+assert!(v[..i].iter().all(|&x| x < 5));
+assert!(v[i..].iter().all(|&x| !(x < 5)));
+

If all elements of the slice match the predicate, including if the slice +is empty, then the length of the slice will be returned:

+ +
let a = [2, 4, 8];
+assert_eq!(a.partition_point(|x| x < &100), a.len());
+let a: [i32; 0] = [];
+assert_eq!(a.partition_point(|x| x < &100), 0);
+

If you want to insert an item to a sorted vector, while maintaining +sort order:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+

pub fn take<R, 'a>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where + R: OneSidedRange<usize>,

🔬This is a nightly-only experimental API. (slice_take)

Removes the subslice corresponding to the given range +and returns a reference to it.

+

Returns None and does not modify the slice if the given +range is out of bounds.

+

Note that this method only accepts one-sided ranges such as +2.. or ..6, but not 2..6.

+
Examples
+

Taking the first three elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+let mut first_three = slice.take(..3).unwrap();
+
+assert_eq!(slice, &['d']);
+assert_eq!(first_three, &['a', 'b', 'c']);
+

Taking the last two elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+let mut tail = slice.take(2..).unwrap();
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(tail, &['c', 'd']);
+

Getting None when range is out of bounds:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+
+assert_eq!(None, slice.take(5..));
+assert_eq!(None, slice.take(..5));
+assert_eq!(None, slice.take(..=4));
+let expected: &[char] = &['a', 'b', 'c', 'd'];
+assert_eq!(Some(expected), slice.take(..4));
+

pub fn take_mut<R, 'a>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>where + R: OneSidedRange<usize>,

🔬This is a nightly-only experimental API. (slice_take)

Removes the subslice corresponding to the given range +and returns a mutable reference to it.

+

Returns None and does not modify the slice if the given +range is out of bounds.

+

Note that this method only accepts one-sided ranges such as +2.. or ..6, but not 2..6.

+
Examples
+

Taking the first three elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+let mut first_three = slice.take_mut(..3).unwrap();
+
+assert_eq!(slice, &mut ['d']);
+assert_eq!(first_three, &mut ['a', 'b', 'c']);
+

Taking the last two elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+let mut tail = slice.take_mut(2..).unwrap();
+
+assert_eq!(slice, &mut ['a', 'b']);
+assert_eq!(tail, &mut ['c', 'd']);
+

Getting None when range is out of bounds:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+
+assert_eq!(None, slice.take_mut(5..));
+assert_eq!(None, slice.take_mut(..5));
+assert_eq!(None, slice.take_mut(..=4));
+let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+assert_eq!(Some(expected), slice.take_mut(..4));
+

pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the first element of the slice and returns a reference +to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c'];
+let first = slice.take_first().unwrap();
+
+assert_eq!(slice, &['b', 'c']);
+assert_eq!(first, &'a');
+

pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the first element of the slice and returns a mutable +reference to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
+let first = slice.take_first_mut().unwrap();
+*first = 'd';
+
+assert_eq!(slice, &['b', 'c']);
+assert_eq!(first, &'d');
+

pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the last element of the slice and returns a reference +to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c'];
+let last = slice.take_last().unwrap();
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(last, &'c');
+

pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the last element of the slice and returns a mutable +reference to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
+let last = slice.take_last_mut().unwrap();
+*last = 'd';
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(last, &'d');
+

pub unsafe fn get_many_unchecked_mut<const N: usize>( + &mut self, + indices: [usize; N] +) -> [&mut T; N]

🔬This is a nightly-only experimental API. (get_many_mut)

Returns mutable references to many indices at once, without doing any checks.

+

For a safe alternative see get_many_mut.

+
Safety
+

Calling this method with overlapping or out-of-bounds indices is undefined behavior +even if the resulting references are not used.

+
Examples
+
#![feature(get_many_mut)]
+
+let x = &mut [1, 2, 4];
+
+unsafe {
+    let [a, b] = x.get_many_unchecked_mut([0, 2]);
+    *a *= 10;
+    *b *= 100;
+}
+assert_eq!(x, &[10, 2, 400]);
+

pub fn get_many_mut<const N: usize>( + &mut self, + indices: [usize; N] +) -> Result<[&mut T; N], GetManyMutError<N>>

🔬This is a nightly-only experimental API. (get_many_mut)

Returns mutable references to many indices at once.

+

Returns an error if any index is out-of-bounds, or if the same index was +passed more than once.

+
Examples
+
#![feature(get_many_mut)]
+
+let v = &mut [1, 2, 3];
+if let Ok([a, b]) = v.get_many_mut([0, 2]) {
+    *a = 413;
+    *b = 612;
+}
+assert_eq!(v, &[413, 2, 612]);
+

pub fn sort_floats(&mut self)

🔬This is a nightly-only experimental API. (sort_floats)

Sorts the slice of floats.

+

This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses +the ordering defined by [f32::total_cmp].

+
Current implementation
+

This uses the same sorting algorithm as sort_unstable_by.

+
Examples
+
#![feature(sort_floats)]
+let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
+
+v.sort_floats();
+let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
+assert_eq!(&v[..8], &sorted[..8]);
+assert!(v[8].is_nan());
+

pub fn sort_floats(&mut self)

🔬This is a nightly-only experimental API. (sort_floats)

Sorts the slice of floats.

+

This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses +the ordering defined by [f64::total_cmp].

+
Current implementation
+

This uses the same sorting algorithm as sort_unstable_by.

+
Examples
+
#![feature(sort_floats)]
+let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
+
+v.sort_floats();
+let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
+assert_eq!(&v[..8], &sorted[..8]);
+assert!(v[8].is_nan());
+

Trait Implementations§

source§

impl<T, const N: usize> AsMut<[T]> for Vec<T, N>

source§

fn as_mut(&mut self) -> &mut [T]

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N>

source§

fn as_mut(&mut self) -> &mut Vec<T, N>

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsRef<[T]> for Vec<T, N>

source§

fn as_ref(&self) -> &[T]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N>

source§

fn as_ref(&self) -> &Vec<T, N>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> Clone for Vec<T, N>where + T: Clone,

source§

fn clone(&self) -> Vec<T, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, const N: usize> Debug for Vec<T, N>where + T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for Vec<T, N>

source§

fn default() -> Vec<T, N>

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Deref for Vec<T, N>

§

type Target = [T]

The resulting type after dereferencing.
source§

fn deref(&self) -> &[T]

Dereferences the value.
source§

impl<T, const N: usize> DerefMut for Vec<T, N>

source§

fn deref_mut(&mut self) -> &mut [T]

Mutably dereferences the value.
source§

impl<T, const N: usize> Drop for Vec<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>where + T: 'a + Copy,

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> Extend<T> for Vec<T, N>

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> FromIterator<T> for Vec<T, N>

source§

fn from_iter<I>(iter: I) -> Vec<T, N>where + I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
source§

impl<T, const N: usize> Hash for Vec<T, N>where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl<T, const N: usize> Hash for Vec<T, N>where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

Feeds this value into the given Hasher.
source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.
source§

impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a Vec<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'a mut Vec<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> IntoIterator for Vec<T, N>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <Vec<T, N> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> Ord for Vec<T, N>where + T: Ord,

source§

fn cmp(&self, other: &Vec<T, N>) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&[B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&[B; M]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&mut [B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &[B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &[B; M]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<B, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>where + T: PartialOrd<T>,

source§

fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl<'a, T, const N: usize> TryFrom<&'a [T]> for Vec<T, N>where + T: Clone,

§

type Error = ()

The type returned in the event of a conversion error.
source§

fn try_from( + slice: &'a [T] +) -> Result<Vec<T, N>, <Vec<T, N> as TryFrom<&'a [T]>>::Error>

Performs the conversion.
source§

impl<const N: usize> Write for Vec<u8, N>

source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write +succeeded. Read more
1.1.0§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a [char] into this writer, returning whether the write succeeded. Read more
1.0.0§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the [write!] macro with implementors of this trait. Read more
source§

impl<T, const N: usize> Eq for Vec<T, N>where + T: Eq,

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for Vec<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for Vec<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for Vec<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for Vec<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for Vec<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/arduboy_rust/prelude/trait.Printable.html b/docs/doc/arduboy_rust/prelude/trait.Printable.html index 67ff505..3d45fd7 100644 --- a/docs/doc/arduboy_rust/prelude/trait.Printable.html +++ b/docs/doc/arduboy_rust/prelude/trait.Printable.html @@ -8,4 +8,4 @@ // Provided method fn print(self) { ... } -}

Required Associated Types§

Required Methods§

source

fn print_2(self, params: Self::Parameters)

source

fn default_parameters() -> Self::Parameters

Provided Methods§

source

fn print(self)

Implementations on Foreign Types§

source§

impl Printable for i16

source§

impl Printable for &[u8]

§

type Parameters = ()

source§

fn print_2(self, _params: Self::Parameters)

source§

fn default_parameters() -> Self::Parameters

source§

impl Printable for u32

source§

impl Printable for &str

§

type Parameters = ()

source§

fn print_2(self, _params: Self::Parameters)

source§

fn default_parameters() -> Self::Parameters

source§

impl Printable for u16

source§

impl Printable for i32

Implementors§

\ No newline at end of file +}

Required Associated Types§

Required Methods§

source

fn print_2(self, params: Self::Parameters)

source

fn default_parameters() -> Self::Parameters

Provided Methods§

source

fn print(self)

Implementations on Foreign Types§

source§

impl Printable for i16

source§

impl Printable for i32

source§

impl Printable for &str

§

type Parameters = ()

source§

fn print_2(self, _params: Self::Parameters)

source§

fn default_parameters() -> Self::Parameters

source§

impl Printable for u16

source§

impl Printable for &[u8]

§

type Parameters = ()

source§

fn print_2(self, _params: Self::Parameters)

source§

fn default_parameters() -> Self::Parameters

source§

impl Printable for u32

Implementors§

\ No newline at end of file diff --git a/docs/doc/arduboy_rust/sidebar-items.js b/docs/doc/arduboy_rust/sidebar-items.js index c48906e..c31f844 100644 --- a/docs/doc/arduboy_rust/sidebar-items.js +++ b/docs/doc/arduboy_rust/sidebar-items.js @@ -1 +1 @@ -window.SIDEBAR_ITEMS = {"constant":["FONT_SIZE","HEIGHT","WIDTH"],"enum":["Color"],"macro":["f","get_sprite_addr","get_string_addr","get_tones_addr","progmem"],"mod":["arduboy2","arduboy_tone","arduino","c","hardware","prelude","sprites"],"struct":["Arduboy2","ArduboyTones","EEPROM","EEPROMBYTE"]}; \ No newline at end of file +window.SIDEBAR_ITEMS = {"constant":["FONT_SIZE","HEIGHT","WIDTH"],"enum":["Color"],"macro":["f","get_sprite_addr","get_string_addr","get_tones_addr","progmem"],"mod":["arduboy2","arduboy_tone","arduino","c","hardware","heapless","prelude","sprites"],"struct":["Arduboy2","ArduboyTones","EEPROM","EEPROMBYTE"]}; \ No newline at end of file diff --git a/docs/doc/atomic_polyfill/all.html b/docs/doc/atomic_polyfill/all.html new file mode 100644 index 0000000..083f796 --- /dev/null +++ b/docs/doc/atomic_polyfill/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/constant.ATOMIC_BOOL_INIT.html b/docs/doc/atomic_polyfill/constant.ATOMIC_BOOL_INIT.html new file mode 100644 index 0000000..f27a262 --- /dev/null +++ b/docs/doc/atomic_polyfill/constant.ATOMIC_BOOL_INIT.html @@ -0,0 +1,2 @@ +ATOMIC_BOOL_INIT in atomic_polyfill - Rust

Constant atomic_polyfill::ATOMIC_BOOL_INIT

1.0.0 ·
pub const ATOMIC_BOOL_INIT: AtomicBool;
👎Deprecated since 1.34.0: the new function is now preferred
Expand description

An AtomicBool initialized to false.

+
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/enum.Ordering.html b/docs/doc/atomic_polyfill/enum.Ordering.html new file mode 100644 index 0000000..3bf4b1f --- /dev/null +++ b/docs/doc/atomic_polyfill/enum.Ordering.html @@ -0,0 +1,60 @@ +Ordering in atomic_polyfill - Rust

Enum atomic_polyfill::Ordering

1.0.0 ·
pub enum Ordering {
+    Relaxed,
+    Release,
+    Acquire,
+    AcqRel,
+    SeqCst,
+}
Expand description

Atomic memory orderings

+

Memory orderings specify the way atomic operations synchronize memory. +In its weakest Ordering::Relaxed, only the memory directly touched by the +operation is synchronized. On the other hand, a store-load pair of Ordering::SeqCst +operations synchronize other memory while additionally preserving a total order of such +operations across all threads.

+

Rust’s memory orderings are the same as those of +C++20.

+

For more information see the nomicon.

+

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Relaxed

No ordering constraints, only atomic operations.

+

Corresponds to memory_order_relaxed in C++20.

+
§

Release

When coupled with a store, all previous operations become ordered +before any load of this value with Acquire (or stronger) ordering. +In particular, all previous writes become visible to all threads +that perform an Acquire (or stronger) load of this value.

+

Notice that using this ordering for an operation that combines loads +and stores leads to a Relaxed load operation!

+

This ordering is only applicable for operations that can perform a store.

+

Corresponds to memory_order_release in C++20.

+
§

Acquire

When coupled with a load, if the loaded value was written by a store operation with +Release (or stronger) ordering, then all subsequent operations +become ordered after that store. In particular, all subsequent loads will see data +written before the store.

+

Notice that using this ordering for an operation that combines loads +and stores leads to a Relaxed store operation!

+

This ordering is only applicable for operations that can perform a load.

+

Corresponds to memory_order_acquire in C++20.

+
§

AcqRel

Has the effects of both Acquire and Release together: +For loads it uses Acquire ordering. For stores it uses the Release ordering.

+

Notice that in the case of compare_and_swap, it is possible that the operation ends up +not performing any store and hence it has just Acquire ordering. However, +AcqRel will never perform Relaxed accesses.

+

This ordering is only applicable for operations that combine both loads and stores.

+

Corresponds to memory_order_acq_rel in C++20.

+
§

SeqCst

Like Acquire/Release/AcqRel (for load, store, and load-with-store +operations, respectively) with the additional guarantee that all threads see all +sequentially consistent operations in the same order.

+

Corresponds to memory_order_seq_cst in C++20.

+

Trait Implementations§

§

impl Clone for Ordering

§

fn clone(&self) -> Ordering

Returns a copy of the value. Read more
§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for Ordering

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Hash for Ordering

§

fn hash<__H>(&self, state: &mut __H)where + __H: Hasher,

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
§

impl PartialEq<Ordering> for Ordering

§

fn eq(&self, other: &Ordering) -> bool

This method tests for self and other values to be equal, and is used +by ==.
§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
§

impl Copy for Ordering

§

impl Eq for Ordering

§

impl StructuralEq for Ordering

§

impl StructuralPartialEq for Ordering

Auto Trait Implementations§

§

impl RefUnwindSafe for Ordering

§

impl Send for Ordering

§

impl Sync for Ordering

§

impl Unpin for Ordering

§

impl UnwindSafe for Ordering

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/fn.compiler_fence.html b/docs/doc/atomic_polyfill/fn.compiler_fence.html new file mode 100644 index 0000000..849577e --- /dev/null +++ b/docs/doc/atomic_polyfill/fn.compiler_fence.html @@ -0,0 +1,57 @@ +compiler_fence in atomic_polyfill - Rust

Function atomic_polyfill::compiler_fence

1.21.0 ·
pub fn compiler_fence(order: Ordering)
Expand description

A compiler memory fence.

+

compiler_fence does not emit any machine code, but restricts the kinds +of memory re-ordering the compiler is allowed to do. Specifically, depending on +the given Ordering semantics, the compiler may be disallowed from moving reads +or writes from before or after the call to the other side of the call to +compiler_fence. Note that it does not prevent the hardware +from doing such re-ordering. This is not a problem in a single-threaded, +execution context, but when other threads may modify memory at the same +time, stronger synchronization primitives such as fence are required.

+

The re-ordering prevented by the different ordering semantics are:

+
    +
  • with SeqCst, no re-ordering of reads and writes across this point is allowed.
  • +
  • with Release, preceding reads and writes cannot be moved past subsequent writes.
  • +
  • with Acquire, subsequent reads and writes cannot be moved ahead of preceding reads.
  • +
  • with AcqRel, both of the above rules are enforced.
  • +
+

compiler_fence is generally only useful for preventing a thread from +racing with itself. That is, if a given thread is executing one piece +of code, and is then interrupted, and starts executing code elsewhere +(while still in the same thread, and conceptually still on the same +core). In traditional programs, this can only occur when a signal +handler is registered. In more low-level code, such situations can also +arise when handling interrupts, when implementing green threads with +pre-emption, etc. Curious readers are encouraged to read the Linux kernel’s +discussion of memory barriers.

+

Panics

+

Panics if order is Relaxed.

+

Examples

+

Without compiler_fence, the assert_eq! in following code +is not guaranteed to succeed, despite everything happening in a single thread. +To see why, remember that the compiler is free to swap the stores to +IMPORTANT_VARIABLE and IS_READY since they are both +Ordering::Relaxed. If it does, and the signal handler is invoked right +after IS_READY is updated, then the signal handler will see +IS_READY=1, but IMPORTANT_VARIABLE=0. +Using a compiler_fence remedies this situation.

+ +
use std::sync::atomic::{AtomicBool, AtomicUsize};
+use std::sync::atomic::Ordering;
+use std::sync::atomic::compiler_fence;
+
+static IMPORTANT_VARIABLE: AtomicUsize = AtomicUsize::new(0);
+static IS_READY: AtomicBool = AtomicBool::new(false);
+
+fn main() {
+    IMPORTANT_VARIABLE.store(42, Ordering::Relaxed);
+    // prevent earlier writes from being moved beyond this point
+    compiler_fence(Ordering::Release);
+    IS_READY.store(true, Ordering::Relaxed);
+}
+
+fn signal_handler() {
+    if IS_READY.load(Ordering::Relaxed) {
+        assert_eq!(IMPORTANT_VARIABLE.load(Ordering::Relaxed), 42);
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/fn.fence.html b/docs/doc/atomic_polyfill/fn.fence.html new file mode 100644 index 0000000..eeb915e --- /dev/null +++ b/docs/doc/atomic_polyfill/fn.fence.html @@ -0,0 +1,62 @@ +fence in atomic_polyfill - Rust

Function atomic_polyfill::fence

1.0.0 ·
pub fn fence(order: Ordering)
Expand description

An atomic fence.

+

Depending on the specified order, a fence prevents the compiler and CPU from +reordering certain types of memory operations around it. +That creates synchronizes-with relationships between it and atomic operations +or fences in other threads.

+

A fence ‘A’ which has (at least) Release ordering semantics, synchronizes +with a fence ‘B’ with (at least) Acquire semantics, if and only if there +exist operations X and Y, both operating on some atomic object ‘M’ such +that A is sequenced before X, Y is sequenced before B and Y observes +the change to M. This provides a happens-before dependence between A and B.

+
    Thread 1                                          Thread 2
+
+fence(Release);      A --------------
+x.store(3, Relaxed); X ---------    |
+                               |    |
+                               |    |
+                               -------------> Y  if x.load(Relaxed) == 3 {
+                                    |-------> B      fence(Acquire);
+                                                     ...
+                                                 }
+
+

Atomic operations with Release or Acquire semantics can also synchronize +with a fence.

+

A fence which has SeqCst ordering, in addition to having both Acquire +and Release semantics, participates in the global program order of the +other SeqCst operations and/or fences.

+

Accepts Acquire, Release, AcqRel and SeqCst orderings.

+

Panics

+

Panics if order is Relaxed.

+

Examples

+
use std::sync::atomic::AtomicBool;
+use std::sync::atomic::fence;
+use std::sync::atomic::Ordering;
+
+// A mutual exclusion primitive based on spinlock.
+pub struct Mutex {
+    flag: AtomicBool,
+}
+
+impl Mutex {
+    pub fn new() -> Mutex {
+        Mutex {
+            flag: AtomicBool::new(false),
+        }
+    }
+
+    pub fn lock(&self) {
+        // Wait until the old value is `false`.
+        while self
+            .flag
+            .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
+            .is_err()
+        {}
+        // This fence synchronizes-with store in `unlock`.
+        fence(Ordering::Acquire);
+    }
+
+    pub fn unlock(&self) {
+        self.flag.store(false, Ordering::Release);
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/fn.spin_loop_hint.html b/docs/doc/atomic_polyfill/fn.spin_loop_hint.html new file mode 100644 index 0000000..2f7afd8 --- /dev/null +++ b/docs/doc/atomic_polyfill/fn.spin_loop_hint.html @@ -0,0 +1,3 @@ +spin_loop_hint in atomic_polyfill - Rust

Function atomic_polyfill::spin_loop_hint

1.24.0 ·
pub fn spin_loop_hint()
👎Deprecated since 1.51.0: use hint::spin_loop instead
Expand description

Signals the processor that it is inside a busy-wait spin-loop (“spin lock”).

+

This function is deprecated in favor of hint::spin_loop.

+
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/index.html b/docs/doc/atomic_polyfill/index.html new file mode 100644 index 0000000..8b56832 --- /dev/null +++ b/docs/doc/atomic_polyfill/index.html @@ -0,0 +1 @@ +atomic_polyfill - Rust

Crate atomic_polyfill

source ·

Structs

  • A boolean type which can be safely shared between threads.
  • An integer type which can be safely shared between threads.
  • An integer type which can be safely shared between threads.

Enums

Constants

Functions

\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/sidebar-items.js b/docs/doc/atomic_polyfill/sidebar-items.js new file mode 100644 index 0000000..4cf0f31 --- /dev/null +++ b/docs/doc/atomic_polyfill/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["ATOMIC_BOOL_INIT"],"enum":["Ordering"],"fn":["compiler_fence","fence","spin_loop_hint"],"struct":["AtomicBool","AtomicI8","AtomicU8"]}; \ No newline at end of file diff --git a/docs/doc/atomic_polyfill/struct.AtomicBool.html b/docs/doc/atomic_polyfill/struct.AtomicBool.html new file mode 100644 index 0000000..b5e23eb --- /dev/null +++ b/docs/doc/atomic_polyfill/struct.AtomicBool.html @@ -0,0 +1,163 @@ +AtomicBool in atomic_polyfill - Rust

Struct atomic_polyfill::AtomicBool

1.0.0 ·
#[repr(C, align(1))]
pub struct AtomicBool { /* private fields */ }
Expand description

A boolean type which can be safely shared between threads.

+

This type has the same in-memory representation as a [bool].

+

Note: This type is only available on platforms that support atomic +loads and stores of u8.

+

Implementations§

§

impl AtomicBool

const: 1.24.0

pub const fn new(v: bool) -> AtomicBool

Creates a new AtomicBool.

+
Examples
+
use std::sync::atomic::AtomicBool;
+
+let atomic_true = AtomicBool::new(true);
+let atomic_false = AtomicBool::new(false);
+
const: unstable

pub unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool

🔬This is a nightly-only experimental API. (atomic_from_ptr)

Creates a new AtomicBool from a pointer.

+
Examples
+
#![feature(atomic_from_ptr, pointer_is_aligned)]
+use std::sync::atomic::{self, AtomicBool};
+use std::mem::align_of;
+
+// Get a pointer to an allocated value
+let ptr: *mut bool = Box::into_raw(Box::new(false));
+
+assert!(ptr.is_aligned_to(align_of::<AtomicBool>()));
+
+{
+    // Create an atomic view of the allocated value
+    let atomic = unsafe { AtomicBool::from_ptr(ptr) };
+
+    // Use `atomic` for atomic operations, possibly share it with other threads
+    atomic.store(true, atomic::Ordering::Relaxed);
+}
+
+// It's ok to non-atomically access the value behind `ptr`,
+// since the reference to the atomic ended its lifetime in the block above
+assert_eq!(unsafe { *ptr }, true);
+
+// Deallocate the value
+unsafe { drop(Box::from_raw(ptr)) }
+
Safety
+
    +
  • ptr must be aligned to align_of::<AtomicBool>() (note that on some platforms this can be bigger than align_of::<bool>()).
  • +
  • ptr must be valid for both reads and writes for the whole lifetime 'a.
  • +
  • The value behind ptr must not be accessed through non-atomic operations for the whole lifetime 'a.
  • +
+
1.15.0

pub fn get_mut(&mut self) -> &mut bool

Returns a mutable reference to the underlying [bool].

+

This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
use std::sync::atomic::{AtomicBool, Ordering};
+
+let mut some_bool = AtomicBool::new(true);
+assert_eq!(*some_bool.get_mut(), true);
+*some_bool.get_mut() = false;
+assert_eq!(some_bool.load(Ordering::SeqCst), false);
+

pub fn from_mut(v: &mut bool) -> &mut AtomicBool

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get atomic access to a &mut bool.

+
Examples
+
#![feature(atomic_from_mut)]
+use std::sync::atomic::{AtomicBool, Ordering};
+
+let mut some_bool = true;
+let a = AtomicBool::from_mut(&mut some_bool);
+a.store(false, Ordering::Relaxed);
+assert_eq!(some_bool, false);
+

pub fn get_mut_slice(this: &mut [AtomicBool]) -> &mut [bool]

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get non-atomic access to a &mut [AtomicBool] slice.

+

This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
#![feature(atomic_from_mut, inline_const)]
+use std::sync::atomic::{AtomicBool, Ordering};
+
+let mut some_bools = [const { AtomicBool::new(false) }; 10];
+
+let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
+assert_eq!(view, [false; 10]);
+view[..5].copy_from_slice(&[true; 5]);
+
+std::thread::scope(|s| {
+    for t in &some_bools[..5] {
+        s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
+    }
+
+    for f in &some_bools[5..] {
+        s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
+    }
+});
+

pub fn from_mut_slice(v: &mut [bool]) -> &mut [AtomicBool]

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get atomic access to a &mut [bool] slice.

+
Examples
+
#![feature(atomic_from_mut)]
+use std::sync::atomic::{AtomicBool, Ordering};
+
+let mut some_bools = [false; 10];
+let a = &*AtomicBool::from_mut_slice(&mut some_bools);
+std::thread::scope(|s| {
+    for i in 0..a.len() {
+        s.spawn(move || a[i].store(true, Ordering::Relaxed));
+    }
+});
+assert_eq!(some_bools, [true; 10]);
+
1.15.0 (const: unstable)

pub fn into_inner(self) -> bool

Consumes the atomic and returns the contained value.

+

This is safe because passing self by value guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
use std::sync::atomic::AtomicBool;
+
+let some_bool = AtomicBool::new(true);
+assert_eq!(some_bool.into_inner(), true);
+

pub fn load(&self, order: Ordering) -> bool

Loads a value from the bool.

+

load takes an Ordering argument which describes the memory ordering +of this operation. Possible values are SeqCst, Acquire and Relaxed.

+
Panics
+

Panics if order is Release or AcqRel.

+
Examples
+
use std::sync::atomic::{AtomicBool, Ordering};
+
+let some_bool = AtomicBool::new(true);
+
+assert_eq!(some_bool.load(Ordering::Relaxed), true);
+

pub fn store(&self, val: bool, order: Ordering)

Stores a value into the bool.

+

store takes an Ordering argument which describes the memory ordering +of this operation. Possible values are SeqCst, Release and Relaxed.

+
Panics
+

Panics if order is Acquire or AcqRel.

+
Examples
+
use std::sync::atomic::{AtomicBool, Ordering};
+
+let some_bool = AtomicBool::new(true);
+
+some_bool.store(false, Ordering::Relaxed);
+assert_eq!(some_bool.load(Ordering::Relaxed), false);
+
1.70.0 (const: 1.70.0)

pub const fn as_ptr(&self) -> *mut bool

Returns a mutable pointer to the underlying [bool].

+

Doing non-atomic reads and writes on the resulting integer can be a data race. +This method is mostly useful for FFI, where the function signature may use +*mut bool instead of &AtomicBool.

+

Returning an *mut pointer from a shared reference to this atomic is safe because the +atomic types work with interior mutability. All modifications of an atomic change the value +through a shared reference, and can do so safely as long as they use atomic operations. Any +use of the returned raw pointer requires an unsafe block and still has to uphold the same +restriction: operations on it must be atomic.

+
Examples
+
use std::sync::atomic::AtomicBool;
+
+extern "C" {
+    fn my_atomic_op(arg: *mut bool);
+}
+
+let mut atomic = AtomicBool::new(true);
+unsafe {
+    my_atomic_op(atomic.as_ptr());
+}
+

Trait Implementations§

1.3.0§

impl Debug for AtomicBool

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for AtomicBool

§

fn default() -> AtomicBool

Creates an AtomicBool initialized to false.

+
1.24.0§

impl From<bool> for AtomicBool

§

fn from(b: bool) -> AtomicBool

Converts a bool into an AtomicBool.

+
Examples
+
use std::sync::atomic::AtomicBool;
+let atomic_bool = AtomicBool::from(true);
+assert_eq!(format!("{atomic_bool:?}"), "true")
+
1.14.0§

impl RefUnwindSafe for AtomicBool

§

impl Sync for AtomicBool

Auto Trait Implementations§

§

impl Send for AtomicBool

§

impl Unpin for AtomicBool

§

impl UnwindSafe for AtomicBool

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/struct.AtomicI8.html b/docs/doc/atomic_polyfill/struct.AtomicI8.html new file mode 100644 index 0000000..970cbf9 --- /dev/null +++ b/docs/doc/atomic_polyfill/struct.AtomicI8.html @@ -0,0 +1,167 @@ +AtomicI8 in atomic_polyfill - Rust

Struct atomic_polyfill::AtomicI8

1.34.0 ·
#[repr(C, align(1))]
pub struct AtomicI8 { /* private fields */ }
Expand description

An integer type which can be safely shared between threads.

+

This type has the same in-memory representation as the underlying +integer type, [i8]. For more about the differences between atomic types and +non-atomic types as well as information about the portability of +this type, please see the module-level documentation.

+

Note: This type is only available on platforms that support +atomic loads and stores of [i8].

+

Implementations§

§

impl AtomicI8

const: 1.34.0

pub const fn new(v: i8) -> AtomicI8

Creates a new atomic integer.

+
Examples
+
use std::sync::atomic::AtomicI8;
+
+let atomic_forty_two = AtomicI8::new(42);
+
const: unstable

pub unsafe fn from_ptr<'a>(ptr: *mut i8) -> &'a AtomicI8

🔬This is a nightly-only experimental API. (atomic_from_ptr)

Creates a new reference to an atomic integer from a pointer.

+
Examples
+
#![feature(atomic_from_ptr, pointer_is_aligned)]
+use std::sync::atomic::{self, AtomicI8};
+use std::mem::align_of;
+
+// Get a pointer to an allocated value
+let ptr: *mut i8 = Box::into_raw(Box::new(0));
+
+assert!(ptr.is_aligned_to(align_of::<AtomicI8>()));
+
+{
+    // Create an atomic view of the allocated value
+    let atomic = unsafe {AtomicI8::from_ptr(ptr) };
+
+    // Use `atomic` for atomic operations, possibly share it with other threads
+    atomic.store(1, atomic::Ordering::Relaxed);
+}
+
+// It's ok to non-atomically access the value behind `ptr`,
+// since the reference to the atomic ended its lifetime in the block above
+assert_eq!(unsafe { *ptr }, 1);
+
+// Deallocate the value
+unsafe { drop(Box::from_raw(ptr)) }
+
Safety
+
    +
  • ptr must be aligned to align_of::<AtomicBool>() (note that on some platforms this can be bigger than align_of::<bool>()).
  • +
  • ptr must be aligned to align_of::<AtomicI8>() (note that on some platforms this can be bigger than align_of::<i8>()).
  • +
  • ptr must be valid for both reads and writes for the whole lifetime 'a.
  • +
  • The value behind ptr must not be accessed through non-atomic operations for the whole lifetime 'a.
  • +
+

pub fn get_mut(&mut self) -> &mut i8

Returns a mutable reference to the underlying integer.

+

This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
use std::sync::atomic::{AtomicI8, Ordering};
+
+let mut some_var = AtomicI8::new(10);
+assert_eq!(*some_var.get_mut(), 10);
+*some_var.get_mut() = 5;
+assert_eq!(some_var.load(Ordering::SeqCst), 5);
+

pub fn from_mut(v: &mut i8) -> &mut AtomicI8

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get atomic access to a &mut i8.

+
Examples
+
#![feature(atomic_from_mut)]
+use std::sync::atomic::{AtomicI8, Ordering};
+
+let mut some_int = 123;
+let a = AtomicI8::from_mut(&mut some_int);
+a.store(100, Ordering::Relaxed);
+assert_eq!(some_int, 100);
+

pub fn get_mut_slice(this: &mut [AtomicI8]) -> &mut [i8]

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get non-atomic access to a &mut [AtomicI8] slice

+

This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
#![feature(atomic_from_mut, inline_const)]
+use std::sync::atomic::{AtomicI8, Ordering};
+
+let mut some_ints = [const { AtomicI8::new(0) }; 10];
+
+let view: &mut [i8] = AtomicI8::get_mut_slice(&mut some_ints);
+assert_eq!(view, [0; 10]);
+view
+    .iter_mut()
+    .enumerate()
+    .for_each(|(idx, int)| *int = idx as _);
+
+std::thread::scope(|s| {
+    some_ints
+        .iter()
+        .enumerate()
+        .for_each(|(idx, int)| {
+            s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
+        })
+});
+

pub fn from_mut_slice(v: &mut [i8]) -> &mut [AtomicI8]

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get atomic access to a &mut [i8] slice.

+
Examples
+
#![feature(atomic_from_mut)]
+use std::sync::atomic::{AtomicI8, Ordering};
+
+let mut some_ints = [0; 10];
+let a = &*AtomicI8::from_mut_slice(&mut some_ints);
+std::thread::scope(|s| {
+    for i in 0..a.len() {
+        s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
+    }
+});
+for (i, n) in some_ints.into_iter().enumerate() {
+    assert_eq!(i, n as usize);
+}
+
const: unstable

pub fn into_inner(self) -> i8

Consumes the atomic and returns the contained value.

+

This is safe because passing self by value guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
use std::sync::atomic::AtomicI8;
+
+let some_var = AtomicI8::new(5);
+assert_eq!(some_var.into_inner(), 5);
+

pub fn load(&self, order: Ordering) -> i8

Loads a value from the atomic integer.

+

load takes an Ordering argument which describes the memory ordering of this operation. +Possible values are SeqCst, Acquire and Relaxed.

+
Panics
+

Panics if order is Release or AcqRel.

+
Examples
+
use std::sync::atomic::{AtomicI8, Ordering};
+
+let some_var = AtomicI8::new(5);
+
+assert_eq!(some_var.load(Ordering::Relaxed), 5);
+

pub fn store(&self, val: i8, order: Ordering)

Stores a value into the atomic integer.

+

store takes an Ordering argument which describes the memory ordering of this operation. +Possible values are SeqCst, Release and Relaxed.

+
Panics
+

Panics if order is Acquire or AcqRel.

+
Examples
+
use std::sync::atomic::{AtomicI8, Ordering};
+
+let some_var = AtomicI8::new(5);
+
+some_var.store(10, Ordering::Relaxed);
+assert_eq!(some_var.load(Ordering::Relaxed), 10);
+
1.70.0 (const: 1.70.0)

pub const fn as_ptr(&self) -> *mut i8

Returns a mutable pointer to the underlying integer.

+

Doing non-atomic reads and writes on the resulting integer can be a data race. +This method is mostly useful for FFI, where the function signature may use +*mut i8 instead of &AtomicI8.

+

Returning an *mut pointer from a shared reference to this atomic is safe because the +atomic types work with interior mutability. All modifications of an atomic change the value +through a shared reference, and can do so safely as long as they use atomic operations. Any +use of the returned raw pointer requires an unsafe block and still has to uphold the same +restriction: operations on it must be atomic.

+
Examples
+
use std::sync::atomic::AtomicI8;
+
+extern "C" {
+    fn my_atomic_op(arg: *mut i8);
+}
+
+let atomic = AtomicI8::new(1);
+
+// SAFETY: Safe as long as `my_atomic_op` is atomic.
+unsafe {
+    my_atomic_op(atomic.as_ptr());
+}
+

Trait Implementations§

§

impl Debug for AtomicI8

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for AtomicI8

§

fn default() -> AtomicI8

Returns the “default value” for a type. Read more
§

impl From<i8> for AtomicI8

§

fn from(v: i8) -> AtomicI8

Converts an i8 into an AtomicI8.

+
§

impl RefUnwindSafe for AtomicI8

§

impl Sync for AtomicI8

Auto Trait Implementations§

§

impl Send for AtomicI8

§

impl Unpin for AtomicI8

§

impl UnwindSafe for AtomicI8

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/atomic_polyfill/struct.AtomicU8.html b/docs/doc/atomic_polyfill/struct.AtomicU8.html new file mode 100644 index 0000000..a0ece4e --- /dev/null +++ b/docs/doc/atomic_polyfill/struct.AtomicU8.html @@ -0,0 +1,167 @@ +AtomicU8 in atomic_polyfill - Rust

Struct atomic_polyfill::AtomicU8

1.34.0 ·
#[repr(C, align(1))]
pub struct AtomicU8 { /* private fields */ }
Expand description

An integer type which can be safely shared between threads.

+

This type has the same in-memory representation as the underlying +integer type, [u8]. For more about the differences between atomic types and +non-atomic types as well as information about the portability of +this type, please see the module-level documentation.

+

Note: This type is only available on platforms that support +atomic loads and stores of [u8].

+

Implementations§

§

impl AtomicU8

const: 1.34.0

pub const fn new(v: u8) -> AtomicU8

Creates a new atomic integer.

+
Examples
+
use std::sync::atomic::AtomicU8;
+
+let atomic_forty_two = AtomicU8::new(42);
+
const: unstable

pub unsafe fn from_ptr<'a>(ptr: *mut u8) -> &'a AtomicU8

🔬This is a nightly-only experimental API. (atomic_from_ptr)

Creates a new reference to an atomic integer from a pointer.

+
Examples
+
#![feature(atomic_from_ptr, pointer_is_aligned)]
+use std::sync::atomic::{self, AtomicU8};
+use std::mem::align_of;
+
+// Get a pointer to an allocated value
+let ptr: *mut u8 = Box::into_raw(Box::new(0));
+
+assert!(ptr.is_aligned_to(align_of::<AtomicU8>()));
+
+{
+    // Create an atomic view of the allocated value
+    let atomic = unsafe {AtomicU8::from_ptr(ptr) };
+
+    // Use `atomic` for atomic operations, possibly share it with other threads
+    atomic.store(1, atomic::Ordering::Relaxed);
+}
+
+// It's ok to non-atomically access the value behind `ptr`,
+// since the reference to the atomic ended its lifetime in the block above
+assert_eq!(unsafe { *ptr }, 1);
+
+// Deallocate the value
+unsafe { drop(Box::from_raw(ptr)) }
+
Safety
+
    +
  • ptr must be aligned to align_of::<AtomicBool>() (note that on some platforms this can be bigger than align_of::<bool>()).
  • +
  • ptr must be aligned to align_of::<AtomicU8>() (note that on some platforms this can be bigger than align_of::<u8>()).
  • +
  • ptr must be valid for both reads and writes for the whole lifetime 'a.
  • +
  • The value behind ptr must not be accessed through non-atomic operations for the whole lifetime 'a.
  • +
+

pub fn get_mut(&mut self) -> &mut u8

Returns a mutable reference to the underlying integer.

+

This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
use std::sync::atomic::{AtomicU8, Ordering};
+
+let mut some_var = AtomicU8::new(10);
+assert_eq!(*some_var.get_mut(), 10);
+*some_var.get_mut() = 5;
+assert_eq!(some_var.load(Ordering::SeqCst), 5);
+

pub fn from_mut(v: &mut u8) -> &mut AtomicU8

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get atomic access to a &mut u8.

+
Examples
+
#![feature(atomic_from_mut)]
+use std::sync::atomic::{AtomicU8, Ordering};
+
+let mut some_int = 123;
+let a = AtomicU8::from_mut(&mut some_int);
+a.store(100, Ordering::Relaxed);
+assert_eq!(some_int, 100);
+

pub fn get_mut_slice(this: &mut [AtomicU8]) -> &mut [u8]

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get non-atomic access to a &mut [AtomicU8] slice

+

This is safe because the mutable reference guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
#![feature(atomic_from_mut, inline_const)]
+use std::sync::atomic::{AtomicU8, Ordering};
+
+let mut some_ints = [const { AtomicU8::new(0) }; 10];
+
+let view: &mut [u8] = AtomicU8::get_mut_slice(&mut some_ints);
+assert_eq!(view, [0; 10]);
+view
+    .iter_mut()
+    .enumerate()
+    .for_each(|(idx, int)| *int = idx as _);
+
+std::thread::scope(|s| {
+    some_ints
+        .iter()
+        .enumerate()
+        .for_each(|(idx, int)| {
+            s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
+        })
+});
+

pub fn from_mut_slice(v: &mut [u8]) -> &mut [AtomicU8]

🔬This is a nightly-only experimental API. (atomic_from_mut)

Get atomic access to a &mut [u8] slice.

+
Examples
+
#![feature(atomic_from_mut)]
+use std::sync::atomic::{AtomicU8, Ordering};
+
+let mut some_ints = [0; 10];
+let a = &*AtomicU8::from_mut_slice(&mut some_ints);
+std::thread::scope(|s| {
+    for i in 0..a.len() {
+        s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
+    }
+});
+for (i, n) in some_ints.into_iter().enumerate() {
+    assert_eq!(i, n as usize);
+}
+
const: unstable

pub fn into_inner(self) -> u8

Consumes the atomic and returns the contained value.

+

This is safe because passing self by value guarantees that no other threads are +concurrently accessing the atomic data.

+
Examples
+
use std::sync::atomic::AtomicU8;
+
+let some_var = AtomicU8::new(5);
+assert_eq!(some_var.into_inner(), 5);
+

pub fn load(&self, order: Ordering) -> u8

Loads a value from the atomic integer.

+

load takes an Ordering argument which describes the memory ordering of this operation. +Possible values are SeqCst, Acquire and Relaxed.

+
Panics
+

Panics if order is Release or AcqRel.

+
Examples
+
use std::sync::atomic::{AtomicU8, Ordering};
+
+let some_var = AtomicU8::new(5);
+
+assert_eq!(some_var.load(Ordering::Relaxed), 5);
+

pub fn store(&self, val: u8, order: Ordering)

Stores a value into the atomic integer.

+

store takes an Ordering argument which describes the memory ordering of this operation. +Possible values are SeqCst, Release and Relaxed.

+
Panics
+

Panics if order is Acquire or AcqRel.

+
Examples
+
use std::sync::atomic::{AtomicU8, Ordering};
+
+let some_var = AtomicU8::new(5);
+
+some_var.store(10, Ordering::Relaxed);
+assert_eq!(some_var.load(Ordering::Relaxed), 10);
+
1.70.0 (const: 1.70.0)

pub const fn as_ptr(&self) -> *mut u8

Returns a mutable pointer to the underlying integer.

+

Doing non-atomic reads and writes on the resulting integer can be a data race. +This method is mostly useful for FFI, where the function signature may use +*mut u8 instead of &AtomicU8.

+

Returning an *mut pointer from a shared reference to this atomic is safe because the +atomic types work with interior mutability. All modifications of an atomic change the value +through a shared reference, and can do so safely as long as they use atomic operations. Any +use of the returned raw pointer requires an unsafe block and still has to uphold the same +restriction: operations on it must be atomic.

+
Examples
+
use std::sync::atomic::AtomicU8;
+
+extern "C" {
+    fn my_atomic_op(arg: *mut u8);
+}
+
+let atomic = AtomicU8::new(1);
+
+// SAFETY: Safe as long as `my_atomic_op` is atomic.
+unsafe {
+    my_atomic_op(atomic.as_ptr());
+}
+

Trait Implementations§

§

impl Debug for AtomicU8

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for AtomicU8

§

fn default() -> AtomicU8

Returns the “default value” for a type. Read more
§

impl From<u8> for AtomicU8

§

fn from(v: u8) -> AtomicU8

Converts an u8 into an AtomicU8.

+
§

impl RefUnwindSafe for AtomicU8

§

impl Sync for AtomicU8

Auto Trait Implementations§

§

impl Send for AtomicU8

§

impl Unpin for AtomicU8

§

impl UnwindSafe for AtomicU8

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/byteorder/all.html b/docs/doc/byteorder/all.html new file mode 100644 index 0000000..d39e29f --- /dev/null +++ b/docs/doc/byteorder/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Enums

Traits

Type Definitions

\ No newline at end of file diff --git a/docs/doc/byteorder/enum.BigEndian.html b/docs/doc/byteorder/enum.BigEndian.html new file mode 100644 index 0000000..58f5169 --- /dev/null +++ b/docs/doc/byteorder/enum.BigEndian.html @@ -0,0 +1,45 @@ +BigEndian in byteorder - Rust

Enum byteorder::BigEndian

source ·
pub enum BigEndian {}
Expand description

Defines big-endian serialization.

+

Note that this type has no value constructor. It is used purely at the +type level.

+

Examples

+

Write and read u32 numbers in big endian order:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut buf = [0; 4];
+BigEndian::write_u32(&mut buf, 1_000_000);
+assert_eq!(1_000_000, BigEndian::read_u32(&buf));
+

Trait Implementations§

source§

impl ByteOrder for BigEndian

source§

fn read_u16(buf: &[u8]) -> u16

Reads an unsigned 16 bit integer from buf. Read more
source§

fn read_u32(buf: &[u8]) -> u32

Reads an unsigned 32 bit integer from buf. Read more
source§

fn read_u64(buf: &[u8]) -> u64

Reads an unsigned 64 bit integer from buf. Read more
source§

fn read_u128(buf: &[u8]) -> u128

Reads an unsigned 128 bit integer from buf. Read more
source§

fn read_uint(buf: &[u8], nbytes: usize) -> u64

Reads an unsigned n-bytes integer from buf. Read more
source§

fn read_uint128(buf: &[u8], nbytes: usize) -> u128

Reads an unsigned n-bytes integer from buf. Read more
source§

fn write_u16(buf: &mut [u8], n: u16)

Writes an unsigned 16 bit integer n to buf. Read more
source§

fn write_u32(buf: &mut [u8], n: u32)

Writes an unsigned 32 bit integer n to buf. Read more
source§

fn write_u64(buf: &mut [u8], n: u64)

Writes an unsigned 64 bit integer n to buf. Read more
source§

fn write_u128(buf: &mut [u8], n: u128)

Writes an unsigned 128 bit integer n to buf. Read more
source§

fn write_uint(buf: &mut [u8], n: u64, nbytes: usize)

Writes an unsigned integer n to buf using only nbytes. Read more
source§

fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize)

Writes an unsigned integer n to buf using only nbytes. Read more
source§

fn read_u16_into(src: &[u8], dst: &mut [u16])

Reads unsigned 16 bit integers from src into dst. Read more
source§

fn read_u32_into(src: &[u8], dst: &mut [u32])

Reads unsigned 32 bit integers from src into dst. Read more
source§

fn read_u64_into(src: &[u8], dst: &mut [u64])

Reads unsigned 64 bit integers from src into dst. Read more
source§

fn read_u128_into(src: &[u8], dst: &mut [u128])

Reads unsigned 128 bit integers from src into dst. Read more
source§

fn write_u16_into(src: &[u16], dst: &mut [u8])

Writes unsigned 16 bit integers from src into dst. Read more
source§

fn write_u32_into(src: &[u32], dst: &mut [u8])

Writes unsigned 32 bit integers from src into dst. Read more
source§

fn write_u64_into(src: &[u64], dst: &mut [u8])

Writes unsigned 64 bit integers from src into dst. Read more
source§

fn write_u128_into(src: &[u128], dst: &mut [u8])

Writes unsigned 128 bit integers from src into dst. Read more
source§

fn from_slice_u16(numbers: &mut [u16])

Converts the given slice of unsigned 16 bit integers to a particular +endianness. Read more
source§

fn from_slice_u32(numbers: &mut [u32])

Converts the given slice of unsigned 32 bit integers to a particular +endianness. Read more
source§

fn from_slice_u64(numbers: &mut [u64])

Converts the given slice of unsigned 64 bit integers to a particular +endianness. Read more
source§

fn from_slice_u128(numbers: &mut [u128])

Converts the given slice of unsigned 128 bit integers to a particular +endianness. Read more
source§

fn from_slice_f32(numbers: &mut [f32])

Converts the given slice of IEEE754 single-precision (4 bytes) floating +point numbers to a particular endianness. Read more
source§

fn from_slice_f64(numbers: &mut [f64])

Converts the given slice of IEEE754 double-precision (8 bytes) floating +point numbers to a particular endianness. Read more
source§

fn read_u24(buf: &[u8]) -> u32

Reads an unsigned 24 bit integer from buf, stored in u32. Read more
source§

fn read_u48(buf: &[u8]) -> u64

Reads an unsigned 48 bit integer from buf, stored in u64. Read more
source§

fn write_u24(buf: &mut [u8], n: u32)

Writes an unsigned 24 bit integer n to buf, stored in u32. Read more
source§

fn write_u48(buf: &mut [u8], n: u64)

Writes an unsigned 48 bit integer n to buf, stored in u64. Read more
source§

fn read_i16(buf: &[u8]) -> i16

Reads a signed 16 bit integer from buf. Read more
source§

fn read_i24(buf: &[u8]) -> i32

Reads a signed 24 bit integer from buf, stored in i32. Read more
source§

fn read_i32(buf: &[u8]) -> i32

Reads a signed 32 bit integer from buf. Read more
source§

fn read_i48(buf: &[u8]) -> i64

Reads a signed 48 bit integer from buf, stored in i64. Read more
source§

fn read_i64(buf: &[u8]) -> i64

Reads a signed 64 bit integer from buf. Read more
source§

fn read_i128(buf: &[u8]) -> i128

Reads a signed 128 bit integer from buf. Read more
source§

fn read_int(buf: &[u8], nbytes: usize) -> i64

Reads a signed n-bytes integer from buf. Read more
source§

fn read_int128(buf: &[u8], nbytes: usize) -> i128

Reads a signed n-bytes integer from buf. Read more
source§

fn read_f32(buf: &[u8]) -> f32

Reads a IEEE754 single-precision (4 bytes) floating point number. Read more
source§

fn read_f64(buf: &[u8]) -> f64

Reads a IEEE754 double-precision (8 bytes) floating point number. Read more
source§

fn write_i16(buf: &mut [u8], n: i16)

Writes a signed 16 bit integer n to buf. Read more
source§

fn write_i24(buf: &mut [u8], n: i32)

Writes a signed 24 bit integer n to buf, stored in i32. Read more
source§

fn write_i32(buf: &mut [u8], n: i32)

Writes a signed 32 bit integer n to buf. Read more
source§

fn write_i48(buf: &mut [u8], n: i64)

Writes a signed 48 bit integer n to buf, stored in i64. Read more
source§

fn write_i64(buf: &mut [u8], n: i64)

Writes a signed 64 bit integer n to buf. Read more
source§

fn write_i128(buf: &mut [u8], n: i128)

Writes a signed 128 bit integer n to buf. Read more
source§

fn write_int(buf: &mut [u8], n: i64, nbytes: usize)

Writes a signed integer n to buf using only nbytes. Read more
source§

fn write_int128(buf: &mut [u8], n: i128, nbytes: usize)

Writes a signed integer n to buf using only nbytes. Read more
source§

fn write_f32(buf: &mut [u8], n: f32)

Writes a IEEE754 single-precision (4 bytes) floating point number. Read more
source§

fn write_f64(buf: &mut [u8], n: f64)

Writes a IEEE754 double-precision (8 bytes) floating point number. Read more
source§

fn read_i16_into(src: &[u8], dst: &mut [i16])

Reads signed 16 bit integers from src to dst. Read more
source§

fn read_i32_into(src: &[u8], dst: &mut [i32])

Reads signed 32 bit integers from src into dst. Read more
source§

fn read_i64_into(src: &[u8], dst: &mut [i64])

Reads signed 64 bit integers from src into dst. Read more
source§

fn read_i128_into(src: &[u8], dst: &mut [i128])

Reads signed 128 bit integers from src into dst. Read more
source§

fn read_f32_into(src: &[u8], dst: &mut [f32])

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst. Read more
source§

fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32])

👎Deprecated since 1.3.0: please use read_f32_into instead
DEPRECATED. Read more
source§

fn read_f64_into(src: &[u8], dst: &mut [f64])

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst. Read more
source§

fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64])

👎Deprecated since 1.3.0: please use read_f64_into instead
DEPRECATED. Read more
source§

fn write_i8_into(src: &[i8], dst: &mut [u8])

Writes signed 8 bit integers from src into dst. Read more
source§

fn write_i16_into(src: &[i16], dst: &mut [u8])

Writes signed 16 bit integers from src into dst. Read more
source§

fn write_i32_into(src: &[i32], dst: &mut [u8])

Writes signed 32 bit integers from src into dst. Read more
source§

fn write_i64_into(src: &[i64], dst: &mut [u8])

Writes signed 64 bit integers from src into dst. Read more
source§

fn write_i128_into(src: &[i128], dst: &mut [u8])

Writes signed 128 bit integers from src into dst. Read more
source§

fn write_f32_into(src: &[f32], dst: &mut [u8])

Writes IEEE754 single-precision (4 bytes) floating point numbers from +src into dst. Read more
source§

fn write_f64_into(src: &[f64], dst: &mut [u8])

Writes IEEE754 double-precision (8 bytes) floating point numbers from +src into dst. Read more
source§

fn from_slice_i16(src: &mut [i16])

Converts the given slice of signed 16 bit integers to a particular +endianness. Read more
source§

fn from_slice_i32(src: &mut [i32])

Converts the given slice of signed 32 bit integers to a particular +endianness. Read more
source§

fn from_slice_i64(src: &mut [i64])

Converts the given slice of signed 64 bit integers to a particular +endianness. Read more
source§

fn from_slice_i128(src: &mut [i128])

Converts the given slice of signed 128 bit integers to a particular +endianness. Read more
source§

impl Clone for BigEndian

source§

fn clone(&self) -> BigEndian

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for BigEndian

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for BigEndian

source§

fn default() -> BigEndian

Returns the “default value” for a type. Read more
source§

impl Hash for BigEndian

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl Ord for BigEndian

source§

fn cmp(&self, other: &BigEndian) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<BigEndian> for BigEndian

source§

fn eq(&self, other: &BigEndian) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<BigEndian> for BigEndian

source§

fn partial_cmp(&self, other: &BigEndian) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for BigEndian

source§

impl Eq for BigEndian

source§

impl StructuralEq for BigEndian

source§

impl StructuralPartialEq for BigEndian

Auto Trait Implementations§

§

impl RefUnwindSafe for BigEndian

§

impl Send for BigEndian

§

impl Sync for BigEndian

§

impl Unpin for BigEndian

§

impl UnwindSafe for BigEndian

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/byteorder/enum.LittleEndian.html b/docs/doc/byteorder/enum.LittleEndian.html new file mode 100644 index 0000000..ece80a6 --- /dev/null +++ b/docs/doc/byteorder/enum.LittleEndian.html @@ -0,0 +1,45 @@ +LittleEndian in byteorder - Rust
pub enum LittleEndian {}
Expand description

Defines little-endian serialization.

+

Note that this type has no value constructor. It is used purely at the +type level.

+

Examples

+

Write and read u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 4];
+LittleEndian::write_u32(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+

Trait Implementations§

source§

impl ByteOrder for LittleEndian

source§

fn read_u16(buf: &[u8]) -> u16

Reads an unsigned 16 bit integer from buf. Read more
source§

fn read_u32(buf: &[u8]) -> u32

Reads an unsigned 32 bit integer from buf. Read more
source§

fn read_u64(buf: &[u8]) -> u64

Reads an unsigned 64 bit integer from buf. Read more
source§

fn read_u128(buf: &[u8]) -> u128

Reads an unsigned 128 bit integer from buf. Read more
source§

fn read_uint(buf: &[u8], nbytes: usize) -> u64

Reads an unsigned n-bytes integer from buf. Read more
source§

fn read_uint128(buf: &[u8], nbytes: usize) -> u128

Reads an unsigned n-bytes integer from buf. Read more
source§

fn write_u16(buf: &mut [u8], n: u16)

Writes an unsigned 16 bit integer n to buf. Read more
source§

fn write_u32(buf: &mut [u8], n: u32)

Writes an unsigned 32 bit integer n to buf. Read more
source§

fn write_u64(buf: &mut [u8], n: u64)

Writes an unsigned 64 bit integer n to buf. Read more
source§

fn write_u128(buf: &mut [u8], n: u128)

Writes an unsigned 128 bit integer n to buf. Read more
source§

fn write_uint(buf: &mut [u8], n: u64, nbytes: usize)

Writes an unsigned integer n to buf using only nbytes. Read more
source§

fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize)

Writes an unsigned integer n to buf using only nbytes. Read more
source§

fn read_u16_into(src: &[u8], dst: &mut [u16])

Reads unsigned 16 bit integers from src into dst. Read more
source§

fn read_u32_into(src: &[u8], dst: &mut [u32])

Reads unsigned 32 bit integers from src into dst. Read more
source§

fn read_u64_into(src: &[u8], dst: &mut [u64])

Reads unsigned 64 bit integers from src into dst. Read more
source§

fn read_u128_into(src: &[u8], dst: &mut [u128])

Reads unsigned 128 bit integers from src into dst. Read more
source§

fn write_u16_into(src: &[u16], dst: &mut [u8])

Writes unsigned 16 bit integers from src into dst. Read more
source§

fn write_u32_into(src: &[u32], dst: &mut [u8])

Writes unsigned 32 bit integers from src into dst. Read more
source§

fn write_u64_into(src: &[u64], dst: &mut [u8])

Writes unsigned 64 bit integers from src into dst. Read more
source§

fn write_u128_into(src: &[u128], dst: &mut [u8])

Writes unsigned 128 bit integers from src into dst. Read more
source§

fn from_slice_u16(numbers: &mut [u16])

Converts the given slice of unsigned 16 bit integers to a particular +endianness. Read more
source§

fn from_slice_u32(numbers: &mut [u32])

Converts the given slice of unsigned 32 bit integers to a particular +endianness. Read more
source§

fn from_slice_u64(numbers: &mut [u64])

Converts the given slice of unsigned 64 bit integers to a particular +endianness. Read more
source§

fn from_slice_u128(numbers: &mut [u128])

Converts the given slice of unsigned 128 bit integers to a particular +endianness. Read more
source§

fn from_slice_f32(numbers: &mut [f32])

Converts the given slice of IEEE754 single-precision (4 bytes) floating +point numbers to a particular endianness. Read more
source§

fn from_slice_f64(numbers: &mut [f64])

Converts the given slice of IEEE754 double-precision (8 bytes) floating +point numbers to a particular endianness. Read more
source§

fn read_u24(buf: &[u8]) -> u32

Reads an unsigned 24 bit integer from buf, stored in u32. Read more
source§

fn read_u48(buf: &[u8]) -> u64

Reads an unsigned 48 bit integer from buf, stored in u64. Read more
source§

fn write_u24(buf: &mut [u8], n: u32)

Writes an unsigned 24 bit integer n to buf, stored in u32. Read more
source§

fn write_u48(buf: &mut [u8], n: u64)

Writes an unsigned 48 bit integer n to buf, stored in u64. Read more
source§

fn read_i16(buf: &[u8]) -> i16

Reads a signed 16 bit integer from buf. Read more
source§

fn read_i24(buf: &[u8]) -> i32

Reads a signed 24 bit integer from buf, stored in i32. Read more
source§

fn read_i32(buf: &[u8]) -> i32

Reads a signed 32 bit integer from buf. Read more
source§

fn read_i48(buf: &[u8]) -> i64

Reads a signed 48 bit integer from buf, stored in i64. Read more
source§

fn read_i64(buf: &[u8]) -> i64

Reads a signed 64 bit integer from buf. Read more
source§

fn read_i128(buf: &[u8]) -> i128

Reads a signed 128 bit integer from buf. Read more
source§

fn read_int(buf: &[u8], nbytes: usize) -> i64

Reads a signed n-bytes integer from buf. Read more
source§

fn read_int128(buf: &[u8], nbytes: usize) -> i128

Reads a signed n-bytes integer from buf. Read more
source§

fn read_f32(buf: &[u8]) -> f32

Reads a IEEE754 single-precision (4 bytes) floating point number. Read more
source§

fn read_f64(buf: &[u8]) -> f64

Reads a IEEE754 double-precision (8 bytes) floating point number. Read more
source§

fn write_i16(buf: &mut [u8], n: i16)

Writes a signed 16 bit integer n to buf. Read more
source§

fn write_i24(buf: &mut [u8], n: i32)

Writes a signed 24 bit integer n to buf, stored in i32. Read more
source§

fn write_i32(buf: &mut [u8], n: i32)

Writes a signed 32 bit integer n to buf. Read more
source§

fn write_i48(buf: &mut [u8], n: i64)

Writes a signed 48 bit integer n to buf, stored in i64. Read more
source§

fn write_i64(buf: &mut [u8], n: i64)

Writes a signed 64 bit integer n to buf. Read more
source§

fn write_i128(buf: &mut [u8], n: i128)

Writes a signed 128 bit integer n to buf. Read more
source§

fn write_int(buf: &mut [u8], n: i64, nbytes: usize)

Writes a signed integer n to buf using only nbytes. Read more
source§

fn write_int128(buf: &mut [u8], n: i128, nbytes: usize)

Writes a signed integer n to buf using only nbytes. Read more
source§

fn write_f32(buf: &mut [u8], n: f32)

Writes a IEEE754 single-precision (4 bytes) floating point number. Read more
source§

fn write_f64(buf: &mut [u8], n: f64)

Writes a IEEE754 double-precision (8 bytes) floating point number. Read more
source§

fn read_i16_into(src: &[u8], dst: &mut [i16])

Reads signed 16 bit integers from src to dst. Read more
source§

fn read_i32_into(src: &[u8], dst: &mut [i32])

Reads signed 32 bit integers from src into dst. Read more
source§

fn read_i64_into(src: &[u8], dst: &mut [i64])

Reads signed 64 bit integers from src into dst. Read more
source§

fn read_i128_into(src: &[u8], dst: &mut [i128])

Reads signed 128 bit integers from src into dst. Read more
source§

fn read_f32_into(src: &[u8], dst: &mut [f32])

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst. Read more
source§

fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32])

👎Deprecated since 1.3.0: please use read_f32_into instead
DEPRECATED. Read more
source§

fn read_f64_into(src: &[u8], dst: &mut [f64])

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst. Read more
source§

fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64])

👎Deprecated since 1.3.0: please use read_f64_into instead
DEPRECATED. Read more
source§

fn write_i8_into(src: &[i8], dst: &mut [u8])

Writes signed 8 bit integers from src into dst. Read more
source§

fn write_i16_into(src: &[i16], dst: &mut [u8])

Writes signed 16 bit integers from src into dst. Read more
source§

fn write_i32_into(src: &[i32], dst: &mut [u8])

Writes signed 32 bit integers from src into dst. Read more
source§

fn write_i64_into(src: &[i64], dst: &mut [u8])

Writes signed 64 bit integers from src into dst. Read more
source§

fn write_i128_into(src: &[i128], dst: &mut [u8])

Writes signed 128 bit integers from src into dst. Read more
source§

fn write_f32_into(src: &[f32], dst: &mut [u8])

Writes IEEE754 single-precision (4 bytes) floating point numbers from +src into dst. Read more
source§

fn write_f64_into(src: &[f64], dst: &mut [u8])

Writes IEEE754 double-precision (8 bytes) floating point numbers from +src into dst. Read more
source§

fn from_slice_i16(src: &mut [i16])

Converts the given slice of signed 16 bit integers to a particular +endianness. Read more
source§

fn from_slice_i32(src: &mut [i32])

Converts the given slice of signed 32 bit integers to a particular +endianness. Read more
source§

fn from_slice_i64(src: &mut [i64])

Converts the given slice of signed 64 bit integers to a particular +endianness. Read more
source§

fn from_slice_i128(src: &mut [i128])

Converts the given slice of signed 128 bit integers to a particular +endianness. Read more
source§

impl Clone for LittleEndian

source§

fn clone(&self) -> LittleEndian

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LittleEndian

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for LittleEndian

source§

fn default() -> LittleEndian

Returns the “default value” for a type. Read more
source§

impl Hash for LittleEndian

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl Ord for LittleEndian

source§

fn cmp(&self, other: &LittleEndian) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LittleEndian> for LittleEndian

source§

fn eq(&self, other: &LittleEndian) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LittleEndian> for LittleEndian

source§

fn partial_cmp(&self, other: &LittleEndian) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LittleEndian

source§

impl Eq for LittleEndian

source§

impl StructuralEq for LittleEndian

source§

impl StructuralPartialEq for LittleEndian

Auto Trait Implementations§

§

impl RefUnwindSafe for LittleEndian

§

impl Send for LittleEndian

§

impl Sync for LittleEndian

§

impl Unpin for LittleEndian

§

impl UnwindSafe for LittleEndian

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/byteorder/index.html b/docs/doc/byteorder/index.html new file mode 100644 index 0000000..fbae92c --- /dev/null +++ b/docs/doc/byteorder/index.html @@ -0,0 +1,41 @@ +byteorder - Rust

Crate byteorder

source ·
Expand description

This crate provides convenience methods for encoding and decoding numbers in +either big-endian or little-endian order.

+

The organization of the crate is pretty simple. A trait, ByteOrder, specifies +byte conversion methods for each type of number in Rust (sans numbers that have +a platform dependent size like usize and isize). Two types, BigEndian +and LittleEndian implement these methods. Finally, ReadBytesExt and +WriteBytesExt provide convenience methods available to all types that +implement Read and Write.

+

An alias, NetworkEndian, for BigEndian is provided to help improve +code clarity.

+

An additional alias, NativeEndian, is provided for the endianness of the +local platform. This is convenient when serializing data for use and +conversions are not desired.

+

Examples

+

Read unsigned 16 bit big-endian integers from a Read type:

+ +
use std::io::Cursor;
+use byteorder::{BigEndian, ReadBytesExt};
+
+let mut rdr = Cursor::new(vec![2, 5, 3, 0]);
+// Note that we use type parameters to indicate which kind of byte order
+// we want!
+assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap());
+assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap());
+

Write unsigned 16 bit little-endian integers to a Write type:

+ +
use byteorder::{LittleEndian, WriteBytesExt};
+
+let mut wtr = vec![];
+wtr.write_u16::<LittleEndian>(517).unwrap();
+wtr.write_u16::<LittleEndian>(768).unwrap();
+assert_eq!(wtr, vec![5, 2, 0, 3]);
+

Optional Features

+

This crate optionally provides support for 128 bit values (i128 and u128) +when built with the i128 feature enabled.

+

This crate can also be used without the standard library.

+

Alternatives

+

Note that as of Rust 1.32, the standard numeric types provide built-in methods +like to_le_bytes and from_le_bytes, which support some of the same use +cases.

+

Enums

Traits

  • ByteOrder describes types that can serialize integers as bytes.

Type Definitions

\ No newline at end of file diff --git a/docs/doc/byteorder/sidebar-items.js b/docs/doc/byteorder/sidebar-items.js new file mode 100644 index 0000000..7c062a3 --- /dev/null +++ b/docs/doc/byteorder/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["BigEndian","LittleEndian"],"trait":["ByteOrder"],"type":["BE","LE","NativeEndian","NetworkEndian"]}; \ No newline at end of file diff --git a/docs/doc/byteorder/trait.ByteOrder.html b/docs/doc/byteorder/trait.ByteOrder.html new file mode 100644 index 0000000..7441bdb --- /dev/null +++ b/docs/doc/byteorder/trait.ByteOrder.html @@ -0,0 +1,961 @@ +ByteOrder in byteorder - Rust

Trait byteorder::ByteOrder

source ·
pub trait ByteOrder: Clone + Copy + Debug + Default + Eq + Hash + Ord + PartialEq + PartialOrd + Sealed {
+
Show 69 methods // Required methods + fn read_u16(buf: &[u8]) -> u16; + fn read_u32(buf: &[u8]) -> u32; + fn read_u64(buf: &[u8]) -> u64; + fn read_u128(buf: &[u8]) -> u128; + fn read_uint(buf: &[u8], nbytes: usize) -> u64; + fn read_uint128(buf: &[u8], nbytes: usize) -> u128; + fn write_u16(buf: &mut [u8], n: u16); + fn write_u32(buf: &mut [u8], n: u32); + fn write_u64(buf: &mut [u8], n: u64); + fn write_u128(buf: &mut [u8], n: u128); + fn write_uint(buf: &mut [u8], n: u64, nbytes: usize); + fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize); + fn read_u16_into(src: &[u8], dst: &mut [u16]); + fn read_u32_into(src: &[u8], dst: &mut [u32]); + fn read_u64_into(src: &[u8], dst: &mut [u64]); + fn read_u128_into(src: &[u8], dst: &mut [u128]); + fn write_u16_into(src: &[u16], dst: &mut [u8]); + fn write_u32_into(src: &[u32], dst: &mut [u8]); + fn write_u64_into(src: &[u64], dst: &mut [u8]); + fn write_u128_into(src: &[u128], dst: &mut [u8]); + fn from_slice_u16(numbers: &mut [u16]); + fn from_slice_u32(numbers: &mut [u32]); + fn from_slice_u64(numbers: &mut [u64]); + fn from_slice_u128(numbers: &mut [u128]); + fn from_slice_f32(numbers: &mut [f32]); + fn from_slice_f64(numbers: &mut [f64]); + + // Provided methods + fn read_u24(buf: &[u8]) -> u32 { ... } + fn read_u48(buf: &[u8]) -> u64 { ... } + fn write_u24(buf: &mut [u8], n: u32) { ... } + fn write_u48(buf: &mut [u8], n: u64) { ... } + fn read_i16(buf: &[u8]) -> i16 { ... } + fn read_i24(buf: &[u8]) -> i32 { ... } + fn read_i32(buf: &[u8]) -> i32 { ... } + fn read_i48(buf: &[u8]) -> i64 { ... } + fn read_i64(buf: &[u8]) -> i64 { ... } + fn read_i128(buf: &[u8]) -> i128 { ... } + fn read_int(buf: &[u8], nbytes: usize) -> i64 { ... } + fn read_int128(buf: &[u8], nbytes: usize) -> i128 { ... } + fn read_f32(buf: &[u8]) -> f32 { ... } + fn read_f64(buf: &[u8]) -> f64 { ... } + fn write_i16(buf: &mut [u8], n: i16) { ... } + fn write_i24(buf: &mut [u8], n: i32) { ... } + fn write_i32(buf: &mut [u8], n: i32) { ... } + fn write_i48(buf: &mut [u8], n: i64) { ... } + fn write_i64(buf: &mut [u8], n: i64) { ... } + fn write_i128(buf: &mut [u8], n: i128) { ... } + fn write_int(buf: &mut [u8], n: i64, nbytes: usize) { ... } + fn write_int128(buf: &mut [u8], n: i128, nbytes: usize) { ... } + fn write_f32(buf: &mut [u8], n: f32) { ... } + fn write_f64(buf: &mut [u8], n: f64) { ... } + fn read_i16_into(src: &[u8], dst: &mut [i16]) { ... } + fn read_i32_into(src: &[u8], dst: &mut [i32]) { ... } + fn read_i64_into(src: &[u8], dst: &mut [i64]) { ... } + fn read_i128_into(src: &[u8], dst: &mut [i128]) { ... } + fn read_f32_into(src: &[u8], dst: &mut [f32]) { ... } + fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32]) { ... } + fn read_f64_into(src: &[u8], dst: &mut [f64]) { ... } + fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64]) { ... } + fn write_i8_into(src: &[i8], dst: &mut [u8]) { ... } + fn write_i16_into(src: &[i16], dst: &mut [u8]) { ... } + fn write_i32_into(src: &[i32], dst: &mut [u8]) { ... } + fn write_i64_into(src: &[i64], dst: &mut [u8]) { ... } + fn write_i128_into(src: &[i128], dst: &mut [u8]) { ... } + fn write_f32_into(src: &[f32], dst: &mut [u8]) { ... } + fn write_f64_into(src: &[f64], dst: &mut [u8]) { ... } + fn from_slice_i16(src: &mut [i16]) { ... } + fn from_slice_i32(src: &mut [i32]) { ... } + fn from_slice_i64(src: &mut [i64]) { ... } + fn from_slice_i128(src: &mut [i128]) { ... } +
}
Expand description

ByteOrder describes types that can serialize integers as bytes.

+

Note that Self does not appear anywhere in this trait’s definition! +Therefore, in order to use it, you’ll need to use syntax like +T::read_u16(&[0, 1]) where T implements ByteOrder.

+

This crate provides two types that implement ByteOrder: BigEndian +and LittleEndian. +This trait is sealed and cannot be implemented for callers to avoid +breaking backwards compatibility when adding new derived traits.

+

Examples

+

Write and read u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 4];
+LittleEndian::write_u32(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+

Write and read i16 numbers in big endian order:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut buf = [0; 2];
+BigEndian::write_i16(&mut buf, -5_000);
+assert_eq!(-5_000, BigEndian::read_i16(&buf));
+

Required Methods§

source

fn read_u16(buf: &[u8]) -> u16

Reads an unsigned 16 bit integer from buf.

+
Panics
+

Panics when buf.len() < 2.

+
source

fn read_u32(buf: &[u8]) -> u32

Reads an unsigned 32 bit integer from buf.

+
Panics
+

Panics when buf.len() < 4.

+
Examples
+

Write and read u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 4];
+LittleEndian::write_u32(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+
source

fn read_u64(buf: &[u8]) -> u64

Reads an unsigned 64 bit integer from buf.

+
Panics
+

Panics when buf.len() < 8.

+
Examples
+

Write and read u64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 8];
+LittleEndian::write_u64(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u64(&buf));
+
source

fn read_u128(buf: &[u8]) -> u128

Reads an unsigned 128 bit integer from buf.

+
Panics
+

Panics when buf.len() < 16.

+
Examples
+

Write and read u128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 16];
+LittleEndian::write_u128(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u128(&buf));
+
source

fn read_uint(buf: &[u8], nbytes: usize) -> u64

Reads an unsigned n-bytes integer from buf.

+
Panics
+

Panics when nbytes < 1 or nbytes > 8 or +buf.len() < nbytes

+
Examples
+

Write and read an n-byte number in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_uint(&mut buf, 1_000_000, 3);
+assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3));
+
source

fn read_uint128(buf: &[u8], nbytes: usize) -> u128

Reads an unsigned n-bytes integer from buf.

+
Panics
+

Panics when nbytes < 1 or nbytes > 16 or +buf.len() < nbytes

+
Examples
+

Write and read an n-byte number in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_uint128(&mut buf, 1_000_000, 3);
+assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3));
+
source

fn write_u16(buf: &mut [u8], n: u16)

Writes an unsigned 16 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 2.

+
Examples
+

Write and read u16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 2];
+LittleEndian::write_u16(&mut buf, 1_000);
+assert_eq!(1_000, LittleEndian::read_u16(&buf));
+
source

fn write_u32(buf: &mut [u8], n: u32)

Writes an unsigned 32 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 4.

+
Examples
+

Write and read u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 4];
+LittleEndian::write_u32(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+
source

fn write_u64(buf: &mut [u8], n: u64)

Writes an unsigned 64 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 8.

+
Examples
+

Write and read u64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 8];
+LittleEndian::write_u64(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u64(&buf));
+
source

fn write_u128(buf: &mut [u8], n: u128)

Writes an unsigned 128 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 16.

+
Examples
+

Write and read u128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 16];
+LittleEndian::write_u128(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u128(&buf));
+
source

fn write_uint(buf: &mut [u8], n: u64, nbytes: usize)

Writes an unsigned integer n to buf using only nbytes.

+
Panics
+

If n is not representable in nbytes, or if nbytes is > 8, then +this method panics.

+
Examples
+

Write and read an n-byte number in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_uint(&mut buf, 1_000_000, 3);
+assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3));
+
source

fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize)

Writes an unsigned integer n to buf using only nbytes.

+
Panics
+

If n is not representable in nbytes, or if nbytes is > 16, then +this method panics.

+
Examples
+

Write and read an n-byte number in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_uint128(&mut buf, 1_000_000, 3);
+assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3));
+
source

fn read_u16_into(src: &[u8], dst: &mut [u16])

Reads unsigned 16 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 2*dst.len().

+
Examples
+

Write and read u16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 8];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u16_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u16_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_u32_into(src: &[u8], dst: &mut [u32])

Reads unsigned 32 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 4*dst.len().

+
Examples
+

Write and read u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u32_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_u64_into(src: &[u8], dst: &mut [u64])

Reads unsigned 64 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 8*dst.len().

+
Examples
+

Write and read u64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u64_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_u128_into(src: &[u8], dst: &mut [u128])

Reads unsigned 128 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 16*dst.len().

+
Examples
+

Write and read u128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 64];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u128_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u128_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_u16_into(src: &[u16], dst: &mut [u8])

Writes unsigned 16 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 2*src.len().

+
Examples
+

Write and read u16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 8];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u16_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u16_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_u32_into(src: &[u32], dst: &mut [u8])

Writes unsigned 32 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 4*src.len().

+
Examples
+

Write and read u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u32_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_u64_into(src: &[u64], dst: &mut [u8])

Writes unsigned 64 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 8*src.len().

+
Examples
+

Write and read u64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u64_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_u128_into(src: &[u128], dst: &mut [u8])

Writes unsigned 128 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 16*src.len().

+
Examples
+

Write and read u128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 64];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_u128_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_u128_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn from_slice_u16(numbers: &mut [u16])

Converts the given slice of unsigned 16 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_u16(&mut numbers);
+assert_eq!(numbers, [5u16.to_be(), 65000u16.to_be()]);
+
source

fn from_slice_u32(numbers: &mut [u32])

Converts the given slice of unsigned 32 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_u32(&mut numbers);
+assert_eq!(numbers, [5u32.to_be(), 65000u32.to_be()]);
+
source

fn from_slice_u64(numbers: &mut [u64])

Converts the given slice of unsigned 64 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_u64(&mut numbers);
+assert_eq!(numbers, [5u64.to_be(), 65000u64.to_be()]);
+
source

fn from_slice_u128(numbers: &mut [u128])

Converts the given slice of unsigned 128 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_u128(&mut numbers);
+assert_eq!(numbers, [5u128.to_be(), 65000u128.to_be()]);
+
source

fn from_slice_f32(numbers: &mut [f32])

Converts the given slice of IEEE754 single-precision (4 bytes) floating +point numbers to a particular endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
source

fn from_slice_f64(numbers: &mut [f64])

Converts the given slice of IEEE754 double-precision (8 bytes) floating +point numbers to a particular endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+

Provided Methods§

source

fn read_u24(buf: &[u8]) -> u32

Reads an unsigned 24 bit integer from buf, stored in u32.

+
Panics
+

Panics when buf.len() < 3.

+
Examples
+

Write and read 24 bit u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_u24(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u24(&buf));
+
source

fn read_u48(buf: &[u8]) -> u64

Reads an unsigned 48 bit integer from buf, stored in u64.

+
Panics
+

Panics when buf.len() < 6.

+
Examples
+

Write and read 48 bit u64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 6];
+LittleEndian::write_u48(&mut buf, 1_000_000_000_000);
+assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf));
+
source

fn write_u24(buf: &mut [u8], n: u32)

Writes an unsigned 24 bit integer n to buf, stored in u32.

+
Panics
+

Panics when buf.len() < 3.

+
Examples
+

Write and read 24 bit u32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_u24(&mut buf, 1_000_000);
+assert_eq!(1_000_000, LittleEndian::read_u24(&buf));
+
source

fn write_u48(buf: &mut [u8], n: u64)

Writes an unsigned 48 bit integer n to buf, stored in u64.

+
Panics
+

Panics when buf.len() < 6.

+
Examples
+

Write and read 48 bit u64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 6];
+LittleEndian::write_u48(&mut buf, 1_000_000_000_000);
+assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf));
+
source

fn read_i16(buf: &[u8]) -> i16

Reads a signed 16 bit integer from buf.

+
Panics
+

Panics when buf.len() < 2.

+
Examples
+

Write and read i16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 2];
+LittleEndian::write_i16(&mut buf, -1_000);
+assert_eq!(-1_000, LittleEndian::read_i16(&buf));
+
source

fn read_i24(buf: &[u8]) -> i32

Reads a signed 24 bit integer from buf, stored in i32.

+
Panics
+

Panics when buf.len() < 3.

+
Examples
+

Write and read 24 bit i32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_i24(&mut buf, -1_000_000);
+assert_eq!(-1_000_000, LittleEndian::read_i24(&buf));
+
source

fn read_i32(buf: &[u8]) -> i32

Reads a signed 32 bit integer from buf.

+
Panics
+

Panics when buf.len() < 4.

+
Examples
+

Write and read i32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 4];
+LittleEndian::write_i32(&mut buf, -1_000_000);
+assert_eq!(-1_000_000, LittleEndian::read_i32(&buf));
+
source

fn read_i48(buf: &[u8]) -> i64

Reads a signed 48 bit integer from buf, stored in i64.

+
Panics
+

Panics when buf.len() < 6.

+
Examples
+

Write and read 48 bit i64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 6];
+LittleEndian::write_i48(&mut buf, -1_000_000_000_000);
+assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf));
+
source

fn read_i64(buf: &[u8]) -> i64

Reads a signed 64 bit integer from buf.

+
Panics
+

Panics when buf.len() < 8.

+
Examples
+

Write and read i64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 8];
+LittleEndian::write_i64(&mut buf, -1_000_000_000);
+assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf));
+
source

fn read_i128(buf: &[u8]) -> i128

Reads a signed 128 bit integer from buf.

+
Panics
+

Panics when buf.len() < 16.

+
Examples
+

Write and read i128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 16];
+LittleEndian::write_i128(&mut buf, -1_000_000_000);
+assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf));
+
source

fn read_int(buf: &[u8], nbytes: usize) -> i64

Reads a signed n-bytes integer from buf.

+
Panics
+

Panics when nbytes < 1 or nbytes > 8 or +buf.len() < nbytes

+
Examples
+

Write and read n-length signed numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_int(&mut buf, -1_000, 3);
+assert_eq!(-1_000, LittleEndian::read_int(&buf, 3));
+
source

fn read_int128(buf: &[u8], nbytes: usize) -> i128

Reads a signed n-bytes integer from buf.

+
Panics
+

Panics when nbytes < 1 or nbytes > 16 or +buf.len() < nbytes

+
Examples
+

Write and read n-length signed numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_int128(&mut buf, -1_000, 3);
+assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3));
+
source

fn read_f32(buf: &[u8]) -> f32

Reads a IEEE754 single-precision (4 bytes) floating point number.

+
Panics
+

Panics when buf.len() < 4.

+
Examples
+

Write and read f32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let e = 2.71828;
+let mut buf = [0; 4];
+LittleEndian::write_f32(&mut buf, e);
+assert_eq!(e, LittleEndian::read_f32(&buf));
+
source

fn read_f64(buf: &[u8]) -> f64

Reads a IEEE754 double-precision (8 bytes) floating point number.

+
Panics
+

Panics when buf.len() < 8.

+
Examples
+

Write and read f64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let phi = 1.6180339887;
+let mut buf = [0; 8];
+LittleEndian::write_f64(&mut buf, phi);
+assert_eq!(phi, LittleEndian::read_f64(&buf));
+
source

fn write_i16(buf: &mut [u8], n: i16)

Writes a signed 16 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 2.

+
Examples
+

Write and read i16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 2];
+LittleEndian::write_i16(&mut buf, -1_000);
+assert_eq!(-1_000, LittleEndian::read_i16(&buf));
+
source

fn write_i24(buf: &mut [u8], n: i32)

Writes a signed 24 bit integer n to buf, stored in i32.

+
Panics
+

Panics when buf.len() < 3.

+
Examples
+

Write and read 24 bit i32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_i24(&mut buf, -1_000_000);
+assert_eq!(-1_000_000, LittleEndian::read_i24(&buf));
+
source

fn write_i32(buf: &mut [u8], n: i32)

Writes a signed 32 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 4.

+
Examples
+

Write and read i32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 4];
+LittleEndian::write_i32(&mut buf, -1_000_000);
+assert_eq!(-1_000_000, LittleEndian::read_i32(&buf));
+
source

fn write_i48(buf: &mut [u8], n: i64)

Writes a signed 48 bit integer n to buf, stored in i64.

+
Panics
+

Panics when buf.len() < 6.

+
Examples
+

Write and read 48 bit i64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 6];
+LittleEndian::write_i48(&mut buf, -1_000_000_000_000);
+assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf));
+
source

fn write_i64(buf: &mut [u8], n: i64)

Writes a signed 64 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 8.

+
Examples
+

Write and read i64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 8];
+LittleEndian::write_i64(&mut buf, -1_000_000_000);
+assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf));
+
source

fn write_i128(buf: &mut [u8], n: i128)

Writes a signed 128 bit integer n to buf.

+
Panics
+

Panics when buf.len() < 16.

+
Examples
+

Write and read n-byte i128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 16];
+LittleEndian::write_i128(&mut buf, -1_000_000_000);
+assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf));
+
source

fn write_int(buf: &mut [u8], n: i64, nbytes: usize)

Writes a signed integer n to buf using only nbytes.

+
Panics
+

If n is not representable in nbytes, or if nbytes is > 8, then +this method panics.

+
Examples
+

Write and read an n-byte number in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_int(&mut buf, -1_000, 3);
+assert_eq!(-1_000, LittleEndian::read_int(&buf, 3));
+
source

fn write_int128(buf: &mut [u8], n: i128, nbytes: usize)

Writes a signed integer n to buf using only nbytes.

+
Panics
+

If n is not representable in nbytes, or if nbytes is > 16, then +this method panics.

+
Examples
+

Write and read n-length signed numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut buf = [0; 3];
+LittleEndian::write_int128(&mut buf, -1_000, 3);
+assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3));
+
source

fn write_f32(buf: &mut [u8], n: f32)

Writes a IEEE754 single-precision (4 bytes) floating point number.

+
Panics
+

Panics when buf.len() < 4.

+
Examples
+

Write and read f32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let e = 2.71828;
+let mut buf = [0; 4];
+LittleEndian::write_f32(&mut buf, e);
+assert_eq!(e, LittleEndian::read_f32(&buf));
+
source

fn write_f64(buf: &mut [u8], n: f64)

Writes a IEEE754 double-precision (8 bytes) floating point number.

+
Panics
+

Panics when buf.len() < 8.

+
Examples
+

Write and read f64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let phi = 1.6180339887;
+let mut buf = [0; 8];
+LittleEndian::write_f64(&mut buf, phi);
+assert_eq!(phi, LittleEndian::read_f64(&buf));
+
source

fn read_i16_into(src: &[u8], dst: &mut [i16])

Reads signed 16 bit integers from src to dst.

+
Panics
+

Panics when buf.len() != 2*dst.len().

+
Examples
+

Write and read i16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 8];
+let numbers_given = [1, 2, 0x0f, 0xee];
+LittleEndian::write_i16_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i16_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_i32_into(src: &[u8], dst: &mut [i32])

Reads signed 32 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 4*dst.len().

+
Examples
+

Write and read i32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_i32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i32_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_i64_into(src: &[u8], dst: &mut [i64])

Reads signed 64 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 8*dst.len().

+
Examples
+

Write and read i64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_i64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i64_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_i128_into(src: &[u8], dst: &mut [i128])

Reads signed 128 bit integers from src into dst.

+
Panics
+

Panics when src.len() != 16*dst.len().

+
Examples
+

Write and read i128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 64];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_i128_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i128_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_f32_into(src: &[u8], dst: &mut [f32])

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst.

+
Panics
+

Panics when src.len() != 4*dst.len().

+
Examples
+

Write and read f32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19];
+LittleEndian::write_f32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0.0; 4];
+LittleEndian::read_f32_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32])

👎Deprecated since 1.3.0: please use read_f32_into instead

DEPRECATED.

+

This method is deprecated. Use read_f32_into instead. +Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst.

+
Panics
+

Panics when src.len() != 4*dst.len().

+
Examples
+

Write and read f32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19];
+LittleEndian::write_f32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0.0; 4];
+LittleEndian::read_f32_into_unchecked(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_f64_into(src: &[u8], dst: &mut [f64])

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst.

+
Panics
+

Panics when src.len() != 8*dst.len().

+
Examples
+

Write and read f64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91];
+LittleEndian::write_f64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0.0; 4];
+LittleEndian::read_f64_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64])

👎Deprecated since 1.3.0: please use read_f64_into instead

DEPRECATED.

+

This method is deprecated. Use read_f64_into instead.

+

Reads IEEE754 single-precision (4 bytes) floating point numbers from +src into dst.

+
Panics
+

Panics when src.len() != 8*dst.len().

+
Examples
+

Write and read f64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91];
+LittleEndian::write_f64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0.0; 4];
+LittleEndian::read_f64_into_unchecked(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_i8_into(src: &[i8], dst: &mut [u8])

Writes signed 8 bit integers from src into dst.

+

Note that since each i8 is a single byte, no byte order conversions +are used. This method is included because it provides a safe, simple +way for the caller to write from a &[i8] buffer. (Without this +method, the caller would have to either use unsafe code or convert +each byte to u8 individually.)

+
Panics
+

Panics when buf.len() != src.len().

+
Examples
+

Write and read i8 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
+
+let mut bytes = [0; 4];
+let numbers_given = [1, 2, 0xf, 0xe];
+LittleEndian::write_i8_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+bytes.as_ref().read_i8_into(&mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_i16_into(src: &[i16], dst: &mut [u8])

Writes signed 16 bit integers from src into dst.

+
Panics
+

Panics when buf.len() != 2*src.len().

+
Examples
+

Write and read i16 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 8];
+let numbers_given = [1, 2, 0x0f, 0xee];
+LittleEndian::write_i16_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i16_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_i32_into(src: &[i32], dst: &mut [u8])

Writes signed 32 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 4*src.len().

+
Examples
+

Write and read i32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_i32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i32_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_i64_into(src: &[i64], dst: &mut [u8])

Writes signed 64 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 8*src.len().

+
Examples
+

Write and read i64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_i64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i64_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_i128_into(src: &[i128], dst: &mut [u8])

Writes signed 128 bit integers from src into dst.

+
Panics
+

Panics when dst.len() != 16*src.len().

+
Examples
+

Write and read i128 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 64];
+let numbers_given = [1, 2, 0xf00f, 0xffee];
+LittleEndian::write_i128_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0; 4];
+LittleEndian::read_i128_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_f32_into(src: &[f32], dst: &mut [u8])

Writes IEEE754 single-precision (4 bytes) floating point numbers from +src into dst.

+
Panics
+

Panics when src.len() != 4*dst.len().

+
Examples
+

Write and read f32 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 16];
+let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19];
+LittleEndian::write_f32_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0.0; 4];
+LittleEndian::read_f32_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn write_f64_into(src: &[f64], dst: &mut [u8])

Writes IEEE754 double-precision (8 bytes) floating point numbers from +src into dst.

+
Panics
+

Panics when src.len() != 8*dst.len().

+
Examples
+

Write and read f64 numbers in little endian order:

+ +
use byteorder::{ByteOrder, LittleEndian};
+
+let mut bytes = [0; 32];
+let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91];
+LittleEndian::write_f64_into(&numbers_given, &mut bytes);
+
+let mut numbers_got = [0.0; 4];
+LittleEndian::read_f64_into(&bytes, &mut numbers_got);
+assert_eq!(numbers_given, numbers_got);
+
source

fn from_slice_i16(src: &mut [i16])

Converts the given slice of signed 16 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 6500];
+BigEndian::from_slice_i16(&mut numbers);
+assert_eq!(numbers, [5i16.to_be(), 6500i16.to_be()]);
+
source

fn from_slice_i32(src: &mut [i32])

Converts the given slice of signed 32 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_i32(&mut numbers);
+assert_eq!(numbers, [5i32.to_be(), 65000i32.to_be()]);
+
source

fn from_slice_i64(src: &mut [i64])

Converts the given slice of signed 64 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_i64(&mut numbers);
+assert_eq!(numbers, [5i64.to_be(), 65000i64.to_be()]);
+
source

fn from_slice_i128(src: &mut [i128])

Converts the given slice of signed 128 bit integers to a particular +endianness.

+

If the endianness matches the endianness of the host platform, then +this is a no-op.

+
Examples
+

Convert the host platform’s endianness to big-endian:

+ +
use byteorder::{ByteOrder, BigEndian};
+
+let mut numbers = [5, 65000];
+BigEndian::from_slice_i128(&mut numbers);
+assert_eq!(numbers, [5i128.to_be(), 65000i128.to_be()]);
+

Implementors§

\ No newline at end of file diff --git a/docs/doc/byteorder/type.BE.html b/docs/doc/byteorder/type.BE.html new file mode 100644 index 0000000..70c0447 --- /dev/null +++ b/docs/doc/byteorder/type.BE.html @@ -0,0 +1,2 @@ +BE in byteorder - Rust

Type Definition byteorder::BE

source ·
pub type BE = BigEndian;
Expand description

A type alias for BigEndian.

+
\ No newline at end of file diff --git a/docs/doc/byteorder/type.LE.html b/docs/doc/byteorder/type.LE.html new file mode 100644 index 0000000..f1b7f26 --- /dev/null +++ b/docs/doc/byteorder/type.LE.html @@ -0,0 +1,2 @@ +LE in byteorder - Rust

Type Definition byteorder::LE

source ·
pub type LE = LittleEndian;
Expand description

A type alias for LittleEndian.

+
\ No newline at end of file diff --git a/docs/doc/byteorder/type.NativeEndian.html b/docs/doc/byteorder/type.NativeEndian.html new file mode 100644 index 0000000..bf450b4 --- /dev/null +++ b/docs/doc/byteorder/type.NativeEndian.html @@ -0,0 +1,5 @@ +NativeEndian in byteorder - Rust

Type Definition byteorder::NativeEndian

source ·
pub type NativeEndian = LittleEndian;
Expand description

Defines system native-endian serialization.

+

Note that this type has no value constructor. It is used purely at the +type level.

+

On this platform, this is an alias for LittleEndian.

+
\ No newline at end of file diff --git a/docs/doc/byteorder/type.NetworkEndian.html b/docs/doc/byteorder/type.NetworkEndian.html new file mode 100644 index 0000000..3c646ac --- /dev/null +++ b/docs/doc/byteorder/type.NetworkEndian.html @@ -0,0 +1,15 @@ +NetworkEndian in byteorder - Rust

Type Definition byteorder::NetworkEndian

source ·
pub type NetworkEndian = BigEndian;
Expand description

Defines network byte order serialization.

+

Network byte order is defined by RFC 1700 to be big-endian, and is +referred to in several protocol specifications. This type is an alias of +BigEndian.

+

Note that this type has no value constructor. It is used purely at the +type level.

+

Examples

+

Write and read i16 numbers in big endian order:

+ +
use byteorder::{ByteOrder, NetworkEndian, BigEndian};
+
+let mut buf = [0; 2];
+BigEndian::write_i16(&mut buf, -5_000);
+assert_eq!(-5_000, NetworkEndian::read_i16(&buf));
+
\ No newline at end of file diff --git a/docs/doc/crates.js b/docs/doc/crates.js index 05dca8f..0f4eb37 100644 --- a/docs/doc/crates.js +++ b/docs/doc/crates.js @@ -1 +1 @@ -window.ALL_CRATES = ["arduboy_rust","panic_halt"]; \ No newline at end of file +window.ALL_CRATES = ["arduboy_rust","atomic_polyfill","byteorder","critical_section","hash32","heapless","panic_halt","stable_deref_trait"]; \ No newline at end of file diff --git a/docs/doc/critical_section/all.html b/docs/doc/critical_section/all.html new file mode 100644 index 0000000..fe4a8f1 --- /dev/null +++ b/docs/doc/critical_section/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Structs

Traits

Macros

Functions

Type Definitions

\ No newline at end of file diff --git a/docs/doc/critical_section/fn.acquire.html b/docs/doc/critical_section/fn.acquire.html new file mode 100644 index 0000000..d169351 --- /dev/null +++ b/docs/doc/critical_section/fn.acquire.html @@ -0,0 +1,16 @@ +acquire in critical_section - Rust

Function critical_section::acquire

source ·
pub unsafe fn acquire() -> RestoreState
Expand description

Acquire a critical section in the current thread.

+

This function is extremely low level. Strongly prefer using with instead.

+

Nesting critical sections is allowed. The inner critical sections +are mostly no-ops since they’re already protected by the outer one.

+

Safety

+
    +
  • Each acquire call must be paired with exactly one release call in the same thread.
  • +
  • acquire returns a “restore state” that you must pass to the corresponding release call.
  • +
  • acquire/release pairs must be “properly nested”, ie it’s not OK to do a=acquire(); b=acquire(); release(a); release(b);.
  • +
  • It is UB to call release if the critical section is not acquired in the current thread.
  • +
  • It is UB to call release with a “restore state” that does not come from the corresponding acquire call.
  • +
  • It must provide ordering guarantees at least equivalent to a [core::sync::atomic::Ordering::Acquire] +on a memory location shared by all critical sections, on which the release call will do a +[core::sync::atomic::Ordering::Release] operation.
  • +
+
\ No newline at end of file diff --git a/docs/doc/critical_section/fn.release.html b/docs/doc/critical_section/fn.release.html new file mode 100644 index 0000000..a53e41e --- /dev/null +++ b/docs/doc/critical_section/fn.release.html @@ -0,0 +1,5 @@ +release in critical_section - Rust

Function critical_section::release

source ·
pub unsafe fn release(restore_state: RestoreState)
Expand description

Release the critical section.

+

This function is extremely low level. Strongly prefer using with instead.

+

Safety

+

See acquire for the safety contract description.

+
\ No newline at end of file diff --git a/docs/doc/critical_section/fn.with.html b/docs/doc/critical_section/fn.with.html new file mode 100644 index 0000000..ce546a5 --- /dev/null +++ b/docs/doc/critical_section/fn.with.html @@ -0,0 +1,7 @@ +with in critical_section - Rust

Function critical_section::with

source ·
pub fn with<R>(f: impl FnOnce(CriticalSection<'_>) -> R) -> R
Expand description

Execute closure f in a critical section.

+

Nesting critical sections is allowed. The inner critical sections +are mostly no-ops since they’re already protected by the outer one.

+

Panics

+

This function panics if the given closure f panics. In this case +the critical section is released before unwinding.

+
\ No newline at end of file diff --git a/docs/doc/critical_section/index.html b/docs/doc/critical_section/index.html new file mode 100644 index 0000000..afef002 --- /dev/null +++ b/docs/doc/critical_section/index.html @@ -0,0 +1,167 @@ +critical_section - Rust

Crate critical_section

source ·
Expand description

critical-section

+

crates.io +crates.io +Documentation

+

This project is developed and maintained by the HAL team.

+

A critical section that works everywhere!

+

When writing software for embedded systems, it’s common to use a “critical section” +as a basic primitive to control concurrency. A critical section is essentially a +mutex global to the whole process, that can be acquired by only one thread at a time. +This can be used to protect data behind mutexes, to emulate atomics in +targets that don’t support them, etc.

+

There’s a wide range of possible implementations depending on the execution environment:

+
    +
  • For bare-metal single core, disabling interrupts in the current (only) core.
  • +
  • For bare-metal multicore, disabling interrupts in the current core and acquiring a hardware spinlock to prevent other cores from entering a critical section concurrently.
  • +
  • For bare-metal using a RTOS, using library functions for acquiring a critical section, often named “scheduler lock” or “kernel lock”.
  • +
  • For bare-metal running in non-privileged mode, calling some system call is usually needed.
  • +
  • For std targets, acquiring a global std::sync::Mutex.
  • +
+

Libraries often need to use critical sections, but there’s no universal API for this in core. This leads +library authors to hard-code them for their target, or at best add some cfgs to support a few targets. +This doesn’t scale since there are many targets out there, and in the general case it’s impossible to know +which critical section implementation is needed from the Rust target alone. For example, the thumbv7em-none-eabi target +could be cases 1-4 from the above list.

+

This crate solves the problem by providing this missing universal API.

+
    +
  • It provides functions acquire, release and with that libraries can directly use.
  • +
  • It provides a way for any crate to supply an implementation. This allows “target support” crates such as architecture crates (cortex-m, riscv), RTOS bindings, or HALs for multicore chips to supply the correct implementation so that all the crates in the dependency tree automatically use it.
  • +
+

Usage in no-std binaries.

+

First, add a dependency on a crate providing a critical section implementation. Enable the critical-section-* Cargo feature if required by the crate.

+

Implementations are typically provided by either architecture-support crates, HAL crates, and OS/RTOS bindings, including:

+
    +
  • The cortex-m crate provides an implementation for all single-core Cortex-M microcontrollers via its critical-section-single-core feature
  • +
  • The riscv crate provides an implementation for all single-hart RISC-V microcontrollers via its critical-section-single-hart feature
  • +
  • The msp430 crate provides an implementation for all MSP430 microcontrollers via its critical-section-single-core feature
  • +
  • The rp2040-hal crate provides a multi-core-safe critical section for the RP2040 microcontroller via its critical-section-impl feature
  • +
  • The avr-device crate provides an implementation for all AVR microcontrollers via its critical-section-impl feature
  • +
  • The esp-hal-common crate provides an implementation for ESP32 microcontrollers which is used by the ESP HALs
  • +
  • The embassy-rp crate provides a multi-core-safe critical section for the RP2040 microcontroller via its critical-section-impl feature
  • +
  • The nrf-softdevice crate provides a critical section that’s compatible with the nRF soft-device firmware via its critical-section-impl feature
  • +
+

For example, for single-core Cortex-M targets, you can use:

+
[dependencies]
+cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]}
+
+

Then you can use critical_section::with().

+ +
use core::cell::Cell;
+use critical_section::Mutex;
+
+static MY_VALUE: Mutex<Cell<u32>> = Mutex::new(Cell::new(0));
+
+critical_section::with(|cs| {
+    // This code runs within a critical section.
+
+    // `cs` is a token that you can use to "prove" that to some API,
+    // for example to a `Mutex`:
+    MY_VALUE.borrow(cs).set(42);
+});
+
+

Usage in std binaries.

+

Add the critical-section dependency to Cargo.toml enabling the std feature. This makes the critical-section crate itself +provide an implementation based on std::sync::Mutex, so you don’t have to add any other dependency.

+
[dependencies]
+critical-section = { version = "1.1", features = ["std"]}
+

Usage in libraries

+

If you’re writing a library intended to be portable across many targets, simply add a dependency on critical-section +and use critical_section::free and/or Mutex as usual.

+

Do not add any dependency supplying a critical section implementation. Do not enable any critical-section-* Cargo feature. +This has to be done by the end user, enabling the correct implementation for their target.

+

Do not enable any Cargo feature in critical-section.

+

Usage in std tests for no-std libraries.

+

If you want to run std-using tests in otherwise no-std libraries, enable the std feature in dev-dependencies only. +This way the main target will use the no-std implementation chosen by the end-user’s binary, and only the test targets +will use the std implementation.

+
[dependencies]
+critical-section = "1.1"
+
+[dev-dependencies]
+critical-section = { version = "1.1", features = ["std"]}
+

Providing an implementation

+

Crates adding support for a particular architecture, chip or operating system should provide a critical section implementation. +It is strongly recommended to gate the implementation behind a feature, so the user can still use another implementation +if needed (having two implementations in the same binary will cause linking to fail).

+

Add the dependency, and a critical-section-* feature to your Cargo.toml:

+
[features]
+# Enable critical section implementation that does "foo"
+critical-section-foo = ["critical-section/restore-state-bool"]
+
+[dependencies]
+critical-section = { version = "1.0", optional = true }
+
+

Then, provide the critical implementation like this:

+ +
// This is a type alias for the enabled `restore-state-*` feature.
+// For example, it is `bool` if you enable `restore-state-bool`.
+use critical_section::RawRestoreState;
+
+struct MyCriticalSection;
+critical_section::set_impl!(MyCriticalSection);
+
+unsafe impl critical_section::Impl for MyCriticalSection {
+    unsafe fn acquire() -> RawRestoreState {
+        // TODO
+    }
+
+    unsafe fn release(token: RawRestoreState) {
+        // TODO
+    }
+}
+

Troubleshooting

Undefined reference errors

+

If you get an error like these:

+
undefined reference to `_critical_section_1_0_acquire'
+undefined reference to `_critical_section_1_0_release'
+
+

it is because you (or a library) are using critical_section::with without providing a critical section implementation. +Make sure you’re depending on a crate providing the implementation, and have enabled the critical-section-* feature in it if required. See the Usage section above.

+

The error can also be caused by having the dependency but never useing it. This can be fixed by adding a dummy use:

+ +
use the_cs_impl_crate as _;
+

Duplicate symbol errors

+

If you get errors like these:

+
error: symbol `_critical_section_1_0_acquire` is already defined
+
+

it is because you have two crates trying to provide a critical section implementation. You can only +have one implementation in a program.

+

You can use cargo tree --format '{p} {f}' to view all dependencies and their enabled features. Make sure +that in the whole dependency tree, exactly one implementation is provided.

+

Check for multiple versions of the same crate as well. For example, check the critical-section-single-core +feature is not enabled for both cortex-m 0.7 and 0.8.

+

Why not generics?

+

An alternative solution would be to use a CriticalSection trait, and make all +code that needs acquiring the critical section generic over it. This has a few problems:

+
    +
  • It would require passing it as a generic param to a very big amount of code, which +would be quite unergonomic.
  • +
  • It’s common to put Mutexes in static variables, and statics can’t +be generic.
  • +
  • It would allow mixing different critical section implementations in the same program, +which would be unsound.
  • +
+

Minimum Supported Rust Version (MSRV)

+

This crate is guaranteed to compile on the following Rust versions:

+
    +
  • If the std feature is not enabled: stable Rust 1.54 and up.
  • +
  • If the std feature is enabled: stable Rust 1.63 and up.
  • +
+

It might compile with older versions but that may change in any new patch release.

+

See here for details on how the MSRV may be upgraded.

+

License

+

This work is licensed under either of

+ +

at your option.

+

Contribution

+

Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions.

+

Code of Conduct

+

Contribution to this crate is organized under the terms of the Rust Code of +Conduct, the maintainer of this crate, the HAL team, promises +to intervene to uphold that code of conduct.

+

Macros

  • Set the critical section implementation.

Structs

Traits

  • Methods required for a critical section implementation.

Functions

  • Acquire a critical section in the current thread.
  • Release the critical section.
  • Execute closure f in a critical section.

Type Definitions

\ No newline at end of file diff --git a/docs/doc/critical_section/macro.set_impl!.html b/docs/doc/critical_section/macro.set_impl!.html new file mode 100644 index 0000000..a96aecb --- /dev/null +++ b/docs/doc/critical_section/macro.set_impl!.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to macro.set_impl.html...

+ + + \ No newline at end of file diff --git a/docs/doc/critical_section/macro.set_impl.html b/docs/doc/critical_section/macro.set_impl.html new file mode 100644 index 0000000..b6a8e68 --- /dev/null +++ b/docs/doc/critical_section/macro.set_impl.html @@ -0,0 +1,19 @@ +set_impl in critical_section - Rust
macro_rules! set_impl {
+    ($t: ty) => { ... };
+}
Expand description

Set the critical section implementation.

+

Example

+
use critical_section::RawRestoreState;
+
+struct MyCriticalSection;
+critical_section::set_impl!(MyCriticalSection);
+
+unsafe impl critical_section::Impl for MyCriticalSection {
+    unsafe fn acquire() -> RawRestoreState {
+        // ...
+    }
+
+    unsafe fn release(restore_state: RawRestoreState) {
+        // ...
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/critical_section/mutex/struct.Mutex.html b/docs/doc/critical_section/mutex/struct.Mutex.html new file mode 100644 index 0000000..2684495 --- /dev/null +++ b/docs/doc/critical_section/mutex/struct.Mutex.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../critical_section/struct.Mutex.html...

+ + + \ No newline at end of file diff --git a/docs/doc/critical_section/sidebar-items.js b/docs/doc/critical_section/sidebar-items.js new file mode 100644 index 0000000..9099ab3 --- /dev/null +++ b/docs/doc/critical_section/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["acquire","release","with"],"macro":["set_impl"],"struct":["CriticalSection","Mutex","RestoreState"],"trait":["Impl"],"type":["RawRestoreState"]}; \ No newline at end of file diff --git a/docs/doc/critical_section/struct.CriticalSection.html b/docs/doc/critical_section/struct.CriticalSection.html new file mode 100644 index 0000000..b67c750 --- /dev/null +++ b/docs/doc/critical_section/struct.CriticalSection.html @@ -0,0 +1,26 @@ +CriticalSection in critical_section - Rust
pub struct CriticalSection<'cs> { /* private fields */ }
Expand description

Critical section token.

+

An instance of this type indicates that the current thread is executing code within a critical +section.

+

Implementations§

source§

impl<'cs> CriticalSection<'cs>

source

pub unsafe fn new() -> Self

Creates a critical section token.

+

This method is meant to be used to create safe abstractions rather than being directly used +in applications.

+
Safety
+

This must only be called when the current thread is in a critical section. The caller must +ensure that the returned instance will not live beyond the end of the critical section.

+

The caller must use adequate fences to prevent the compiler from moving the +instructions inside the critical section to the outside of it. Sequentially consistent fences are +suggested immediately after entry and immediately before exit from the critical section.

+

Note that the lifetime 'cs of the returned instance is unconstrained. User code must not +be able to influence the lifetime picked for this type, since that might cause it to be +inferred to 'static.

+

Trait Implementations§

source§

impl<'cs> Clone for CriticalSection<'cs>

source§

fn clone(&self) -> CriticalSection<'cs>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'cs> Debug for CriticalSection<'cs>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'cs> Copy for CriticalSection<'cs>

Auto Trait Implementations§

§

impl<'cs> RefUnwindSafe for CriticalSection<'cs>

§

impl<'cs> Send for CriticalSection<'cs>

§

impl<'cs> Sync for CriticalSection<'cs>

§

impl<'cs> Unpin for CriticalSection<'cs>

§

impl<'cs> UnwindSafe for CriticalSection<'cs>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/critical_section/struct.Mutex.html b/docs/doc/critical_section/struct.Mutex.html new file mode 100644 index 0000000..8b27aeb --- /dev/null +++ b/docs/doc/critical_section/struct.Mutex.html @@ -0,0 +1,101 @@ +Mutex in critical_section - Rust

Struct critical_section::Mutex

source ·
pub struct Mutex<T> { /* private fields */ }
Expand description

A mutex based on critical sections.

+

Example

+

+static FOO: Mutex<Cell<i32>> = Mutex::new(Cell::new(42));
+
+fn main() {
+    critical_section::with(|cs| {
+        FOO.borrow(cs).set(43);
+    });
+}
+
+fn interrupt_handler() {
+    let _x = critical_section::with(|cs| FOO.borrow(cs).get());
+}
+

Design

+

std::sync::Mutex has two purposes. It converts types that are [Send] +but not [Sync] into types that are both; and it provides +interior mutability. critical_section::Mutex, on the other hand, only adds +Sync. It does not provide interior mutability.

+

This was a conscious design choice. It is possible to create multiple +CriticalSection tokens, either by nesting critical sections or Copying +an existing token. As a result, it would not be sound for Mutex::borrow +to return &mut T, because there would be nothing to prevent calling +borrow multiple times to create aliased &mut T references.

+

The solution is to include a runtime check to ensure that each resource is +borrowed only once. This is what std::sync::Mutex does. However, this is +a runtime cost that may not be required in all circumstances. For instance, +Mutex<Cell<T>> never needs to create &mut T or equivalent.

+

If &mut T is needed, the simplest solution is to use Mutex<RefCell<T>>, +which is the closest analogy to std::sync::Mutex. [RefCell] inserts the +exact runtime check necessary to guarantee that the &mut T reference is +unique.

+

To reduce verbosity when using Mutex<RefCell<T>>, we reimplement some of +RefCell’s methods on it directly.

+ +

+static FOO: Mutex<RefCell<i32>> = Mutex::new(RefCell::new(42));
+
+fn main() {
+    critical_section::with(|cs| {
+        // Instead of calling this
+        let _ = FOO.borrow(cs).take();
+        // Call this
+        let _ = FOO.take(cs);
+        // `RefCell::borrow` and `RefCell::borrow_mut` are renamed to
+        // `borrow_ref` and `borrow_ref_mut` to avoid name collisions
+        let _: &mut i32 = &mut *FOO.borrow_ref_mut(cs);
+    })
+}
+

Implementations§

source§

impl<T> Mutex<T>

source

pub const fn new(value: T) -> Self

Creates a new mutex.

+
source

pub fn get_mut(&mut self) -> &mut T

Gets a mutable reference to the contained value when the mutex is already uniquely borrowed.

+

This does not require locking or a critical section since it takes &mut self, which +guarantees unique ownership already. Care must be taken when using this method to +unsafely access static mut variables, appropriate fences must be used to prevent +unwanted optimizations.

+
source

pub fn into_inner(self) -> T

Unwraps the contained value, consuming the mutex.

+
source

pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T

Borrows the data for the duration of the critical section.

+
source§

impl<T> Mutex<RefCell<T>>

source

pub fn replace<'cs>(&'cs self, cs: CriticalSection<'cs>, t: T) -> T

Borrow the data and call [RefCell::replace]

+

This is equivalent to self.borrow(cs).replace(t)

+
Panics
+

This call could panic. See the documentation for [RefCell::replace] +for more details.

+
source

pub fn replace_with<'cs, F>(&'cs self, cs: CriticalSection<'cs>, f: F) -> Twhere + F: FnOnce(&mut T) -> T,

Borrow the data and call [RefCell::replace_with]

+

This is equivalent to self.borrow(cs).replace_with(f)

+
Panics
+

This call could panic. See the documentation for +[RefCell::replace_with] for more details.

+
source

pub fn borrow_ref<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, T>

Borrow the data and call [RefCell::borrow]

+

This is equivalent to self.borrow(cs).borrow()

+
Panics
+

This call could panic. See the documentation for [RefCell::borrow] +for more details.

+
source

pub fn borrow_ref_mut<'cs>( + &'cs self, + cs: CriticalSection<'cs> +) -> RefMut<'cs, T>

Borrow the data and call [RefCell::borrow_mut]

+

This is equivalent to self.borrow(cs).borrow_mut()

+
Panics
+

This call could panic. See the documentation for [RefCell::borrow_mut] +for more details.

+
source§

impl<T: Default> Mutex<RefCell<T>>

source

pub fn take<'cs>(&'cs self, cs: CriticalSection<'cs>) -> T

Borrow the data and call [RefCell::take]

+

This is equivalent to self.borrow(cs).take()

+
Panics
+

This call could panic. See the documentation for [RefCell::take] +for more details.

+

Trait Implementations§

source§

impl<T: Debug> Debug for Mutex<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T> Sync for Mutex<T>where + T: Send,

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Mutex<T>

§

impl<T> Send for Mutex<T>where + T: Send,

§

impl<T> Unpin for Mutex<T>where + T: Unpin,

§

impl<T> UnwindSafe for Mutex<T>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/critical_section/struct.RestoreState.html b/docs/doc/critical_section/struct.RestoreState.html new file mode 100644 index 0000000..7f39908 --- /dev/null +++ b/docs/doc/critical_section/struct.RestoreState.html @@ -0,0 +1,25 @@ +RestoreState in critical_section - Rust
pub struct RestoreState(_);
Expand description

Opaque “restore state”.

+

Implementations use this to “carry over” information between acquiring and releasing +a critical section. For example, when nesting two critical sections of an +implementation that disables interrupts globally, acquiring the inner one won’t disable +the interrupts since they’re already disabled. The impl would use the restore state to “tell” +the corresponding release that it does not have to reenable interrupts yet, only the +outer release should do so.

+

User code uses RestoreState opaquely, critical section implementations +use RawRestoreState so that they can use the inner value.

+

Implementations§

source§

impl RestoreState

source

pub const fn invalid() -> Self

Create an invalid, dummy RestoreState.

+

This can be useful to avoid Option when storing a RestoreState in a +struct field, or a static.

+

Note that due to the safety contract of acquire/release, you must not pass +a RestoreState obtained from this method to release.

+

Trait Implementations§

source§

impl Clone for RestoreState

source§

fn clone(&self) -> RestoreState

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for RestoreState

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Copy for RestoreState

Auto Trait Implementations§

§

impl RefUnwindSafe for RestoreState

§

impl Send for RestoreState

§

impl Sync for RestoreState

§

impl Unpin for RestoreState

§

impl UnwindSafe for RestoreState

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/critical_section/trait.Impl.html b/docs/doc/critical_section/trait.Impl.html new file mode 100644 index 0000000..e07d7ef --- /dev/null +++ b/docs/doc/critical_section/trait.Impl.html @@ -0,0 +1,15 @@ +Impl in critical_section - Rust
pub unsafe trait Impl {
+    // Required methods
+    unsafe fn acquire() -> RawRestoreState;
+    unsafe fn release(restore_state: RawRestoreState);
+}
Expand description

Methods required for a critical section implementation.

+

This trait is not intended to be used except when implementing a critical section.

+

Safety

+

Implementations must uphold the contract specified in crate::acquire and crate::release.

+

Required Methods§

source

unsafe fn acquire() -> RawRestoreState

Acquire the critical section.

+
Safety
+

Callers must uphold the contract specified in crate::acquire and crate::release.

+
source

unsafe fn release(restore_state: RawRestoreState)

Release the critical section.

+
Safety
+

Callers must uphold the contract specified in crate::acquire and crate::release.

+

Implementors§

\ No newline at end of file diff --git a/docs/doc/critical_section/type.RawRestoreState.html b/docs/doc/critical_section/type.RawRestoreState.html new file mode 100644 index 0000000..dc004ed --- /dev/null +++ b/docs/doc/critical_section/type.RawRestoreState.html @@ -0,0 +1,14 @@ +RawRestoreState in critical_section - Rust

Type Definition critical_section::RawRestoreState

source ·
pub type RawRestoreState = ();
Expand description

Raw, transparent “restore state”.

+

This type changes based on which Cargo feature is selected, out of

+
    +
  • restore-state-none (default, makes the type be ())
  • +
  • restore-state-bool
  • +
  • restore-state-u8
  • +
  • restore-state-u16
  • +
  • restore-state-u32
  • +
  • restore-state-u64
  • +
+

See RestoreState.

+

User code uses RestoreState opaquely, critical section implementations +use RawRestoreState so that they can use the inner value.

+
\ No newline at end of file diff --git a/docs/doc/hash32/all.html b/docs/doc/hash32/all.html new file mode 100644 index 0000000..2801a80 --- /dev/null +++ b/docs/doc/hash32/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/docs/doc/hash32/fnv/struct.Hasher.html b/docs/doc/hash32/fnv/struct.Hasher.html new file mode 100644 index 0000000..670d7d2 --- /dev/null +++ b/docs/doc/hash32/fnv/struct.Hasher.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../hash32/struct.FnvHasher.html...

+ + + \ No newline at end of file diff --git a/docs/doc/hash32/index.html b/docs/doc/hash32/index.html new file mode 100644 index 0000000..54735d8 --- /dev/null +++ b/docs/doc/hash32/index.html @@ -0,0 +1,46 @@ +hash32 - Rust

Crate hash32

source ·
Expand description

32-bit hashing machinery

+

Why?

+

Because 32-bit architectures are a thing (e.g. ARM Cortex-M) and you don’t want your hashing +function to pull in a bunch of slow 64-bit compiler intrinsics (software implementations of +64-bit operations).

+

Relationship to core::hash

+

This crate exposes the same interfaces you’ll find in core::hash: Hash, Hasher, +BuildHasher and BuildHasherDefault. The main difference is that hash32::Hasher::finish +returns a u32 instead of u64, and the contract of hash32::Hasher forbids the implementer +from performing 64-bit (or 128-bit) operations while computing the hash.

+

#[derive(Hash32)]

+

The easiest way to implement hash32::Hash for a struct is to use the #[derive(Hash32)].

+

Note that you need to explicitly depend on both hash32 and hash32_derive; both crates +must appear in your Cargo.toml.

+ +
use hash32_derive::Hash32;
+
+#[derive(Hash32)]
+struct Ipv4Addr([u8; 4]);
+
+
+

Hashers

+

This crate provides implementations of the following 32-bit hashing algorithms:

+ +

MSRV

+

This crate is guaranteed to compile on latest stable Rust. It might compile on older +versions but that may change in any new patch release.

+

Future

+

In the future we’d like to deprecate this crate in favor of making core::hash::Hasher generic +over the size of the computed hash. Below is shown the planned change (but it doesn’t work due +to limitations in the associated_type_defaults feature):

+ +
#![feature(associated_type_defaults)]
+
+trait Hasher {
+    type Hash = u64; // default type for backwards compatibility
+
+    fn finish(&self) -> Self::Hash; // changed
+    fn write(&mut self, bytes: &[u8]);
+}
+

With this change a single #[derive(Hash)] would enough to make a type hashable with 32-bit and +64-bit hashers.

+

Structs

Traits

\ No newline at end of file diff --git a/docs/doc/hash32/murmur3/struct.Hasher.html b/docs/doc/hash32/murmur3/struct.Hasher.html new file mode 100644 index 0000000..bdeafc6 --- /dev/null +++ b/docs/doc/hash32/murmur3/struct.Hasher.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../hash32/struct.Murmur3Hasher.html...

+ + + \ No newline at end of file diff --git a/docs/doc/hash32/sidebar-items.js b/docs/doc/hash32/sidebar-items.js new file mode 100644 index 0000000..84624b8 --- /dev/null +++ b/docs/doc/hash32/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["BuildHasherDefault","FnvHasher","Murmur3Hasher"],"trait":["BuildHasher","Hash","Hasher"]}; \ No newline at end of file diff --git a/docs/doc/hash32/struct.BuildHasherDefault.html b/docs/doc/hash32/struct.BuildHasherDefault.html new file mode 100644 index 0000000..1e9ca7d --- /dev/null +++ b/docs/doc/hash32/struct.BuildHasherDefault.html @@ -0,0 +1,24 @@ +BuildHasherDefault in hash32 - Rust
pub struct BuildHasherDefault<H> { /* private fields */ }
Expand description

Implementations§

source§

impl<H> BuildHasherDefault<H>

source

pub const fn new() -> Self

const constructor

+

Trait Implementations§

source§

impl<H> BuildHasher for BuildHasherDefault<H>where + H: Default + Hasher,

source§

impl<H> Clone for BuildHasherDefault<H>where + H: Default + Hasher,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<H: Default + Hasher> Debug for BuildHasherDefault<H>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<H> Default for BuildHasherDefault<H>where + H: Default + Hasher,

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<H> PartialEq<BuildHasherDefault<H>> for BuildHasherDefault<H>where + H: Default + Hasher,

source§

fn eq(&self, _other: &BuildHasherDefault<H>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<H: Default + Hasher> Eq for BuildHasherDefault<H>

Auto Trait Implementations§

§

impl<H> RefUnwindSafe for BuildHasherDefault<H>where + H: RefUnwindSafe,

§

impl<H> Send for BuildHasherDefault<H>where + H: Send,

§

impl<H> Sync for BuildHasherDefault<H>where + H: Sync,

§

impl<H> Unpin for BuildHasherDefault<H>where + H: Unpin,

§

impl<H> UnwindSafe for BuildHasherDefault<H>where + H: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/hash32/struct.FnvHasher.html b/docs/doc/hash32/struct.FnvHasher.html new file mode 100644 index 0000000..d522e60 --- /dev/null +++ b/docs/doc/hash32/struct.FnvHasher.html @@ -0,0 +1,12 @@ +FnvHasher in hash32 - Rust

Struct hash32::FnvHasher

source ·
pub struct FnvHasher { /* private fields */ }
Expand description

32-bit Fowler-Noll-Vo hasher

+

Trait Implementations§

source§

impl Default for Hasher

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl Hasher for Hasher

source§

fn finish(&self) -> u32

source§

fn write(&mut self, bytes: &[u8])

Auto Trait Implementations§

§

impl RefUnwindSafe for Hasher

§

impl Send for Hasher

§

impl Sync for Hasher

§

impl Unpin for Hasher

§

impl UnwindSafe for Hasher

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/hash32/struct.Murmur3Hasher.html b/docs/doc/hash32/struct.Murmur3Hasher.html new file mode 100644 index 0000000..e3f378c --- /dev/null +++ b/docs/doc/hash32/struct.Murmur3Hasher.html @@ -0,0 +1,12 @@ +Murmur3Hasher in hash32 - Rust

Struct hash32::Murmur3Hasher

source ·
pub struct Murmur3Hasher { /* private fields */ }
Expand description

32-bit MurmurHash3 hasher

+

Trait Implementations§

source§

impl Default for Hasher

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl Hasher for Hasher

source§

fn finish(&self) -> u32

source§

fn write(&mut self, bytes: &[u8])

Auto Trait Implementations§

§

impl RefUnwindSafe for Hasher

§

impl Send for Hasher

§

impl Sync for Hasher

§

impl Unpin for Hasher

§

impl UnwindSafe for Hasher

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/hash32/trait.BuildHasher.html b/docs/doc/hash32/trait.BuildHasher.html new file mode 100644 index 0000000..2716cc0 --- /dev/null +++ b/docs/doc/hash32/trait.BuildHasher.html @@ -0,0 +1,10 @@ +BuildHasher in hash32 - Rust

Trait hash32::BuildHasher

source ·
pub trait BuildHasher {
+    type Hasher: Hasher;
+
+    // Required method
+    fn build_hasher(&self) -> Self::Hasher;
+}
Expand description

See core::hash::BuildHasher for details

+

Required Associated Types§

Required Methods§

Implementors§

source§

impl<H> BuildHasher for BuildHasherDefault<H>where + H: Default + Hasher,

§

type Hasher = H

\ No newline at end of file diff --git a/docs/doc/hash32/trait.Hash.html b/docs/doc/hash32/trait.Hash.html new file mode 100644 index 0000000..40233cc --- /dev/null +++ b/docs/doc/hash32/trait.Hash.html @@ -0,0 +1,119 @@ +Hash in hash32 - Rust

Trait hash32::Hash

source ·
pub trait Hash {
+    // Required method
+    fn hash<H>(&self, state: &mut H)
+       where H: Hasher;
+
+    // Provided method
+    fn hash_slice<H>(data: &[Self], state: &mut H)
+       where H: Hasher,
+             Self: Sized { ... }
+}
Expand description

See core::hash::Hash for details

+

Required Methods§

source

fn hash<H>(&self, state: &mut H)where + H: Hasher,

Feeds this value into the given Hasher.

+

Provided Methods§

source

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.

+

Implementations on Foreign Types§

source§

impl<T> Hash for [T; 23]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl Hash for bool

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash, J: Hash, K> Hash for (A, B, C, D, E, F, G, H, I, J, K)where + K: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl Hash for i16

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl Hash for usize

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<A> Hash for (A,)where + A: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl Hash for isize

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 27]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I> Hash for (A, B, C, D, E, F, G, H, I)where + I: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<T> Hash for [T; 1]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 30]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 9]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 0]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl Hash for i64

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 2]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 20]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G> Hash for (A, B, C, D, E, F, G)where + G: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<A: Hash, B: Hash, C: Hash, D> Hash for (A, B, C, D)where + D: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F> Hash for (A, B, C, D, E, F)where + F: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<A: Hash, B> Hash for (A, B)where + B: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<T> Hash for [T; 25]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 15]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 14]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E> Hash for (A, B, C, D, E)where + E: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<T> Hash for [T; 5]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 31]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 8]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 7]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 16]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 17]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<'a, T: ?Sized + Hash> Hash for &'a mut T

source§

fn hash<H: Hasher>(&self, state: &mut H)

source§

impl<T> Hash for [T; 26]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 21]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 13]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 11]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H> Hash for (A, B, C, D, E, F, G, H)where + H: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<T> Hash for [T; 22]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 32]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 4]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 6]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 29]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 10]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl Hash for str

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 24]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 3]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl Hash for u8

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 12]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl Hash for u16

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<'a, T: ?Sized + Hash> Hash for &'a T

source§

fn hash<H: Hasher>(&self, state: &mut H)

source§

impl<T> Hash for [T; 18]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl Hash for i32

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash, J> Hash for (A, B, C, D, E, F, G, H, I, J)where + J: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl Hash for u32

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl Hash for i8

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl Hash for char

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C> Hash for (A, B, C)where + C: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl Hash for ()

source§

fn hash<H: Hasher>(&self, _state: &mut H)

source§

impl Hash for u64

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher,

source§

impl<A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H: Hash, I: Hash, J: Hash, K: Hash, L> Hash for (A, B, C, D, E, F, G, H, I, J, K, L)where + L: ?Sized + Hash,

source§

fn hash<S: Hasher>(&self, state: &mut S)

source§

impl<T> Hash for [T; 19]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

source§

impl<T> Hash for [T; 28]where + T: Hash,

source§

fn hash<H>(&self, state: &mut H)where + H: Hasher,

Implementors§

\ No newline at end of file diff --git a/docs/doc/hash32/trait.Hasher.html b/docs/doc/hash32/trait.Hasher.html new file mode 100644 index 0000000..1c7b5f5 --- /dev/null +++ b/docs/doc/hash32/trait.Hasher.html @@ -0,0 +1,11 @@ +Hasher in hash32 - Rust

Trait hash32::Hasher

source ·
pub trait Hasher {
+    // Required methods
+    fn finish(&self) -> u32;
+    fn write(&mut self, bytes: &[u8]);
+}
Expand description

See core::hash::Hasher for details

+

Contract

+

Implementers of this trait must not perform any 64-bit (or 128-bit) operation while computing +the hash.

+

Required Methods§

source

fn finish(&self) -> u32

source

fn write(&mut self, bytes: &[u8])

Implementors§

source§

impl Hasher for hash32::FnvHasher

source§

impl Hasher for hash32::Murmur3Hasher

\ No newline at end of file diff --git a/docs/doc/heapless/all.html b/docs/doc/heapless/all.html new file mode 100644 index 0000000..cc82b4d --- /dev/null +++ b/docs/doc/heapless/all.html @@ -0,0 +1 @@ +List of all items in this crate
\ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/enum.Max.html b/docs/doc/heapless/binary_heap/enum.Max.html new file mode 100644 index 0000000..3ccac83 --- /dev/null +++ b/docs/doc/heapless/binary_heap/enum.Max.html @@ -0,0 +1,12 @@ +Max in heapless::binary_heap - Rust
pub enum Max {}
Expand description

Max-heap

+

Trait Implementations§

source§

impl Kind for Max

Auto Trait Implementations§

§

impl RefUnwindSafe for Max

§

impl Send for Max

§

impl Sync for Max

§

impl Unpin for Max

§

impl UnwindSafe for Max

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/enum.Min.html b/docs/doc/heapless/binary_heap/enum.Min.html new file mode 100644 index 0000000..695666c --- /dev/null +++ b/docs/doc/heapless/binary_heap/enum.Min.html @@ -0,0 +1,12 @@ +Min in heapless::binary_heap - Rust
pub enum Min {}
Expand description

Min-heap

+

Trait Implementations§

source§

impl Kind for Min

Auto Trait Implementations§

§

impl RefUnwindSafe for Min

§

impl Send for Min

§

impl Sync for Min

§

impl Unpin for Min

§

impl UnwindSafe for Min

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/index.html b/docs/doc/heapless/binary_heap/index.html new file mode 100644 index 0000000..72e143e --- /dev/null +++ b/docs/doc/heapless/binary_heap/index.html @@ -0,0 +1,5 @@ +heapless::binary_heap - Rust

Module heapless::binary_heap

source ·
Expand description

A priority queue implemented with a binary heap.

+

Insertion and popping the largest element have O(log n) time complexity. Checking the largest +/ smallest element is O(1).

+

Structs

  • A priority queue implemented with a binary heap.
  • Structure wrapping a mutable reference to the greatest item on a +BinaryHeap.

Enums

Traits

  • The binary heap kind: min-heap or max-heap
\ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/sidebar-items.js b/docs/doc/heapless/binary_heap/sidebar-items.js new file mode 100644 index 0000000..1a0b7ee --- /dev/null +++ b/docs/doc/heapless/binary_heap/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Max","Min"],"struct":["BinaryHeap","PeekMut"],"trait":["Kind"]}; \ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/struct.BinaryHeap.html b/docs/doc/heapless/binary_heap/struct.BinaryHeap.html new file mode 100644 index 0000000..740bced --- /dev/null +++ b/docs/doc/heapless/binary_heap/struct.BinaryHeap.html @@ -0,0 +1,197 @@ +BinaryHeap in heapless::binary_heap - Rust
pub struct BinaryHeap<T, K, const N: usize> { /* private fields */ }
Expand description

A priority queue implemented with a binary heap.

+

This can be either a min-heap or a max-heap.

+

It is a logic error for an item to be modified in such a way that the item’s ordering relative +to any other item, as determined by the Ord trait, changes while it is in the heap. This is +normally only possible through Cell, RefCell, global state, I/O, or unsafe code.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+
+// We can use peek to look at the next item in the heap. In this case,
+// there's no items in there yet so we get None.
+assert_eq!(heap.peek(), None);
+
+// Let's add some scores...
+heap.push(1).unwrap();
+heap.push(5).unwrap();
+heap.push(2).unwrap();
+
+// Now peek shows the most important item in the heap.
+assert_eq!(heap.peek(), Some(&5));
+
+// We can check the length of a heap.
+assert_eq!(heap.len(), 3);
+
+// We can iterate over the items in the heap, although they are returned in
+// a random order.
+for x in &heap {
+    println!("{}", x);
+}
+
+// If we instead pop these scores, they should come back in order.
+assert_eq!(heap.pop(), Some(5));
+assert_eq!(heap.pop(), Some(2));
+assert_eq!(heap.pop(), Some(1));
+assert_eq!(heap.pop(), None);
+
+// We can clear the heap of any remaining items.
+heap.clear();
+
+// The heap should now be empty.
+assert!(heap.is_empty())
+

Implementations§

source§

impl<T, K, const N: usize> BinaryHeap<T, K, N>

source

pub const fn new() -> Self

Creates an empty BinaryHeap as a $K-heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+// allocate the binary heap on the stack
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(4).unwrap();
+
+// allocate the binary heap in a static variable
+static mut HEAP: BinaryHeap<i32, Max, 8> = BinaryHeap::new();
+
source§

impl<T, K, const N: usize> BinaryHeap<T, K, N>where + T: Ord, + K: Kind,

source

pub fn capacity(&self) -> usize

Returns the capacity of the binary heap.

+
source

pub fn clear(&mut self)

Drops all items from the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert!(!heap.is_empty());
+
+heap.clear();
+
+assert!(heap.is_empty());
+
source

pub fn len(&self) -> usize

Returns the length of the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert_eq!(heap.len(), 2);
+
source

pub fn is_empty(&self) -> bool

Checks if the binary heap is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+
+assert!(heap.is_empty());
+
+heap.push(3).unwrap();
+heap.push(5).unwrap();
+heap.push(1).unwrap();
+
+assert!(!heap.is_empty());
+
source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator visiting all values in the underlying vector, in arbitrary order.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(2).unwrap();
+heap.push(3).unwrap();
+heap.push(4).unwrap();
+
+// Print 1, 2, 3, 4 in arbitrary order
+for x in heap.iter() {
+    println!("{}", x);
+
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator visiting all values in the underlying vector, in arbitrary order.

+

WARNING Mutating the items in the binary heap can leave the heap in an inconsistent +state.

+
source

pub fn peek(&self) -> Option<&T>

Returns the top (greatest if max-heap, smallest if min-heap) item in the binary heap, or +None if it is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+assert_eq!(heap.peek(), None);
+
+heap.push(1).unwrap();
+heap.push(5).unwrap();
+heap.push(2).unwrap();
+assert_eq!(heap.peek(), Some(&5));
+
source

pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, K, N>>

Returns a mutable reference to the greatest item in the binary heap, or +None if it is empty.

+

Note: If the PeekMut value is leaked, the heap may be in an +inconsistent state.

+
Examples
+

Basic usage:

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+assert!(heap.peek_mut().is_none());
+
+heap.push(1);
+heap.push(5);
+heap.push(2);
+{
+    let mut val = heap.peek_mut().unwrap();
+    *val = 0;
+}
+
+assert_eq!(heap.peek(), Some(&2));
+
source

pub fn pop(&mut self) -> Option<T>

Removes the top (greatest if max-heap, smallest if min-heap) item from the binary heap and +returns it, or None if it is empty.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(1).unwrap();
+heap.push(3).unwrap();
+
+assert_eq!(heap.pop(), Some(3));
+assert_eq!(heap.pop(), Some(1));
+assert_eq!(heap.pop(), None);
+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Removes the top (greatest if max-heap, smallest if min-heap) item from the binary heap and +returns it, without checking if the binary heap is empty.

+
source

pub fn push(&mut self, item: T) -> Result<(), T>

Pushes an item onto the binary heap.

+ +
use heapless::binary_heap::{BinaryHeap, Max};
+
+let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+heap.push(3).unwrap();
+heap.push(5).unwrap();
+heap.push(1).unwrap();
+
+assert_eq!(heap.len(), 3);
+assert_eq!(heap.peek(), Some(&5));
+
source

pub unsafe fn push_unchecked(&mut self, item: T)

Pushes an item onto the binary heap without first checking if it’s full.

+
source

pub fn into_vec(self) -> Vec<T, N>

Returns the underlying Vec<T,N>. Order is arbitrary and time is O(1).

+

Trait Implementations§

source§

impl<T, K, const N: usize> Clone for BinaryHeap<T, K, N>where + K: Kind, + T: Ord + Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, K, const N: usize> Debug for BinaryHeap<T, K, N>where + K: Kind, + T: Ord + Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, K, const N: usize> Default for BinaryHeap<T, K, N>where + T: Ord, + K: Kind,

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'a, T, K, const N: usize> IntoIterator for &'a BinaryHeap<T, K, N>where + K: Kind, + T: Ord,

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, K, const N: usize> RefUnwindSafe for BinaryHeap<T, K, N>where + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, K, const N: usize> Send for BinaryHeap<T, K, N>where + K: Send, + T: Send,

§

impl<T, K, const N: usize> Sync for BinaryHeap<T, K, N>where + K: Sync, + T: Sync,

§

impl<T, K, const N: usize> Unpin for BinaryHeap<T, K, N>where + K: Unpin, + T: Unpin,

§

impl<T, K, const N: usize> UnwindSafe for BinaryHeap<T, K, N>where + K: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/struct.PeekMut.html b/docs/doc/heapless/binary_heap/struct.PeekMut.html new file mode 100644 index 0000000..eabcd5c --- /dev/null +++ b/docs/doc/heapless/binary_heap/struct.PeekMut.html @@ -0,0 +1,32 @@ +PeekMut in heapless::binary_heap - Rust
pub struct PeekMut<'a, T, K, const N: usize>where
+    T: Ord,
+    K: Kind,{ /* private fields */ }
Expand description

Structure wrapping a mutable reference to the greatest item on a +BinaryHeap.

+

This struct is created by the peek_mut method on BinaryHeap. See +its documentation for more.

+

Implementations§

source§

impl<'a, T, K, const N: usize> PeekMut<'a, T, K, N>where + T: Ord, + K: Kind,

source

pub fn pop(this: PeekMut<'a, T, K, N>) -> T

Removes the peeked value from the heap and returns it.

+

Trait Implementations§

source§

impl<T, K, const N: usize> Deref for PeekMut<'_, T, K, N>where + T: Ord, + K: Kind,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
source§

impl<T, K, const N: usize> DerefMut for PeekMut<'_, T, K, N>where + T: Ord, + K: Kind,

source§

fn deref_mut(&mut self) -> &mut T

Mutably dereferences the value.
source§

impl<T, K, const N: usize> Drop for PeekMut<'_, T, K, N>where + T: Ord, + K: Kind,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'a, T, K, const N: usize> RefUnwindSafe for PeekMut<'a, T, K, N>where + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<'a, T, K, const N: usize> Send for PeekMut<'a, T, K, N>where + K: Send, + T: Send,

§

impl<'a, T, K, const N: usize> Sync for PeekMut<'a, T, K, N>where + K: Sync, + T: Sync,

§

impl<'a, T, K, const N: usize> Unpin for PeekMut<'a, T, K, N>

§

impl<'a, T, K, const N: usize> !UnwindSafe for PeekMut<'a, T, K, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/binary_heap/trait.Kind.html b/docs/doc/heapless/binary_heap/trait.Kind.html new file mode 100644 index 0000000..a08f54e --- /dev/null +++ b/docs/doc/heapless/binary_heap/trait.Kind.html @@ -0,0 +1,2 @@ +Kind in heapless::binary_heap - Rust
pub trait Kind: Sealed { }
Expand description

The binary heap kind: min-heap or max-heap

+

Implementors§

source§

impl Kind for Max

source§

impl Kind for Min

\ No newline at end of file diff --git a/docs/doc/heapless/deque/struct.Deque.html b/docs/doc/heapless/deque/struct.Deque.html new file mode 100644 index 0000000..bed2056 --- /dev/null +++ b/docs/doc/heapless/deque/struct.Deque.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.Deque.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/enum.Entry.html b/docs/doc/heapless/enum.Entry.html new file mode 100644 index 0000000..c007eb4 --- /dev/null +++ b/docs/doc/heapless/enum.Entry.html @@ -0,0 +1,24 @@ +Entry in heapless - Rust

Enum heapless::Entry

source ·
pub enum Entry<'a, K, V, const N: usize> {
+    Occupied(OccupiedEntry<'a, K, V, N>),
+    Vacant(VacantEntry<'a, K, V, N>),
+}
Expand description

A view into an entry in the map

+

Variants§

§

Occupied(OccupiedEntry<'a, K, V, N>)

The entry corresponding to the key K exists in the map

+
§

Vacant(VacantEntry<'a, K, V, N>)

The entry corresponding to the key K does not exist in the map

+

Auto Trait Implementations§

§

impl<'a, K, V, const N: usize> RefUnwindSafe for Entry<'a, K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<'a, K, V, const N: usize> Send for Entry<'a, K, V, N>where + K: Send, + V: Send,

§

impl<'a, K, V, const N: usize> Sync for Entry<'a, K, V, N>where + K: Sync, + V: Sync,

§

impl<'a, K, V, const N: usize> Unpin for Entry<'a, K, V, N>where + K: Unpin,

§

impl<'a, K, V, const N: usize> !UnwindSafe for Entry<'a, K, V, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/histbuf/struct.HistoryBuffer.html b/docs/doc/heapless/histbuf/struct.HistoryBuffer.html new file mode 100644 index 0000000..e82b382 --- /dev/null +++ b/docs/doc/heapless/histbuf/struct.HistoryBuffer.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.HistoryBuffer.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/histbuf/struct.OldestOrdered.html b/docs/doc/heapless/histbuf/struct.OldestOrdered.html new file mode 100644 index 0000000..5f3824b --- /dev/null +++ b/docs/doc/heapless/histbuf/struct.OldestOrdered.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.OldestOrdered.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/index.html b/docs/doc/heapless/index.html new file mode 100644 index 0000000..c7e4a4d --- /dev/null +++ b/docs/doc/heapless/index.html @@ -0,0 +1,64 @@ +heapless - Rust

Crate heapless

source ·
Expand description

static friendly data structures that don’t require dynamic memory allocation

+

The core principle behind heapless is that its data structures are backed by a static memory +allocation. For example, you can think of heapless::Vec as an alternative version of +std::Vec with fixed capacity and that can’t be re-allocated on the fly (e.g. via push).

+

All heapless data structures store their memory allocation inline and specify their capacity +via their type parameter N. This means that you can instantiate a heapless data structure on +the stack, in a static variable, or even in the heap.

+ +
use heapless::Vec; // fixed capacity `std::Vec`
+
+// on the stack
+let mut xs: Vec<u8, 8> = Vec::new(); // can hold up to 8 elements
+xs.push(42).unwrap();
+assert_eq!(xs.pop(), Some(42));
+
+// in a `static` variable
+static mut XS: Vec<u8, 8> = Vec::new();
+
+let xs = unsafe { &mut XS };
+
+xs.push(42);
+assert_eq!(xs.pop(), Some(42));
+
+// in the heap (though kind of pointless because no reallocation)
+let mut ys: Box<Vec<u8, 8>> = Box::new(Vec::new());
+ys.push(42).unwrap();
+assert_eq!(ys.pop(), Some(42));
+

Because they have fixed capacity heapless data structures don’t implicitly reallocate. This +means that operations like heapless::Vec.push are truly constant time rather than amortized +constant time with potentially unbounded (depends on the allocator) worst case execution time +(which is bad / unacceptable for hard real time applications).

+

heapless data structures don’t use a memory allocator which means no risk of an uncatchable +Out Of Memory (OOM) condition while performing operations on them. It’s certainly possible to +run out of capacity while growing heapless data structures, but the API lets you handle this +possibility by returning a Result on operations that may exhaust the capacity of the data +structure.

+

List of currently implemented data structures:

+ +

Optional Features

+

The heapless crate provides the following optional Cargo features:

+ +

Minimum Supported Rust Version (MSRV)

+

This crate is guaranteed to compile on stable Rust 1.51 and up with its default set of features. +It might compile on older versions but that may change in any new patch release.

+

Re-exports

  • pub use binary_heap::BinaryHeap;
  • pub use indexmap::Bucket;
  • pub use indexmap::Pos;

Modules

  • A priority queue implemented with a binary heap.
  • A fixed sorted priority linked list, similar to BinaryHeap but with different properties +on push, pop, etc. +For example, the sorting of the list will never memcpy the underlying value, so having large +objects in the list will not cause a performance hit.

Structs

Enums

  • A view into an entry in the map

Type Definitions

\ No newline at end of file diff --git a/docs/doc/heapless/indexmap/enum.Entry.html b/docs/doc/heapless/indexmap/enum.Entry.html new file mode 100644 index 0000000..d262792 --- /dev/null +++ b/docs/doc/heapless/indexmap/enum.Entry.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/enum.Entry.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/indexmap/struct.IndexMap.html b/docs/doc/heapless/indexmap/struct.IndexMap.html new file mode 100644 index 0000000..62bda9b --- /dev/null +++ b/docs/doc/heapless/indexmap/struct.IndexMap.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.IndexMap.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/indexmap/struct.OccupiedEntry.html b/docs/doc/heapless/indexmap/struct.OccupiedEntry.html new file mode 100644 index 0000000..1571dfb --- /dev/null +++ b/docs/doc/heapless/indexmap/struct.OccupiedEntry.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.OccupiedEntry.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/indexmap/struct.VacantEntry.html b/docs/doc/heapless/indexmap/struct.VacantEntry.html new file mode 100644 index 0000000..fdd96b9 --- /dev/null +++ b/docs/doc/heapless/indexmap/struct.VacantEntry.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.VacantEntry.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/indexmap/type.FnvIndexMap.html b/docs/doc/heapless/indexmap/type.FnvIndexMap.html new file mode 100644 index 0000000..833b42e --- /dev/null +++ b/docs/doc/heapless/indexmap/type.FnvIndexMap.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/type.FnvIndexMap.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/indexset/struct.IndexSet.html b/docs/doc/heapless/indexset/struct.IndexSet.html new file mode 100644 index 0000000..94efaaf --- /dev/null +++ b/docs/doc/heapless/indexset/struct.IndexSet.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.IndexSet.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/indexset/type.FnvIndexSet.html b/docs/doc/heapless/indexset/type.FnvIndexSet.html new file mode 100644 index 0000000..3324f20 --- /dev/null +++ b/docs/doc/heapless/indexset/type.FnvIndexSet.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/type.FnvIndexSet.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/linear_map/struct.LinearMap.html b/docs/doc/heapless/linear_map/struct.LinearMap.html new file mode 100644 index 0000000..a377206 --- /dev/null +++ b/docs/doc/heapless/linear_map/struct.LinearMap.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.LinearMap.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/sidebar-items.js b/docs/doc/heapless/sidebar-items.js new file mode 100644 index 0000000..0e3275a --- /dev/null +++ b/docs/doc/heapless/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Entry"],"mod":["binary_heap","sorted_linked_list"],"struct":["Deque","HistoryBuffer","IndexMap","IndexSet","LinearMap","OccupiedEntry","OldestOrdered","String","VacantEntry","Vec"],"type":["FnvIndexMap","FnvIndexSet"]}; \ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/index.html b/docs/doc/heapless/sorted_linked_list/index.html new file mode 100644 index 0000000..a895e23 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/index.html @@ -0,0 +1,21 @@ +heapless::sorted_linked_list - Rust
Expand description

A fixed sorted priority linked list, similar to BinaryHeap but with different properties +on push, pop, etc. +For example, the sorting of the list will never memcpy the underlying value, so having large +objects in the list will not cause a performance hit.

+

Examples

+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+// The largest value will always be first
+ll.push(1).unwrap();
+assert_eq!(ll.peek(), Some(&1));
+
+ll.push(2).unwrap();
+assert_eq!(ll.peek(), Some(&2));
+
+ll.push(3).unwrap();
+assert_eq!(ll.peek(), Some(&3));
+
+// This will not fit in the queue.
+assert_eq!(ll.push(4), Err(4));
+

Structs

Traits

  • The linked list kind: min-list or max-list
  • Trait for defining an index for the linked list, never implemented by users.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/sidebar-items.js b/docs/doc/heapless/sorted_linked_list/sidebar-items.js new file mode 100644 index 0000000..ae6b39f --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["FindMut","Iter","LinkedIndexU16","LinkedIndexU8","LinkedIndexUsize","Max","Min","Node","SortedLinkedList"],"trait":["Kind","SortedLinkedListIndex"]}; \ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.FindMut.html b/docs/doc/heapless/sorted_linked_list/struct.FindMut.html new file mode 100644 index 0000000..a3b872c --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.FindMut.html @@ -0,0 +1,77 @@ +FindMut in heapless::sorted_linked_list - Rust
pub struct FindMut<'a, T, Idx, K, const N: usize>where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,{ /* private fields */ }
Expand description

Implementations§

source§

impl<'a, T, Idx, K, const N: usize> FindMut<'a, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source

pub fn pop(self) -> T

This will pop the element from the list.

+

Complexity is worst-case O(1).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+ll.push(3).unwrap();
+
+// Find a value and update it
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+find.pop();
+
+assert_eq!(ll.pop(), Ok(3));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+
source

pub fn finish(self)

This will resort the element into the correct position in the list if needed. The resorting +will only happen if the element has been accessed mutably.

+

Same as calling drop.

+

Complexity is worst-case O(N).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+ll.push(3).unwrap();
+
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+find.finish(); // No resort, we did not access the value.
+
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+*find += 1000;
+find.finish(); // Will resort, we accessed (and updated) the value.
+
+assert_eq!(ll.pop(), Ok(1002));
+assert_eq!(ll.pop(), Ok(3));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+

Trait Implementations§

source§

impl<T, Idx, K, const N: usize> Deref for FindMut<'_, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl<T, Idx, K, const N: usize> DerefMut for FindMut<'_, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<T, Idx, K, const N: usize> Drop for FindMut<'_, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'a, T, Idx, K, const N: usize> RefUnwindSafe for FindMut<'a, T, Idx, K, N>where + Idx: RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<'a, T, Idx, K, const N: usize> Send for FindMut<'a, T, Idx, K, N>where + Idx: Send, + K: Send, + T: Send,

§

impl<'a, T, Idx, K, const N: usize> Sync for FindMut<'a, T, Idx, K, N>where + Idx: Sync, + K: Sync, + T: Sync,

§

impl<'a, T, Idx, K, const N: usize> Unpin for FindMut<'a, T, Idx, K, N>where + Idx: Unpin,

§

impl<'a, T, Idx, K, const N: usize> !UnwindSafe for FindMut<'a, T, Idx, K, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.Iter.html b/docs/doc/heapless/sorted_linked_list/struct.Iter.html new file mode 100644 index 0000000..34b523d --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.Iter.html @@ -0,0 +1,205 @@ +Iter in heapless::sorted_linked_list - Rust
pub struct Iter<'a, T, Idx, K, const N: usize>where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,{ /* private fields */ }
Expand description

Iterator for the linked list.

+

Trait Implementations§

source§

impl<'a, T, Idx, K, const N: usize> Iterator for Iter<'a, T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

§

type Item = &'a T

The type of the elements being iterated over.
source§

fn next(&mut self) -> Option<Self::Item>

Advances the iterator and returns the next value. Read more
§

fn next_chunk<const N: usize>( + &mut self +) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.0.0§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
1.0.0§

fn count(self) -> usizewhere + Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
1.0.0§

fn last(self) -> Option<Self::Item>where + Self: Sized,

Consumes the iterator, returning the last element. Read more
§

fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.0.0§

fn nth(&mut self, n: usize) -> Option<Self::Item>

Returns the nth element of the iterator. Read more
1.28.0§

fn step_by(self, step: usize) -> StepBy<Self>where + Self: Sized,

Creates an iterator starting at the same point, but stepping by +the given amount at each iteration. Read more
1.0.0§

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.0.0§

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator,

‘Zips up’ two iterators into a single iterator of pairs. Read more
§

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>where + Self: Sized, + G: FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator +between adjacent items of the original iterator. Read more
1.0.0§

fn map<B, F>(self, f: F) -> Map<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each +element. Read more
1.21.0§

fn for_each<F>(self, f: F)where + Self: Sized, + F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.0.0§

fn filter<P>(self, predicate: P) -> Filter<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element +should be yielded. Read more
1.0.0§

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.0.0§

fn enumerate(self) -> Enumerate<Self>where + Self: Sized,

Creates an iterator which gives the current iteration count as well as +the next value. Read more
1.0.0§

fn peekable(self) -> Peekable<Self>where + Self: Sized,

Creates an iterator which can use the peek and peek_mut methods +to look at the next element of the iterator without consuming it. See +their documentation for more information. Read more
1.0.0§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.0.0§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where + Self: Sized, + P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.0.0§

fn skip(self, n: usize) -> Skip<Self>where + Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.0.0§

fn take(self, n: usize) -> Take<Self>where + Self: Sized,

Creates an iterator that yields the first n elements, or fewer +if the underlying iterator ends sooner. Read more
1.0.0§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where + Self: Sized, + F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but +unlike fold, produces a new iterator. Read more
1.0.0§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where + Self: Sized, + U: IntoIterator, + F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
1.0.0§

fn fuse(self) -> Fuse<Self>where + Self: Sized,

Creates an iterator which ends after the first [None]. Read more
1.0.0§

fn inspect<F>(self, f: F) -> Inspect<Self, F>where + Self: Sized, + F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.0.0§

fn by_ref(&mut self) -> &mut Selfwhere + Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.0.0§

fn collect<B>(self) -> Bwhere + B: FromIterator<Self::Item>, + Self: Sized,

Transforms an iterator into a collection. Read more
§

fn collect_into<E>(self, collection: &mut E) -> &mut Ewhere + E: Extend<Self::Item>, + Self: Sized,

🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.0.0§

fn partition<B, F>(self, f: F) -> (B, B)where + Self: Sized, + B: Default + Extend<Self::Item>, + F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
§

fn is_partitioned<P>(self, predicate: P) -> boolwhere + Self: Sized, + P: FnMut(Self::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate, +such that all those that return true precede all those that return false. Read more
1.27.0§

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try<Output = B>,

An iterator method that applies a function as long as it returns +successfully, producing a single, final value. Read more
1.27.0§

fn try_for_each<F, R>(&mut self, f: F) -> Rwhere + Self: Sized, + F: FnMut(Self::Item) -> R, + R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the +iterator, stopping at the first error and returning that error. Read more
1.0.0§

fn fold<B, F>(self, init: B, f: F) -> Bwhere + Self: Sized, + F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation, +returning the final result. Read more
1.51.0§

fn reduce<F>(self, f: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing +operation. Read more
§

fn try_reduce<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> R, + R: Try<Output = Self::Item>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the +closure returns a failure, the failure is propagated back to the caller immediately. Read more
1.0.0§

fn all<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.0.0§

fn any<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.0.0§

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0§

fn find_map<B, F>(&mut self, f: F) -> Option<B>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns +the first non-none result. Read more
§

fn try_find<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere + Self: Sized, + F: FnMut(&Self::Item) -> R, + R: Try<Output = bool>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns +the first true result or the first error. Read more
1.0.0§

fn position<P>(&mut self, predicate: P) -> Option<usize>where + Self: Sized, + P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0§

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the +specified function. Read more
1.15.0§

fn max_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the +specified comparison function. Read more
1.6.0§

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the +specified function. Read more
1.15.0§

fn min_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the +specified comparison function. Read more
1.0.0§

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where + FromA: Default + Extend<A>, + FromB: Default + Extend<B>, + Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0§

fn copied<'a, T>(self) -> Copied<Self>where + T: 'a + Copy, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.0.0§

fn cloned<'a, T>(self) -> Cloned<Self>where + T: 'a + Clone, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
§

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0§

fn sum<S>(self) -> Swhere + Self: Sized, + S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0§

fn product<P>(self) -> Pwhere + Self: Sized, + P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
§

fn cmp_by<I, F>(self, other: I, cmp: F) -> Orderingwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn partial_cmp<I>(self, other: I) -> Option<Ordering>where + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Lexicographically compares the [PartialOrd] elements of +this [Iterator] with those of another. The comparison works like short-circuit +evaluation, returning a result without comparing the remaining elements. +As soon as an order can be determined, the evaluation stops and a result is returned. Read more
§

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn eq<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are equal to those of +another. Read more
§

fn eq_by<I, F>(self, other: I, eq: F) -> boolwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this [Iterator] are equal to those of +another with respect to the specified equality function. Read more
1.5.0§

fn ne<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are not equal to those of +another. Read more
1.5.0§

fn lt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less than those of another. Read more
1.5.0§

fn le<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less or equal to those of another. Read more
1.5.0§

fn gt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than those of another. Read more
1.5.0§

fn ge<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than or equal to those of another. Read more
§

fn is_sorted_by<F>(self, compare: F) -> boolwhere + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
§

fn is_sorted_by_key<F, K>(self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction +function. Read more

Auto Trait Implementations§

§

impl<'a, T, Idx, K, const N: usize> RefUnwindSafe for Iter<'a, T, Idx, K, N>where + Idx: RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<'a, T, Idx, K, const N: usize> Send for Iter<'a, T, Idx, K, N>where + Idx: Send + Sync, + K: Sync, + T: Sync,

§

impl<'a, T, Idx, K, const N: usize> Sync for Iter<'a, T, Idx, K, N>where + Idx: Sync, + K: Sync, + T: Sync,

§

impl<'a, T, Idx, K, const N: usize> Unpin for Iter<'a, T, Idx, K, N>where + Idx: Unpin,

§

impl<'a, T, Idx, K, const N: usize> UnwindSafe for Iter<'a, T, Idx, K, N>where + Idx: UnwindSafe + RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<I> IntoIterator for Iwhere + I: Iterator,

§

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
§

type IntoIter = I

Which kind of iterator are we turning this into?
const: unstable§

fn into_iter(self) -> I

Creates an iterator from a value. Read more
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU16.html b/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU16.html new file mode 100644 index 0000000..c0ccd0d --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU16.html @@ -0,0 +1,19 @@ +LinkedIndexU16 in heapless::sorted_linked_list - Rust
pub struct LinkedIndexU16(_);
Expand description

Index for the SortedLinkedList with specific backing storage.

+

Trait Implementations§

source§

impl Clone for LinkedIndexU16

source§

fn clone(&self) -> LinkedIndexU16

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LinkedIndexU16

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Ord for LinkedIndexU16

source§

fn cmp(&self, other: &LinkedIndexU16) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LinkedIndexU16> for LinkedIndexU16

source§

fn eq(&self, other: &LinkedIndexU16) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LinkedIndexU16> for LinkedIndexU16

source§

fn partial_cmp(&self, other: &LinkedIndexU16) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LinkedIndexU16

source§

impl Eq for LinkedIndexU16

source§

impl SortedLinkedListIndex for LinkedIndexU16

source§

impl StructuralEq for LinkedIndexU16

source§

impl StructuralPartialEq for LinkedIndexU16

Auto Trait Implementations§

§

impl RefUnwindSafe for LinkedIndexU16

§

impl Send for LinkedIndexU16

§

impl Sync for LinkedIndexU16

§

impl Unpin for LinkedIndexU16

§

impl UnwindSafe for LinkedIndexU16

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU8.html b/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU8.html new file mode 100644 index 0000000..1d612d8 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexU8.html @@ -0,0 +1,19 @@ +LinkedIndexU8 in heapless::sorted_linked_list - Rust
pub struct LinkedIndexU8(_);
Expand description

Index for the SortedLinkedList with specific backing storage.

+

Trait Implementations§

source§

impl Clone for LinkedIndexU8

source§

fn clone(&self) -> LinkedIndexU8

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LinkedIndexU8

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Ord for LinkedIndexU8

source§

fn cmp(&self, other: &LinkedIndexU8) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LinkedIndexU8> for LinkedIndexU8

source§

fn eq(&self, other: &LinkedIndexU8) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LinkedIndexU8> for LinkedIndexU8

source§

fn partial_cmp(&self, other: &LinkedIndexU8) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LinkedIndexU8

source§

impl Eq for LinkedIndexU8

source§

impl SortedLinkedListIndex for LinkedIndexU8

source§

impl StructuralEq for LinkedIndexU8

source§

impl StructuralPartialEq for LinkedIndexU8

Auto Trait Implementations§

§

impl RefUnwindSafe for LinkedIndexU8

§

impl Send for LinkedIndexU8

§

impl Sync for LinkedIndexU8

§

impl Unpin for LinkedIndexU8

§

impl UnwindSafe for LinkedIndexU8

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexUsize.html b/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexUsize.html new file mode 100644 index 0000000..d0a1e45 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.LinkedIndexUsize.html @@ -0,0 +1,19 @@ +LinkedIndexUsize in heapless::sorted_linked_list - Rust
pub struct LinkedIndexUsize(_);
Expand description

Index for the SortedLinkedList with specific backing storage.

+

Trait Implementations§

source§

impl Clone for LinkedIndexUsize

source§

fn clone(&self) -> LinkedIndexUsize

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for LinkedIndexUsize

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Ord for LinkedIndexUsize

source§

fn cmp(&self, other: &LinkedIndexUsize) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<LinkedIndexUsize> for LinkedIndexUsize

source§

fn eq(&self, other: &LinkedIndexUsize) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<LinkedIndexUsize> for LinkedIndexUsize

source§

fn partial_cmp(&self, other: &LinkedIndexUsize) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl Copy for LinkedIndexUsize

source§

impl Eq for LinkedIndexUsize

source§

impl SortedLinkedListIndex for LinkedIndexUsize

source§

impl StructuralEq for LinkedIndexUsize

source§

impl StructuralPartialEq for LinkedIndexUsize

Auto Trait Implementations§

§

impl RefUnwindSafe for LinkedIndexUsize

§

impl Send for LinkedIndexUsize

§

impl Sync for LinkedIndexUsize

§

impl Unpin for LinkedIndexUsize

§

impl UnwindSafe for LinkedIndexUsize

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.Max.html b/docs/doc/heapless/sorted_linked_list/struct.Max.html new file mode 100644 index 0000000..1c92549 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.Max.html @@ -0,0 +1,12 @@ +Max in heapless::sorted_linked_list - Rust
pub struct Max;
Expand description

Marker for Max sorted SortedLinkedList.

+

Trait Implementations§

source§

impl Kind for Max

Auto Trait Implementations§

§

impl RefUnwindSafe for Max

§

impl Send for Max

§

impl Sync for Max

§

impl Unpin for Max

§

impl UnwindSafe for Max

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.Min.html b/docs/doc/heapless/sorted_linked_list/struct.Min.html new file mode 100644 index 0000000..2b81879 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.Min.html @@ -0,0 +1,12 @@ +Min in heapless::sorted_linked_list - Rust
pub struct Min;
Expand description

Marker for Min sorted SortedLinkedList.

+

Trait Implementations§

source§

impl Kind for Min

Auto Trait Implementations§

§

impl RefUnwindSafe for Min

§

impl Send for Min

§

impl Sync for Min

§

impl Unpin for Min

§

impl UnwindSafe for Min

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.Node.html b/docs/doc/heapless/sorted_linked_list/struct.Node.html new file mode 100644 index 0000000..504014c --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.Node.html @@ -0,0 +1,22 @@ +Node in heapless::sorted_linked_list - Rust
pub struct Node<T, Idx> { /* private fields */ }
Expand description

A node in the SortedLinkedList.

+

Auto Trait Implementations§

§

impl<T, Idx> RefUnwindSafe for Node<T, Idx>where + Idx: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, Idx> Send for Node<T, Idx>where + Idx: Send, + T: Send,

§

impl<T, Idx> Sync for Node<T, Idx>where + Idx: Sync, + T: Sync,

§

impl<T, Idx> Unpin for Node<T, Idx>where + Idx: Unpin, + T: Unpin,

§

impl<T, Idx> UnwindSafe for Node<T, Idx>where + Idx: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/struct.SortedLinkedList.html b/docs/doc/heapless/sorted_linked_list/struct.SortedLinkedList.html new file mode 100644 index 0000000..937fd41 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/struct.SortedLinkedList.html @@ -0,0 +1,151 @@ +SortedLinkedList in heapless::sorted_linked_list - Rust
pub struct SortedLinkedList<T, Idx, K, const N: usize>where
+    Idx: SortedLinkedListIndex,{ /* private fields */ }
Expand description

The linked list.

+

Implementations§

source§

impl<T, K, const N: usize> SortedLinkedList<T, LinkedIndexU8, K, N>

source

pub const fn new_u8() -> Self

Create a new linked list.

+
source§

impl<T, K, const N: usize> SortedLinkedList<T, LinkedIndexU16, K, N>

source

pub const fn new_u16() -> Self

Create a new linked list.

+
source§

impl<T, K, const N: usize> SortedLinkedList<T, LinkedIndexUsize, K, N>

source

pub const fn new_usize() -> Self

Create a new linked list.

+
source§

impl<T, Idx, K, const N: usize> SortedLinkedList<T, Idx, K, N>where + T: Ord, + Idx: SortedLinkedListIndex, + K: Kind,

source

pub unsafe fn push_unchecked(&mut self, value: T)

Pushes a value onto the list without checking if the list is full.

+

Complexity is worst-case O(N).

+
Safety
+

Assumes that the list is not full.

+
source

pub fn push(&mut self, value: T) -> Result<(), T>

Pushes an element to the linked list and sorts it into place.

+

Complexity is worst-case O(N).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+// The largest value will always be first
+ll.push(1).unwrap();
+assert_eq!(ll.peek(), Some(&1));
+
+ll.push(2).unwrap();
+assert_eq!(ll.peek(), Some(&2));
+
+ll.push(3).unwrap();
+assert_eq!(ll.peek(), Some(&3));
+
+// This will not fit in the queue.
+assert_eq!(ll.push(4), Err(4));
+
source

pub fn iter(&self) -> Iter<'_, T, Idx, K, N>

Get an iterator over the sorted list.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+
+let mut iter = ll.iter();
+
+assert_eq!(iter.next(), Some(&2));
+assert_eq!(iter.next(), Some(&1));
+assert_eq!(iter.next(), None);
+
source

pub fn find_mut<F>(&mut self, f: F) -> Option<FindMut<'_, T, Idx, K, N>>where + F: FnMut(&T) -> bool,

Find an element in the list that can be changed and resorted.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+ll.push(3).unwrap();
+
+// Find a value and update it
+let mut find = ll.find_mut(|v| *v == 2).unwrap();
+*find += 1000;
+find.finish();
+
+assert_eq!(ll.pop(), Ok(1002));
+assert_eq!(ll.pop(), Ok(3));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+
source

pub fn peek(&self) -> Option<&T>

Peek at the first element.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max, Min};
+let mut ll_max: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+// The largest value will always be first
+ll_max.push(1).unwrap();
+assert_eq!(ll_max.peek(), Some(&1));
+ll_max.push(2).unwrap();
+assert_eq!(ll_max.peek(), Some(&2));
+ll_max.push(3).unwrap();
+assert_eq!(ll_max.peek(), Some(&3));
+
+let mut ll_min: SortedLinkedList<_, _, Min, 3> = SortedLinkedList::new_usize();
+
+// The Smallest value will always be first
+ll_min.push(3).unwrap();
+assert_eq!(ll_min.peek(), Some(&3));
+ll_min.push(2).unwrap();
+assert_eq!(ll_min.peek(), Some(&2));
+ll_min.push(1).unwrap();
+assert_eq!(ll_min.peek(), Some(&1));
+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Pop an element from the list without checking so the list is not empty.

+
Safety
+

Assumes that the list is not empty.

+
source

pub fn pop(&mut self) -> Result<T, ()>

Pops the first element in the list.

+

Complexity is worst-case O(1).

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+ll.push(1).unwrap();
+ll.push(2).unwrap();
+
+assert_eq!(ll.pop(), Ok(2));
+assert_eq!(ll.pop(), Ok(1));
+assert_eq!(ll.pop(), Err(()));
+
source

pub fn is_full(&self) -> bool

Checks if the linked list is full.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+assert_eq!(ll.is_full(), false);
+
+ll.push(1).unwrap();
+assert_eq!(ll.is_full(), false);
+ll.push(2).unwrap();
+assert_eq!(ll.is_full(), false);
+ll.push(3).unwrap();
+assert_eq!(ll.is_full(), true);
+
source

pub fn is_empty(&self) -> bool

Checks if the linked list is empty.

+
Example
+
use heapless::sorted_linked_list::{SortedLinkedList, Max};
+let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+
+assert_eq!(ll.is_empty(), true);
+
+ll.push(1).unwrap();
+assert_eq!(ll.is_empty(), false);
+

Trait Implementations§

source§

impl<T, Idx, K, const N: usize> Debug for SortedLinkedList<T, Idx, K, N>where + T: Ord + Debug, + Idx: SortedLinkedListIndex, + K: Kind,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, Idx, K, const N: usize> Drop for SortedLinkedList<T, Idx, K, N>where + Idx: SortedLinkedListIndex,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T, Idx, K, const N: usize> RefUnwindSafe for SortedLinkedList<T, Idx, K, N>where + Idx: RefUnwindSafe, + K: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, Idx, K, const N: usize> Send for SortedLinkedList<T, Idx, K, N>where + Idx: Send, + K: Send, + T: Send,

§

impl<T, Idx, K, const N: usize> Sync for SortedLinkedList<T, Idx, K, N>where + Idx: Sync, + K: Sync, + T: Sync,

§

impl<T, Idx, K, const N: usize> Unpin for SortedLinkedList<T, Idx, K, N>where + Idx: Unpin, + K: Unpin, + T: Unpin,

§

impl<T, Idx, K, const N: usize> UnwindSafe for SortedLinkedList<T, Idx, K, N>where + Idx: UnwindSafe, + K: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/trait.Kind.html b/docs/doc/heapless/sorted_linked_list/trait.Kind.html new file mode 100644 index 0000000..322cc71 --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/trait.Kind.html @@ -0,0 +1,2 @@ +Kind in heapless::sorted_linked_list - Rust
pub trait Kind: Sealed { }
Expand description

The linked list kind: min-list or max-list

+

Implementors§

source§

impl Kind for Max

source§

impl Kind for Min

\ No newline at end of file diff --git a/docs/doc/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html b/docs/doc/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html new file mode 100644 index 0000000..f33f3db --- /dev/null +++ b/docs/doc/heapless/sorted_linked_list/trait.SortedLinkedListIndex.html @@ -0,0 +1,2 @@ +SortedLinkedListIndex in heapless::sorted_linked_list - Rust
pub trait SortedLinkedListIndex: Copy { }
Expand description

Trait for defining an index for the linked list, never implemented by users.

+

Implementors§

\ No newline at end of file diff --git a/docs/doc/heapless/string/struct.String.html b/docs/doc/heapless/string/struct.String.html new file mode 100644 index 0000000..85a356a --- /dev/null +++ b/docs/doc/heapless/string/struct.String.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.String.html...

+ + + \ No newline at end of file diff --git a/docs/doc/heapless/struct.Deque.html b/docs/doc/heapless/struct.Deque.html new file mode 100644 index 0000000..5a5f974 --- /dev/null +++ b/docs/doc/heapless/struct.Deque.html @@ -0,0 +1,89 @@ +Deque in heapless - Rust

Struct heapless::Deque

source ·
pub struct Deque<T, const N: usize> { /* private fields */ }
Expand description

A fixed capacity double-ended queue.

+

Examples

+
use heapless::Deque;
+
+// A deque with a fixed capacity of 8 elements allocated on the stack
+let mut deque = Deque::<_, 8>::new();
+
+// You can use it as a good old FIFO queue.
+deque.push_back(1);
+deque.push_back(2);
+assert_eq!(deque.len(), 2);
+
+assert_eq!(deque.pop_front(), Some(1));
+assert_eq!(deque.pop_front(), Some(2));
+assert_eq!(deque.len(), 0);
+
+// Deque is double-ended, you can push and pop from the front and back.
+deque.push_back(1);
+deque.push_front(2);
+deque.push_back(3);
+deque.push_front(4);
+assert_eq!(deque.pop_front(), Some(4));
+assert_eq!(deque.pop_front(), Some(2));
+assert_eq!(deque.pop_front(), Some(1));
+assert_eq!(deque.pop_front(), Some(3));
+
+// You can iterate it, yielding all the elements front-to-back.
+for x in &deque {
+    println!("{}", x);
+}
+

Implementations§

source§

impl<T, const N: usize> Deque<T, N>

source

pub const fn new() -> Self

Constructs a new, empty deque with a fixed capacity of N

+
Examples
+
use heapless::Deque;
+
+// allocate the deque on the stack
+let mut x: Deque<u8, 16> = Deque::new();
+
+// allocate the deque in a static variable
+static mut X: Deque<u8, 16> = Deque::new();
+
source

pub const fn capacity(&self) -> usize

Returns the maximum number of elements the deque can hold.

+
source

pub const fn len(&self) -> usize

Returns the number of elements currently in the deque.

+
source

pub fn clear(&mut self)

Clears the deque, removing all values.

+
source

pub fn is_empty(&self) -> bool

Returns whether the deque is empty.

+
source

pub fn is_full(&self) -> bool

Returns whether the deque is full (i.e. if len() == capacity().

+
source

pub fn as_slices(&self) -> (&[T], &[T])

Returns a pair of slices which contain, in order, the contents of the Deque.

+
source

pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T])

Returns a pair of mutable slices which contain, in order, the contents of the Deque.

+
source

pub fn front(&self) -> Option<&T>

Provides a reference to the front element, or None if the Deque is empty.

+
source

pub fn front_mut(&mut self) -> Option<&mut T>

Provides a mutable reference to the front element, or None if the Deque is empty.

+
source

pub fn back(&self) -> Option<&T>

Provides a reference to the back element, or None if the Deque is empty.

+
source

pub fn back_mut(&mut self) -> Option<&mut T>

Provides a mutable reference to the back element, or None if the Deque is empty.

+
source

pub fn pop_front(&mut self) -> Option<T>

Removes the item from the front of the deque and returns it, or None if it’s empty

+
source

pub fn pop_back(&mut self) -> Option<T>

Removes the item from the back of the deque and returns it, or None if it’s empty

+
source

pub fn push_front(&mut self, item: T) -> Result<(), T>

Appends an item to the front of the deque

+

Returns back the item if the deque is full

+
source

pub fn push_back(&mut self, item: T) -> Result<(), T>

Appends an item to the back of the deque

+

Returns back the item if the deque is full

+
source

pub unsafe fn pop_front_unchecked(&mut self) -> T

Removes an item from the front of the deque and returns it, without checking that the deque +is not empty

+
Safety
+

It’s undefined behavior to call this on an empty deque

+
source

pub unsafe fn pop_back_unchecked(&mut self) -> T

Removes an item from the back of the deque and returns it, without checking that the deque +is not empty

+
Safety
+

It’s undefined behavior to call this on an empty deque

+
source

pub unsafe fn push_front_unchecked(&mut self, item: T)

Appends an item to the front of the deque

+
Safety
+

This assumes the deque is not full.

+
source

pub unsafe fn push_back_unchecked(&mut self, item: T)

Appends an item to the back of the deque

+
Safety
+

This assumes the deque is not full.

+
source

pub fn iter(&self) -> Iter<'_, T, N>

Returns an iterator over the deque.

+
source

pub fn iter_mut(&mut self) -> IterMut<'_, T, N>

Returns an iterator that allows modifying each value.

+

Trait Implementations§

source§

impl<T, const N: usize> Clone for Deque<T, N>where + T: Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug, const N: usize> Debug for Deque<T, N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for Deque<T, N>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Drop for Deque<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a Deque<T, N>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a mut Deque<T, N>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> IntoIterator for Deque<T, N>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for Deque<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for Deque<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for Deque<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for Deque<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for Deque<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.HistoryBuffer.html b/docs/doc/heapless/struct.HistoryBuffer.html new file mode 100644 index 0000000..f7e9ecc --- /dev/null +++ b/docs/doc/heapless/struct.HistoryBuffer.html @@ -0,0 +1,1089 @@ +HistoryBuffer in heapless - Rust

Struct heapless::HistoryBuffer

source ·
pub struct HistoryBuffer<T, const N: usize> { /* private fields */ }
Expand description

A “history buffer”, similar to a write-only ring buffer of fixed length.

+

This buffer keeps a fixed number of elements. On write, the oldest element +is overwritten. Thus, the buffer is useful to keep a history of values with +some desired depth, and for example calculate a rolling average.

+

Examples

+
use heapless::HistoryBuffer;
+
+// Initialize a new buffer with 8 elements.
+let mut buf = HistoryBuffer::<_, 8>::new();
+
+// Starts with no data
+assert_eq!(buf.recent(), None);
+
+buf.write(3);
+buf.write(5);
+buf.extend(&[4, 4]);
+
+// The most recent written element is a four.
+assert_eq!(buf.recent(), Some(&4));
+
+// To access all elements in an unspecified order, use `as_slice()`.
+for el in buf.as_slice() { println!("{:?}", el); }
+
+// Now we can prepare an average of all values, which comes out to 4.
+let avg = buf.as_slice().iter().sum::<usize>() / buf.len();
+assert_eq!(avg, 4);
+

Implementations§

source§

impl<T, const N: usize> HistoryBuffer<T, N>

source

pub const fn new() -> Self

Constructs a new history buffer.

+

The construction of a HistoryBuffer works in const contexts.

+
Examples
+
use heapless::HistoryBuffer;
+
+// Allocate a 16-element buffer on the stack
+let x: HistoryBuffer<u8, 16> = HistoryBuffer::new();
+assert_eq!(x.len(), 0);
+
source

pub fn clear(&mut self)

Clears the buffer, replacing every element with the default value of +type T.

+
source§

impl<T, const N: usize> HistoryBuffer<T, N>where + T: Copy + Clone,

source

pub fn new_with(t: T) -> Self

Constructs a new history buffer, where every element is the given value.

+
Examples
+
use heapless::HistoryBuffer;
+
+// Allocate a 16-element buffer on the stack
+let mut x: HistoryBuffer<u8, 16> = HistoryBuffer::new_with(4);
+// All elements are four
+assert_eq!(x.as_slice(), [4; 16]);
+
source

pub fn clear_with(&mut self, t: T)

Clears the buffer, replacing every element with the given value.

+
source§

impl<T, const N: usize> HistoryBuffer<T, N>

source

pub fn len(&self) -> usize

Returns the current fill level of the buffer.

+
source

pub fn capacity(&self) -> usize

Returns the capacity of the buffer, which is the length of the +underlying backing array.

+
source

pub fn write(&mut self, t: T)

Writes an element to the buffer, overwriting the oldest value.

+
source

pub fn extend_from_slice(&mut self, other: &[T])where + T: Clone,

Clones and writes all elements in a slice to the buffer.

+

If the slice is longer than the buffer, only the last self.len() +elements will actually be stored.

+
source

pub fn recent(&self) -> Option<&T>

Returns a reference to the most recently written value.

+
Examples
+
use heapless::HistoryBuffer;
+
+let mut x: HistoryBuffer<u8, 16> = HistoryBuffer::new();
+x.write(4);
+x.write(10);
+assert_eq!(x.recent(), Some(&10));
+
source

pub fn as_slice(&self) -> &[T]

Returns the array slice backing the buffer, without keeping track +of the write position. Therefore, the element order is unspecified.

+
source

pub fn oldest_ordered<'a>(&'a self) -> OldestOrdered<'a, T, N>

Returns an iterator for iterating over the buffer from oldest to newest.

+
Examples
+
use heapless::HistoryBuffer;
+
+let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
+buffer.extend([0, 0, 0, 1, 2, 3, 4, 5, 6]);
+let expected = [1, 2, 3, 4, 5, 6];
+for (x, y) in buffer.oldest_ordered().zip(expected.iter()) {
+    assert_eq!(x, y)
+}
+
+

Methods from Deref<Target = [T]>§

1.23.0

pub fn is_ascii(&self) -> bool

Checks if all bytes in this slice are within the ASCII range.

+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this slice is_ascii, returns it as a slice of +ASCII characters, otherwise returns None.

+

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this slice of bytes into a slice of ASCII characters, +without checking whether they’re valid.

+
Safety
+

Every byte in the slice must be in 0..=127, or else this is UB.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool

Checks that two slices are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
1.60.0

pub fn escape_ascii(&self) -> EscapeAscii<'_>

Returns an iterator that produces an escaped version of this slice, +treating it as an ASCII string.

+
Examples
+

+let s = b"0\t\r\n'\"\\\x9d";
+let escaped = s.escape_ascii().to_string();
+assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
+

pub fn trim_ascii_start(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
+assert_eq!(b"  ".trim_ascii_start(), b"");
+assert_eq!(b"".trim_ascii_start(), b"");
+

pub fn trim_ascii_end(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with trailing ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
+assert_eq!(b"  ".trim_ascii_end(), b"");
+assert_eq!(b"".trim_ascii_end(), b"");
+

pub fn trim_ascii(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading and trailing ASCII whitespace bytes +removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
+assert_eq!(b"  ".trim_ascii(), b"");
+assert_eq!(b"".trim_ascii(), b"");
+

pub fn as_str(&self) -> &str

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a UTF-8 str.

+

pub fn as_bytes(&self) -> &[u8]

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a slice of u8 bytes.

+

pub fn flatten(&self) -> &[T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &[[T; N]], and flattens it to a &[T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
+
+assert_eq!(
+    [[1, 2, 3], [4, 5, 6]].flatten(),
+    [[1, 2], [3, 4], [5, 6]].flatten(),
+);
+
+let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
+assert!(slice_of_empty_arrays.flatten().is_empty());
+
+let empty_slice_of_arrays: &[[u32; 10]] = &[];
+assert!(empty_slice_of_arrays.flatten().is_empty());
+
1.0.0

pub fn len(&self) -> usize

Returns the number of elements in the slice.

+
Examples
+
let a = [1, 2, 3];
+assert_eq!(a.len(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if the slice has a length of 0.

+
Examples
+
let a = [1, 2, 3];
+assert!(!a.is_empty());
+
1.0.0

pub fn first(&self) -> Option<&T>

Returns the first element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&10), v.first());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.first());
+
1.5.0

pub fn split_first(&self) -> Option<(&T, &[T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first() {
+    assert_eq!(first, &0);
+    assert_eq!(elements, &[1, 2]);
+}
+
1.5.0

pub fn split_last(&self) -> Option<(&T, &[T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last() {
+    assert_eq!(last, &2);
+    assert_eq!(elements, &[0, 1]);
+}
+
1.0.0

pub fn last(&self) -> Option<&T>

Returns the last element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&30), v.last());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.last());
+

pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice, or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.first_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.first_chunk::<0>());
+

pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk::<2>() {
+    assert_eq!(first, &[0, 1]);
+    assert_eq!(elements, &[2]);
+}
+

pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk::<2>() {
+    assert_eq!(last, &[1, 2]);
+    assert_eq!(elements, &[0]);
+}
+

pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last element of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.last_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.last_chunk::<0>());
+
1.0.0

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a reference to an element or subslice depending on the type of +index.

+
    +
  • If given a position, returns a reference to the element at that +position or None if out of bounds.
  • +
  • If given a range, returns the subslice corresponding to that range, +or None if out of bounds.
  • +
+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&40), v.get(1));
+assert_eq!(Some(&[10, 40][..]), v.get(0..2));
+assert_eq!(None, v.get(3));
+assert_eq!(None, v.get(0..4));
+
1.0.0

pub unsafe fn get_unchecked<I>( + &self, + index: I +) -> &<I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a reference to an element or subslice, without doing bounds +checking.

+

For a safe alternative see get.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &[1, 2, 4];
+
+unsafe {
+    assert_eq!(x.get_unchecked(1), &2);
+}
+
1.0.0

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

The caller must also ensure that the memory the pointer (non-transitively) points to +is never written to (except inside an UnsafeCell) using this pointer or any pointer +derived 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 +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &[1, 2, 4];
+let x_ptr = x.as_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
+    }
+}
+
1.48.0

pub fn as_ptr_range(&self) -> Range<*const T>

Returns the two raw pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_ptr for warnings on using these pointers. The end pointer +requires extra caution, as it does not point to a valid element in the +slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+

It can also be useful to check if a pointer to an element refers to an +element of this slice:

+ +
let a = [1, 2, 3];
+let x = &a[1] as *const _;
+let y = &5 as *const _;
+
+assert!(a.as_ptr_range().contains(&x));
+assert!(!a.as_ptr_range().contains(&y));
+
1.0.0

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the slice.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &[1, 2, 4];
+let mut iterator = x.iter();
+
+assert_eq!(iterator.next(), Some(&1));
+assert_eq!(iterator.next(), Some(&2));
+assert_eq!(iterator.next(), Some(&4));
+assert_eq!(iterator.next(), None);
+
1.0.0

pub fn windows(&self, size: usize) -> Windows<'_, T>

Returns an iterator over all contiguous windows of length +size. The windows overlap. If the slice is shorter than +size, the iterator returns no values.

+
Panics
+

Panics if size is 0.

+
Examples
+
let slice = ['r', 'u', 's', 't'];
+let mut iter = slice.windows(2);
+assert_eq!(iter.next().unwrap(), &['r', 'u']);
+assert_eq!(iter.next().unwrap(), &['u', 's']);
+assert_eq!(iter.next().unwrap(), &['s', 't']);
+assert!(iter.next().is_none());
+

If the slice is shorter than size:

+ +
let slice = ['f', 'o', 'o'];
+let mut iter = slice.windows(4);
+assert!(iter.next().is_none());
+

There’s no windows_mut, as that existing would let safe code violate the +“only one &mut at a time to the same thing” rule. However, you can sometimes +use Cell::as_slice_of_cells in +conjunction with windows to accomplish something similar:

+ +
use std::cell::Cell;
+
+let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
+let slice = &mut array[..];
+let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
+for w in slice_of_cells.windows(3) {
+    Cell::swap(&w[0], &w[2]);
+}
+assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
+
1.0.0

pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and rchunks for the same iterator but starting at the end of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert_eq!(iter.next().unwrap(), &['m']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of chunks.

+

See chunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and rchunks_exact for the same iterator but starting at the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &[[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &[[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
+

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (chunks, remainder) = slice.as_chunks();
+assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
+assert_eq!(remainder, &['m']);
+

If you expect the slice to be an exact multiple, you can combine +let-else with an empty slice pattern:

+ +
#![feature(slice_as_chunks)]
+let slice = ['R', 'u', 's', 't'];
+let (chunks, []) = slice.as_chunks::<2>() else {
+    panic!("slice didn't have even length")
+};
+assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
+

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (remainder, chunks) = slice.as_rchunks();
+assert_eq!(remainder, &['l']);
+assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
+

pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are array references and do not overlap. If N does not divide the +length of the slice, then the last up to N-1 elements will be omitted and can be +retrieved from the remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.array_chunks();
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>

🔬This is a nightly-only experimental API. (array_windows)

Returns an iterator over overlapping windows of N elements of a slice, +starting 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
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_windows)]
+let slice = [0, 1, 2, 3];
+let mut iter = slice.array_windows();
+assert_eq!(iter.next().unwrap(), &[0, 1]);
+assert_eq!(iter.next().unwrap(), &[1, 2]);
+assert_eq!(iter.next().unwrap(), &[2, 3]);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and chunks for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert_eq!(iter.next().unwrap(), &['l']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +end of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of rchunks.

+

See rchunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and chunks_exact for the same iterator but starting at the beginning of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['l']);
+

pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping runs +of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&[3, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+
1.0.0

pub fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let v = [1, 2, 3, 4, 5, 6];
+
+{
+   let (left, right) = v.split_at(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let v = [1, 2, 3, 4, 5, 6];
+
+unsafe {
+   let (left, right) = v.split_at_unchecked(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.split_array_ref::<0>();
+   assert_eq!(left, &[]);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<2>();
+    assert_eq!(left, &[1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<6>();
+    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index from +the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index len - N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.rsplit_array_ref::<0>();
+   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+   assert_eq!(right, &[]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<2>();
+    assert_eq!(left, [1, 2, 3, 4]);
+    assert_eq!(right, &[5, 6]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<6>();
+    assert_eq!(left, []);
+    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
+}
+
1.0.0

pub fn split<F>(&self, pred: F) -> Split<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is not contained in the subslices.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the first element is matched, an empty slice will be the first item +returned by the iterator. Similarly, if the last element in the slice +is matched, an empty slice will be the last item returned by the +iterator:

+ +
let slice = [10, 40, 33];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert!(iter.next().is_none());
+

If two matched elements are directly adjacent, an empty slice will be +present between them:

+ +
let slice = [10, 6, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+
1.51.0

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is contained in the end of the previous +subslice as a terminator.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the last element of the slice is matched, +that element will be considered the terminator of the preceding slice. +That slice will be the last item returned by the iterator.

+ +
let slice = [3, 10, 40, 33];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[3]);
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert!(iter.next().is_none());
+
1.27.0

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, starting at the end of the slice and working backwards. +The matched element is not contained in the subslices.

+
Examples
+
let slice = [11, 22, 33, 0, 44, 55];
+let mut iter = slice.rsplit(|num| *num == 0);
+
+assert_eq!(iter.next().unwrap(), &[44, 55]);
+assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
+assert_eq!(iter.next(), None);
+

As with split(), if the first or last element is matched, an empty +slice will be the first (or last) item returned by the iterator.

+ +
let v = &[0, 1, 1, 2, 3, 5, 8];
+let mut it = v.rsplit(|n| *n % 2 == 0);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next().unwrap(), &[3, 5]);
+assert_eq!(it.next().unwrap(), &[1, 1]);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next(), None);
+
1.0.0

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once by numbers divisible by 3 (i.e., [10, 40], +[20, 60, 50]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once, starting from the end, by numbers divisible +by 3 (i.e., [50], [10, 40, 30, 20]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.rsplitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn contains(&self, x: &T) -> boolwhere + T: PartialEq<T>,

Returns true if the slice contains an element with the given value.

+

This operation is O(n).

+

Note that if you have a sorted slice, binary_search may be faster.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.contains(&30));
+assert!(!v.contains(&50));
+

If you do not have a &T, but some other value that you can compare +with one (for example, String implements PartialEq<str>), you can +use iter().any:

+ +
let v = [String::from("hello"), String::from("world")]; // slice of `String`
+assert!(v.iter().any(|e| e == "hello")); // search with `&str`
+assert!(!v.iter().any(|e| e == "hi"));
+
1.0.0

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.starts_with(&[10]));
+assert!(v.starts_with(&[10, 40]));
+assert!(!v.starts_with(&[50]));
+assert!(!v.starts_with(&[10, 50]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.starts_with(&[]));
+let v: &[u8] = &[];
+assert!(v.starts_with(&[]));
+
1.0.0

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.ends_with(&[30]));
+assert!(v.ends_with(&[40, 30]));
+assert!(!v.ends_with(&[50]));
+assert!(!v.ends_with(&[50, 30]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.ends_with(&[]));
+let v: &[u8] = &[];
+assert!(v.ends_with(&[]));
+
1.51.0

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the prefix removed.

+

If the slice starts with prefix, returns the subslice after the prefix, wrapped in Some. +If prefix is empty, simply returns the original slice.

+

If the slice does not start with prefix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
+assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
+assert_eq!(v.strip_prefix(&[50]), None);
+assert_eq!(v.strip_prefix(&[10, 50]), None);
+
+let prefix : &str = "he";
+assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
+           Some(b"llo".as_ref()));
+
1.51.0

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the suffix removed.

+

If the slice ends with suffix, returns the subslice before the suffix, wrapped in Some. +If suffix is empty, simply returns the original slice.

+

If the slice does not end with suffix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
+assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
+assert_eq!(v.strip_suffix(&[50]), None);
+assert_eq!(v.strip_suffix(&[50, 30]), None);
+

Binary searches this slice for a given element. +If the slice is not sorted, the returned result is unspecified and +meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search_by, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+assert_eq!(s.binary_search(&13),  Ok(9));
+assert_eq!(s.binary_search(&4),   Err(7));
+assert_eq!(s.binary_search(&100), Err(13));
+let r = s.binary_search(&1);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+

If you want to find that whole range of matching items, rather than +an 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];
+
+let low = s.partition_point(|x| x < &1);
+assert_eq!(low, 1);
+let high = s.partition_point(|x| x <= &1);
+assert_eq!(high, 5);
+let r = s.binary_search(&1);
+assert!((low..high).contains(&r.unwrap()));
+
+assert!(s[..low].iter().all(|&x| x < 1));
+assert!(s[low..high].iter().all(|&x| x == 1));
+assert!(s[high..].iter().all(|&x| x > 1));
+
+// For something not found, the "range" of equal items is empty
+assert_eq!(s.partition_point(|x| x < &11), 9);
+assert_eq!(s.partition_point(|x| x <= &11), 9);
+assert_eq!(s.binary_search(&11), Err(9));
+

If you want to insert an item to a sorted vector, while maintaining +sort order, consider using partition_point:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+
1.0.0

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where + F: FnMut(&'a T) -> Ordering,

Binary searches this slice with a comparator function.

+

The comparator function should return an order code that indicates +whether its argument is Less, Equal or Greater the desired +target. +If the slice is not sorted or if the comparator function does not +implement an order consistent with the sort order of the underlying +slice, the returned result is unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+let seek = 13;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
+let seek = 4;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
+let seek = 100;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
+let seek = 1;
+let r = s.binary_search_by(|probe| probe.cmp(&seek));
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.10.0

pub fn binary_search_by_key<'a, B, F>( + &'a self, + b: &B, + f: F +) -> Result<usize, usize>where + F: FnMut(&'a T) -> B, + B: Ord,

Binary searches this slice with a key extraction function.

+

Assumes that the slice is sorted by the key, for instance with +sort_by_key using the same key extraction function. +If the slice is not sorted by the key, the returned result is +unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by, and partition_point.

+
Examples
+

Looks up a series of four elements in a slice of pairs sorted by +their second elements. The first is found, with a uniquely +determined position; the second and third are not found; the +fourth could match any position in [1, 4].

+ +
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
+         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
+         (1, 21), (2, 34), (4, 55)];
+
+assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
+assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
+assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
+let r = s.binary_search_by_key(&1, |&(a, b)| b);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.30.0

pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])

Transmute the slice to a slice of another type, ensuring alignment of the types is +maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])where + Simd<T, LANES>: AsRef<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

+

This is a safe wrapper around [slice::align_to], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+
Examples
+
#![feature(portable_simd)]
+use core::simd::SimdFloat;
+
+let short = &[1, 2, 3];
+let (prefix, middle, suffix) = short.as_simd::<4>();
+assert_eq!(middle, []); // Not enough elements for anything in the middle
+
+// They might be split in any possible way between prefix and suffix
+let it = prefix.iter().chain(suffix).copied();
+assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
+
+fn basic_simd_sum(x: &[f32]) -> f32 {
+    use std::ops::Add;
+    use std::simd::f32x4;
+    let (prefix, middle, suffix) = x.as_simd();
+    let sums = f32x4::from_array([
+        prefix.iter().copied().sum(),
+        0.0,
+        0.0,
+        suffix.iter().copied().sum(),
+    ]);
+    let sums = middle.iter().copied().fold(sums, f32x4::add);
+    sums.reduce_sum()
+}
+
+let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
+assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
+

pub fn is_sorted(&self) -> boolwhere + T: PartialOrd<T>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted.

+

That is, for each element a and its following element b, a <= b must hold. If the +slice yields exactly zero or one element, true is returned.

+

Note that if Self::Item is only PartialOrd, but not Ord, the above definition +implies that this function returns false if any two consecutive items are not +comparable.

+
Examples
+
#![feature(is_sorted)]
+let empty: [i32; 0] = [];
+
+assert!([1, 2, 2, 9].is_sorted());
+assert!(![1, 3, 2, 4].is_sorted());
+assert!([0].is_sorted());
+assert!(empty.is_sorted());
+assert!(![0.0, 1.0, f32::NAN].is_sorted());
+

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> boolwhere + F: FnMut(&'a T, &'a T) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given comparator function.

+

Instead of using PartialOrd::partial_cmp, this function uses the given compare +function to determine the ordering of two elements. Apart from that, it’s equivalent to +is_sorted; see its documentation for more information.

+

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> boolwhere + F: FnMut(&'a T) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given key extraction function.

+

Instead of comparing the slice’s elements directly, this function compares the keys of the +elements, as determined by f. Apart from that, it’s equivalent to is_sorted; see its +documentation for more information.

+
Examples
+
#![feature(is_sorted)]
+
+assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
+assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
+
1.52.0

pub fn partition_point<P>(&self, pred: P) -> usizewhere + P: FnMut(&T) -> bool,

Returns the index of the partition point according to the given predicate +(the index of the first element of the second partition).

+

The slice is assumed to be partitioned according to the given predicate. +This means that all elements for which the predicate returns true are at the start of the slice +and all elements for which the predicate returns false are at the end. +For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 +(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, +as this method performs a kind of binary search.

+

See also binary_search, binary_search_by, and binary_search_by_key.

+
Examples
+
let v = [1, 2, 3, 3, 5, 6, 7];
+let i = v.partition_point(|&x| x < 5);
+
+assert_eq!(i, 4);
+assert!(v[..i].iter().all(|&x| x < 5));
+assert!(v[i..].iter().all(|&x| !(x < 5)));
+

If all elements of the slice match the predicate, including if the slice +is empty, then the length of the slice will be returned:

+ +
let a = [2, 4, 8];
+assert_eq!(a.partition_point(|x| x < &100), a.len());
+let a: [i32; 0] = [];
+assert_eq!(a.partition_point(|x| x < &100), 0);
+

If you want to insert an item to a sorted vector, while maintaining +sort order:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+

Trait Implementations§

source§

impl<T, const N: usize> AsRef<[T]> for HistoryBuffer<T, N>

source§

fn as_ref(&self) -> &[T]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> Debug for HistoryBuffer<T, N>where + T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for HistoryBuffer<T, N>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Deref for HistoryBuffer<T, N>

§

type Target = [T]

The resulting type after dereferencing.
source§

fn deref(&self) -> &[T]

Dereferences the value.
source§

impl<T, const N: usize> Drop for HistoryBuffer<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> Extend<&'a T> for HistoryBuffer<T, N>where + T: 'a + Clone,

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> Extend<T> for HistoryBuffer<T, N>

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for HistoryBuffer<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for HistoryBuffer<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for HistoryBuffer<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for HistoryBuffer<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for HistoryBuffer<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.IndexMap.html b/docs/doc/heapless/struct.IndexMap.html new file mode 100644 index 0000000..ed6aa0f --- /dev/null +++ b/docs/doc/heapless/struct.IndexMap.html @@ -0,0 +1,306 @@ +IndexMap in heapless - Rust

Struct heapless::IndexMap

source ·
pub struct IndexMap<K, V, S, const N: usize> { /* private fields */ }
Expand description

Fixed capacity IndexMap

+

Note that you cannot use IndexMap directly, since it is generic around the hashing algorithm +in use. Pick a concrete instantiation like FnvIndexMap instead +or create your own.

+

Note that the capacity of the IndexMap must be a power of 2.

+

Examples

+

Since IndexMap cannot be used directly, we’re using its FnvIndexMap instantiation +for this example.

+ +
use heapless::FnvIndexMap;
+
+// A hash map with a capacity of 16 key-value pairs allocated on the stack
+let mut book_reviews = FnvIndexMap::<_, _, 16>::new();
+
+// review some books.
+book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.").unwrap();
+book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.").unwrap();
+book_reviews.insert("Pride and Prejudice",               "Very enjoyable.").unwrap();
+book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.").unwrap();
+
+// check for a specific one.
+if !book_reviews.contains_key("Les Misérables") {
+    println!("We've got {} reviews, but Les Misérables ain't one.",
+             book_reviews.len());
+}
+
+// oops, this review has a lot of spelling mistakes, let's delete it.
+book_reviews.remove("The Adventures of Sherlock Holmes");
+
+// look up the values associated with some keys.
+let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
+for book in &to_find {
+    match book_reviews.get(book) {
+        Some(review) => println!("{}: {}", book, review),
+        None => println!("{} is unreviewed.", book)
+    }
+}
+
+// iterate over everything.
+for (book, review) in &book_reviews {
+    println!("{}: \"{}\"", book, review);
+}
+

Implementations§

source§

impl<K, V, S, const N: usize> IndexMap<K, V, BuildHasherDefault<S>, N>

source

pub const fn new() -> Self

Creates an empty IndexMap.

+
source§

impl<K, V, S, const N: usize> IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold

+
source

pub fn keys(&self) -> impl Iterator<Item = &K>

Return an iterator over the keys of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for key in map.keys() {
+    println!("{}", key);
+}
+
source

pub fn values(&self) -> impl Iterator<Item = &V>

Return an iterator over the values of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V>

Return an iterator over mutable references to the the values of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values_mut() {
+    *val += 10;
+}
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn iter(&self) -> Iter<'_, K, V>

Return an iterator over the key-value pairs of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (key, val) in map.iter() {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

Return an iterator over the key-value pairs of the map, in their order

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (_, val) in map.iter_mut() {
+    *val = 2;
+}
+
+for (key, val) in &map {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn first(&self) -> Option<(&K, &V)>

Get the first key-value pair

+

Computes in O(1) time

+
source

pub fn first_mut(&mut self) -> Option<(&K, &mut V)>

Get the first key-value pair, with mutable access to the value

+

Computes in O(1) time

+
source

pub fn last(&self) -> Option<(&K, &V)>

Get the last key-value pair

+

Computes in O(1) time

+
source

pub fn last_mut(&mut self) -> Option<(&K, &mut V)>

Get the last key-value pair, with mutable access to the value

+

Computes in O(1) time

+
source

pub fn entry(&mut self, key: K) -> Entry<'_, K, V, N>

Returns an entry for the corresponding key

+ +
use heapless::FnvIndexMap;
+use heapless::Entry;
+let mut map = FnvIndexMap::<_, _, 16>::new();
+if let Entry::Vacant(v) = map.entry("a") {
+    v.insert(1).unwrap();
+}
+if let Entry::Occupied(mut o) = map.entry("a") {
+    println!("found {}", *o.get()); // Prints 1
+    o.insert(2);
+}
+// Prints 2
+println!("val: {}", *map.get("a").unwrap());
+
source

pub fn len(&self) -> usize

Return the number of key-value pairs in the map.

+

Computes in O(1) time.

+ +
use heapless::FnvIndexMap;
+
+let mut a = FnvIndexMap::<_, _, 16>::new();
+assert_eq!(a.len(), 0);
+a.insert(1, "a").unwrap();
+assert_eq!(a.len(), 1);
+
source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

+

Computes in O(1) time.

+ +
use heapless::FnvIndexMap;
+
+let mut a = FnvIndexMap::<_, _, 16>::new();
+assert!(a.is_empty());
+a.insert(1, "a");
+assert!(!a.is_empty());
+
source

pub fn clear(&mut self)

Remove all key-value pairs in the map, while preserving its capacity.

+

Computes in O(n) time.

+ +
use heapless::FnvIndexMap;
+
+let mut a = FnvIndexMap::<_, _, 16>::new();
+a.insert(1, "a");
+a.clear();
+assert!(a.is_empty());
+
source

pub fn get<Q>(&self, key: &Q) -> Option<&V>where + K: Borrow<Q>, + Q: ?Sized + Hash + Eq,

Returns a reference to the value corresponding to the key.

+

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed +form must match those for the key type.

+

Computes in O(1) time (average).

+ +
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 16>::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.get(&1), Some(&"a"));
+assert_eq!(map.get(&2), None);
+
source

pub fn contains_key<Q>(&self, key: &Q) -> boolwhere + K: Borrow<Q>, + Q: ?Sized + Eq + Hash,

Returns true if the map contains a value for the specified key.

+

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed +form must match those for the key type.

+

Computes in O(1) time (average).

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.contains_key(&1), true);
+assert_eq!(map.contains_key(&2), false);
+
source

pub fn get_mut<'v, Q>(&'v mut self, key: &Q) -> Option<&'v mut V>where + K: Borrow<Q>, + Q: ?Sized + Hash + Eq,

Returns a mutable reference to the value corresponding to the key.

+

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed +form must match those for the key type.

+

Computes in O(1) time (average).

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+map.insert(1, "a").unwrap();
+if let Some(x) = map.get_mut(&1) {
+    *x = "b";
+}
+assert_eq!(map[&1], "b");
+
source

pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)>

Inserts a key-value pair into the map.

+

If an equivalent key already exists in the map: the key remains and retains in its place in +the order, its corresponding value is updated with value and the older value is returned +inside Some(_).

+

If no equivalent key existed in the map: the new key-value pair is inserted, last in order, +and None is returned.

+

Computes in O(1) time (average).

+

See also entry if you you want to insert or modify or if you need to get the index of the +corresponding key-value pair.

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+assert_eq!(map.insert(37, "a"), Ok(None));
+assert_eq!(map.is_empty(), false);
+
+map.insert(37, "b");
+assert_eq!(map.insert(37, "c"), Ok(Some("b")));
+assert_eq!(map[&37], "c");
+
source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: ?Sized + Hash + Eq,

Same as swap_remove

+

Computes in O(1) time (average).

+
Examples
+
use heapless::FnvIndexMap;
+
+let mut map = FnvIndexMap::<_, _, 8>::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.remove(&1), Some("a"));
+assert_eq!(map.remove(&1), None);
+
source

pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: ?Sized + Hash + Eq,

Remove the key-value pair equivalent to key and return its value.

+

Like Vec::swap_remove, the pair is removed by swapping it with the last element of the map +and popping it off. This perturbs the postion of what used to be the last element!

+

Return None if key is not in map.

+

Computes in O(1) time (average).

+

Trait Implementations§

source§

impl<K, V, S, const N: usize> Clone for IndexMap<K, V, S, N>where + K: Eq + Hash + Clone, + V: Clone, + S: Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K, V, S, const N: usize> Debug for IndexMap<K, V, S, N>where + K: Eq + Hash + Debug, + V: Debug, + S: BuildHasher,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<K, V, S, const N: usize> Default for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher + Default,

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'a, K, V, S, const N: usize> Extend<(&'a K, &'a V)> for IndexMap<K, V, S, N>where + K: Eq + Hash + Copy, + V: Copy, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = (&'a K, &'a V)>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<K, V, S, const N: usize> Extend<(K, V)> for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = (K, V)>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<K, V, S, const N: usize> FromIterator<(K, V)> for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher + Default,

source§

fn from_iter<I>(iterable: I) -> Selfwhere + I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl<'a, K, Q, V, S, const N: usize> Index<&'a Q> for IndexMap<K, V, S, N>where + K: Eq + Hash + Borrow<Q>, + Q: ?Sized + Eq + Hash, + S: BuildHasher,

§

type Output = V

The returned type after indexing.
source§

fn index(&self, key: &Q) -> &V

Performs the indexing (container[index]) operation. Read more
source§

impl<'a, K, Q, V, S, const N: usize> IndexMut<&'a Q> for IndexMap<K, V, S, N>where + K: Eq + Hash + Borrow<Q>, + Q: ?Sized + Eq + Hash, + S: BuildHasher,

source§

fn index_mut(&mut self, key: &Q) -> &mut V

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, K, V, S, const N: usize> IntoIterator for &'a IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, K, V, S, const N: usize> IntoIterator for &'a mut IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

§

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, S, const N: usize> IntoIterator for IndexMap<K, V, S, N>where + K: Eq + Hash, + S: BuildHasher,

§

type Item = (K, V)

The type of the elements being iterated over.
§

type IntoIter = IntoIter<K, V, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, S, S2, const N: usize, const N2: usize> PartialEq<IndexMap<K, V, S2, N2>> for IndexMap<K, V, S, N>where + K: Eq + Hash, + V: Eq, + S: BuildHasher, + S2: BuildHasher,

source§

fn eq(&self, other: &IndexMap<K, V, S2, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<K, V, S, const N: usize> Eq for IndexMap<K, V, S, N>where + K: Eq + Hash, + V: Eq, + S: BuildHasher,

Auto Trait Implementations§

§

impl<K, V, S, const N: usize> RefUnwindSafe for IndexMap<K, V, S, N>where + K: RefUnwindSafe, + S: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<K, V, S, const N: usize> Send for IndexMap<K, V, S, N>where + K: Send, + S: Send, + V: Send,

§

impl<K, V, S, const N: usize> Sync for IndexMap<K, V, S, N>where + K: Sync, + S: Sync, + V: Sync,

§

impl<K, V, S, const N: usize> Unpin for IndexMap<K, V, S, N>where + K: Unpin, + S: Unpin, + V: Unpin,

§

impl<K, V, S, const N: usize> UnwindSafe for IndexMap<K, V, S, N>where + K: UnwindSafe, + S: UnwindSafe, + V: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.IndexSet.html b/docs/doc/heapless/struct.IndexSet.html new file mode 100644 index 0000000..e36c5ae --- /dev/null +++ b/docs/doc/heapless/struct.IndexSet.html @@ -0,0 +1,296 @@ +IndexSet in heapless - Rust

Struct heapless::IndexSet

source ·
pub struct IndexSet<T, S, const N: usize> { /* private fields */ }
Expand description

Fixed capacity IndexSet.

+

Note that you cannot use IndexSet directly, since it is generic around the hashing algorithm +in use. Pick a concrete instantiation like FnvIndexSet instead +or create your own.

+

Note that the capacity of the IndexSet must be a power of 2.

+

Examples

+

Since IndexSet cannot be used directly, we’re using its FnvIndexSet instantiation +for this example.

+ +
use heapless::FnvIndexSet;
+
+// A hash set with a capacity of 16 elements allocated on the stack
+let mut books = FnvIndexSet::<_, 16>::new();
+
+// Add some books.
+books.insert("A Dance With Dragons").unwrap();
+books.insert("To Kill a Mockingbird").unwrap();
+books.insert("The Odyssey").unwrap();
+books.insert("The Great Gatsby").unwrap();
+
+// Check for a specific one.
+if !books.contains("The Winds of Winter") {
+    println!("We have {} books, but The Winds of Winter ain't one.",
+             books.len());
+}
+
+// Remove a book.
+books.remove("The Odyssey");
+
+// Iterate over everything.
+for book in &books {
+    println!("{}", book);
+}
+

Implementations§

source§

impl<T, S, const N: usize> IndexSet<T, BuildHasherDefault<S>, N>

source

pub const fn new() -> Self

Creates an empty IndexSet

+
source§

impl<T, S, const N: usize> IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher,

source

pub fn capacity(&self) -> usize

Returns the number of elements the set can hold

+
Examples
+
use heapless::FnvIndexSet;
+
+let set = FnvIndexSet::<i32, 16>::new();
+assert_eq!(set.capacity(), 16);
+
source

pub fn iter(&self) -> Iter<'_, T>

Return an iterator over the values of the set, in their order

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut set = FnvIndexSet::<_, 16>::new();
+set.insert("a").unwrap();
+set.insert("b").unwrap();
+
+// Will print in an arbitrary order.
+for x in set.iter() {
+    println!("{}", x);
+}
+
source

pub fn first(&self) -> Option<&T>

Get the first value

+

Computes in O(1) time

+
source

pub fn last(&self) -> Option<&T>

Get the last value

+

Computes in O(1) time

+
source

pub fn difference<'a, S2, const N2: usize>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> Difference<'a, T, S2, N2>where + S2: BuildHasher,

Visits the values representing the difference, i.e. the values that are in self but not in +other.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Can be seen as `a - b`.
+for x in a.difference(&b) {
+    println!("{}", x); // Print 1
+}
+
+let diff: FnvIndexSet<_, 16> = a.difference(&b).collect();
+assert_eq!(diff, [1].iter().collect::<FnvIndexSet<_, 16>>());
+
+// Note that difference is not symmetric,
+// and `b - a` means something else:
+let diff: FnvIndexSet<_, 16> = b.difference(&a).collect();
+assert_eq!(diff, [4].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn symmetric_difference<'a, S2, const N2: usize>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> impl Iterator<Item = &'a T>where + S2: BuildHasher,

Visits the values representing the symmetric difference, i.e. the values that are in self +or in other but not in both.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Print 1, 4 in that order order.
+for x in a.symmetric_difference(&b) {
+    println!("{}", x);
+}
+
+let diff1: FnvIndexSet<_, 16> = a.symmetric_difference(&b).collect();
+let diff2: FnvIndexSet<_, 16> = b.symmetric_difference(&a).collect();
+
+assert_eq!(diff1, diff2);
+assert_eq!(diff1, [1, 4].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn intersection<'a, S2, const N2: usize>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> Intersection<'a, T, S2, N2>where + S2: BuildHasher,

Visits the values representing the intersection, i.e. the values that are both in self and +other.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Print 2, 3 in that order.
+for x in a.intersection(&b) {
+    println!("{}", x);
+}
+
+let intersection: FnvIndexSet<_, 16> = a.intersection(&b).collect();
+assert_eq!(intersection, [2, 3].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn union<'a, S2, const N2: usize>( + &'a self, + other: &'a IndexSet<T, S2, N2> +) -> impl Iterator<Item = &'a T>where + S2: BuildHasher,

Visits the values representing the union, i.e. all the values in self or other, without +duplicates.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+
+// Print 1, 2, 3, 4 in that order.
+for x in a.union(&b) {
+    println!("{}", x);
+}
+
+let union: FnvIndexSet<_, 16> = a.union(&b).collect();
+assert_eq!(union, [1, 2, 3, 4].iter().collect::<FnvIndexSet<_, 16>>());
+
source

pub fn len(&self) -> usize

Returns the number of elements in the set.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+assert_eq!(v.len(), 0);
+v.insert(1).unwrap();
+assert_eq!(v.len(), 1);
+
source

pub fn is_empty(&self) -> bool

Returns true if the set contains no elements.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+assert!(v.is_empty());
+v.insert(1).unwrap();
+assert!(!v.is_empty());
+
source

pub fn clear(&mut self)

Clears the set, removing all values.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+v.insert(1).unwrap();
+v.clear();
+assert!(v.is_empty());
+
source

pub fn contains<Q>(&self, value: &Q) -> boolwhere + T: Borrow<Q>, + Q: ?Sized + Eq + Hash,

Returns true if the set contains a value.

+

The value may be any borrowed form of the set’s value type, but Hash and Eq on the +borrowed form must match those for the value type.

+
Examples
+
use heapless::FnvIndexSet;
+
+let set: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+assert_eq!(set.contains(&1), true);
+assert_eq!(set.contains(&4), false);
+
source

pub fn is_disjoint<S2, const N2: usize>( + &self, + other: &IndexSet<T, S2, N2> +) -> boolwhere + S2: BuildHasher,

Returns true if self has no elements in common with other. This is equivalent to +checking for an empty intersection.

+
Examples
+
use heapless::FnvIndexSet;
+
+let a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut b = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(a.is_disjoint(&b), true);
+b.insert(4).unwrap();
+assert_eq!(a.is_disjoint(&b), true);
+b.insert(1).unwrap();
+assert_eq!(a.is_disjoint(&b), false);
+
source

pub fn is_subset<S2, const N2: usize>( + &self, + other: &IndexSet<T, S2, N2> +) -> boolwhere + S2: BuildHasher,

Returns true if the set is a subset of another, i.e. other contains at least all the +values in self.

+
Examples
+
use heapless::FnvIndexSet;
+
+let sup: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+let mut set = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(set.is_subset(&sup), true);
+set.insert(2).unwrap();
+assert_eq!(set.is_subset(&sup), true);
+set.insert(4).unwrap();
+assert_eq!(set.is_subset(&sup), false);
+
source

pub fn is_superset<S2, const N2: usize>( + &self, + other: &IndexSet<T, S2, N2> +) -> boolwhere + S2: BuildHasher,

Examples
+
use heapless::FnvIndexSet;
+
+let sub: FnvIndexSet<_, 16> = [1, 2].iter().cloned().collect();
+let mut set = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(set.is_superset(&sub), false);
+
+set.insert(0).unwrap();
+set.insert(1).unwrap();
+assert_eq!(set.is_superset(&sub), false);
+
+set.insert(2).unwrap();
+assert_eq!(set.is_superset(&sub), true);
+
source

pub fn insert(&mut self, value: T) -> Result<bool, T>

Adds a value to the set.

+

If the set did not have this value present, true is returned.

+

If the set did have this value present, false is returned.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut set = FnvIndexSet::<_, 16>::new();
+
+assert_eq!(set.insert(2).unwrap(), true);
+assert_eq!(set.insert(2).unwrap(), false);
+assert_eq!(set.len(), 1);
+
source

pub fn remove<Q>(&mut self, value: &Q) -> boolwhere + T: Borrow<Q>, + Q: ?Sized + Eq + Hash,

Removes a value from the set. Returns true if the value was present in the set.

+

The value may be any borrowed form of the set’s value type, but Hash and Eq on the +borrowed form must match those for the value type.

+
Examples
+
use heapless::FnvIndexSet;
+
+let mut set = FnvIndexSet::<_, 16>::new();
+
+set.insert(2).unwrap();
+assert_eq!(set.remove(&2), true);
+assert_eq!(set.remove(&2), false);
+

Trait Implementations§

source§

impl<T, S, const N: usize> Clone for IndexSet<T, S, N>where + T: Eq + Hash + Clone, + S: Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, S, const N: usize> Debug for IndexSet<T, S, N>where + T: Eq + Hash + Debug, + S: BuildHasher,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, S, const N: usize> Default for IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher + Default,

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<'a, T, S, const N: usize> Extend<&'a T> for IndexSet<T, S, N>where + T: 'a + Eq + Hash + Copy, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, S, const N: usize> Extend<T> for IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher,

source§

fn extend<I>(&mut self, iterable: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, S, const N: usize> FromIterator<T> for IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher + Default,

source§

fn from_iter<I>(iter: I) -> Selfwhere + I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
source§

impl<'a, T, S, const N: usize> IntoIterator for &'a IndexSet<T, S, N>where + T: Eq + Hash, + S: BuildHasher,

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, S1, S2, const N1: usize, const N2: usize> PartialEq<IndexSet<T, S2, N2>> for IndexSet<T, S1, N1>where + T: Eq + Hash, + S1: BuildHasher, + S2: BuildHasher,

source§

fn eq(&self, other: &IndexSet<T, S2, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl<T, S, const N: usize> RefUnwindSafe for IndexSet<T, S, N>where + S: RefUnwindSafe, + T: RefUnwindSafe,

§

impl<T, S, const N: usize> Send for IndexSet<T, S, N>where + S: Send, + T: Send,

§

impl<T, S, const N: usize> Sync for IndexSet<T, S, N>where + S: Sync, + T: Sync,

§

impl<T, S, const N: usize> Unpin for IndexSet<T, S, N>where + S: Unpin, + T: Unpin,

§

impl<T, S, const N: usize> UnwindSafe for IndexSet<T, S, N>where + S: UnwindSafe, + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.LinearMap.html b/docs/doc/heapless/struct.LinearMap.html new file mode 100644 index 0000000..4e5f589 --- /dev/null +++ b/docs/doc/heapless/struct.LinearMap.html @@ -0,0 +1,214 @@ +LinearMap in heapless - Rust

Struct heapless::LinearMap

source ·
pub struct LinearMap<K, V, const N: usize> { /* private fields */ }
Expand description

A fixed capacity map / dictionary that performs lookups via linear search

+

Note that as this map doesn’t use hashing so most operations are O(N) instead of O(1)

+

Implementations§

source§

impl<K, V, const N: usize> LinearMap<K, V, N>

source

pub const fn new() -> Self

Creates an empty LinearMap

+
Examples
+
use heapless::LinearMap;
+
+// allocate the map on the stack
+let mut map: LinearMap<&str, isize, 8> = LinearMap::new();
+
+// allocate the map in a static variable
+static mut MAP: LinearMap<&str, isize, 8> = LinearMap::new();
+
source§

impl<K, V, const N: usize> LinearMap<K, V, N>where + K: Eq,

source

pub fn capacity(&self) -> usize

Returns the number of elements that the map can hold

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let map: LinearMap<&str, isize, 8> = LinearMap::new();
+assert_eq!(map.capacity(), 8);
+
source

pub fn clear(&mut self)

Clears the map, removing all key-value pairs

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+map.clear();
+assert!(map.is_empty());
+
source

pub fn contains_key(&self, key: &K) -> bool

Returns true if the map contains a value for the specified key.

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.contains_key(&1), true);
+assert_eq!(map.contains_key(&2), false);
+
source

pub fn get<Q>(&self, key: &Q) -> Option<&V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Returns a reference to the value corresponding to the key

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.get(&1), Some(&"a"));
+assert_eq!(map.get(&2), None);
+
source

pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Returns a mutable reference to the value corresponding to the key

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+if let Some(x) = map.get_mut(&1) {
+    *x = "b";
+}
+assert_eq!(map[&1], "b");
+
source

pub fn len(&self) -> usize

Returns the number of elements in this map

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut a: LinearMap<_, _, 8> = LinearMap::new();
+assert_eq!(a.len(), 0);
+a.insert(1, "a").unwrap();
+assert_eq!(a.len(), 1);
+
source

pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)>

Inserts a key-value pair into the map.

+

If the map did not have this key present, None is returned.

+

If the map did have this key present, the value is updated, and the old value is returned.

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+assert_eq!(map.insert(37, "a").unwrap(), None);
+assert_eq!(map.is_empty(), false);
+
+map.insert(37, "b").unwrap();
+assert_eq!(map.insert(37, "c").unwrap(), Some("b"));
+assert_eq!(map[&37], "c");
+
source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements

+

Computes in O(1) time

+
Examples
+
use heapless::LinearMap;
+
+let mut a: LinearMap<_, _, 8> = LinearMap::new();
+assert!(a.is_empty());
+a.insert(1, "a").unwrap();
+assert!(!a.is_empty());
+
source

pub fn iter(&self) -> Iter<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order.

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for (key, val) in map.iter() {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the +values

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+// Update all values
+for (_, val) in map.iter_mut() {
+    *val = 2;
+}
+
+for (key, val) in &map {
+    println!("key: {} val: {}", key, val);
+}
+
source

pub fn keys(&self) -> impl Iterator<Item = &K>

An iterator visiting all keys in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for key in map.keys() {
+    println!("{}", key);
+}
+
source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>where + K: Borrow<Q>, + Q: Eq + ?Sized,

Removes a key from the map, returning the value at the key if the key was previously in the +map

+

Computes in O(N) time

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert(1, "a").unwrap();
+assert_eq!(map.remove(&1), Some("a"));
+assert_eq!(map.remove(&1), None);
+
source

pub fn values(&self) -> impl Iterator<Item = &V>

An iterator visiting all values in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values() {
+    println!("{}", val);
+}
+
source

pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V>

An iterator visiting all values mutably in arbitrary order

+
Examples
+
use heapless::LinearMap;
+
+let mut map: LinearMap<_, _, 8> = LinearMap::new();
+map.insert("a", 1).unwrap();
+map.insert("b", 2).unwrap();
+map.insert("c", 3).unwrap();
+
+for val in map.values_mut() {
+    *val += 10;
+}
+
+for val in map.values() {
+    println!("{}", val);
+}
+

Trait Implementations§

source§

impl<K, V, const N: usize> Clone for LinearMap<K, V, N>where + K: Eq + Clone, + V: Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K, V, const N: usize> Debug for LinearMap<K, V, N>where + K: Eq + Debug, + V: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<K, V, const N: usize> Default for LinearMap<K, V, N>where + K: Eq,

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<K, V, const N: usize> Drop for LinearMap<K, V, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<K, V, const N: usize> FromIterator<(K, V)> for LinearMap<K, V, N>where + K: Eq,

source§

fn from_iter<I>(iter: I) -> Selfwhere + I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl<'a, K, V, Q, const N: usize> Index<&'a Q> for LinearMap<K, V, N>where + K: Borrow<Q> + Eq, + Q: Eq + ?Sized,

§

type Output = V

The returned type after indexing.
source§

fn index(&self, key: &Q) -> &V

Performs the indexing (container[index]) operation. Read more
source§

impl<'a, K, V, Q, const N: usize> IndexMut<&'a Q> for LinearMap<K, V, N>where + K: Borrow<Q> + Eq, + Q: Eq + ?Sized,

source§

fn index_mut(&mut self, key: &Q) -> &mut V

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, K, V, const N: usize> IntoIterator for &'a LinearMap<K, V, N>where + K: Eq,

§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<K, V, const N: usize, const N2: usize> PartialEq<LinearMap<K, V, N2>> for LinearMap<K, V, N>where + K: Eq, + V: PartialEq,

source§

fn eq(&self, other: &LinearMap<K, V, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<K, V, const N: usize> Eq for LinearMap<K, V, N>where + K: Eq, + V: PartialEq,

Auto Trait Implementations§

§

impl<K, V, const N: usize> RefUnwindSafe for LinearMap<K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<K, V, const N: usize> Send for LinearMap<K, V, N>where + K: Send, + V: Send,

§

impl<K, V, const N: usize> Sync for LinearMap<K, V, N>where + K: Sync, + V: Sync,

§

impl<K, V, const N: usize> Unpin for LinearMap<K, V, N>where + K: Unpin, + V: Unpin,

§

impl<K, V, const N: usize> UnwindSafe for LinearMap<K, V, N>where + K: UnwindSafe, + V: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.OccupiedEntry.html b/docs/doc/heapless/struct.OccupiedEntry.html new file mode 100644 index 0000000..52c1a38 --- /dev/null +++ b/docs/doc/heapless/struct.OccupiedEntry.html @@ -0,0 +1,27 @@ +OccupiedEntry in heapless - Rust

Struct heapless::OccupiedEntry

source ·
pub struct OccupiedEntry<'a, K, V, const N: usize> { /* private fields */ }
Expand description

An occupied entry which can be manipulated

+

Implementations§

source§

impl<'a, K, V, const N: usize> OccupiedEntry<'a, K, V, N>where + K: Eq + Hash,

source

pub fn key(&self) -> &K

Gets a reference to the key that this entity corresponds to

+
source

pub fn remove_entry(self) -> (K, V)

Removes this entry from the map and yields its corresponding key and value

+
source

pub fn get(&self) -> &V

Gets a reference to the value associated with this entry

+
source

pub fn get_mut(&mut self) -> &mut V

Gets a mutable reference to the value associated with this entry

+
source

pub fn into_mut(self) -> &'a mut V

Consumes this entry and yields a reference to the underlying value

+
source

pub fn insert(self, value: V) -> V

Overwrites the underlying map’s value with this entry’s value

+
source

pub fn remove(self) -> V

Removes this entry from the map and yields its value

+

Auto Trait Implementations§

§

impl<'a, K, V, const N: usize> RefUnwindSafe for OccupiedEntry<'a, K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<'a, K, V, const N: usize> Send for OccupiedEntry<'a, K, V, N>where + K: Send, + V: Send,

§

impl<'a, K, V, const N: usize> Sync for OccupiedEntry<'a, K, V, N>where + K: Sync, + V: Sync,

§

impl<'a, K, V, const N: usize> Unpin for OccupiedEntry<'a, K, V, N>where + K: Unpin,

§

impl<'a, K, V, const N: usize> !UnwindSafe for OccupiedEntry<'a, K, V, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.OldestOrdered.html b/docs/doc/heapless/struct.OldestOrdered.html new file mode 100644 index 0000000..ef0f03a --- /dev/null +++ b/docs/doc/heapless/struct.OldestOrdered.html @@ -0,0 +1,190 @@ +OldestOrdered in heapless - Rust

Struct heapless::OldestOrdered

source ·
pub struct OldestOrdered<'a, T, const N: usize> { /* private fields */ }
Expand description

An iterator on the underlying buffer ordered from oldest data to newest

+

Trait Implementations§

source§

impl<'a, T: Clone, const N: usize> Clone for OldestOrdered<'a, T, N>

source§

fn clone(&self) -> OldestOrdered<'a, T, N>

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a, T, const N: usize> Iterator for OldestOrdered<'a, T, N>

§

type Item = &'a T

The type of the elements being iterated over.
source§

fn next(&mut self) -> Option<&'a T>

Advances the iterator and returns the next value. Read more
§

fn next_chunk<const N: usize>( + &mut self +) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.0.0§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
1.0.0§

fn count(self) -> usizewhere + Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
1.0.0§

fn last(self) -> Option<Self::Item>where + Self: Sized,

Consumes the iterator, returning the last element. Read more
§

fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.0.0§

fn nth(&mut self, n: usize) -> Option<Self::Item>

Returns the nth element of the iterator. Read more
1.28.0§

fn step_by(self, step: usize) -> StepBy<Self>where + Self: Sized,

Creates an iterator starting at the same point, but stepping by +the given amount at each iteration. Read more
1.0.0§

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.0.0§

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where + Self: Sized, + U: IntoIterator,

‘Zips up’ two iterators into a single iterator of pairs. Read more
§

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>where + Self: Sized, + G: FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator +between adjacent items of the original iterator. Read more
1.0.0§

fn map<B, F>(self, f: F) -> Map<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each +element. Read more
1.21.0§

fn for_each<F>(self, f: F)where + Self: Sized, + F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.0.0§

fn filter<P>(self, predicate: P) -> Filter<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element +should be yielded. Read more
1.0.0§

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.0.0§

fn enumerate(self) -> Enumerate<Self>where + Self: Sized,

Creates an iterator which gives the current iteration count as well as +the next value. Read more
1.0.0§

fn peekable(self) -> Peekable<Self>where + Self: Sized,

Creates an iterator which can use the peek and peek_mut methods +to look at the next element of the iterator without consuming it. See +their documentation for more information. Read more
1.0.0§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.0.0§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where + Self: Sized, + P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.0.0§

fn skip(self, n: usize) -> Skip<Self>where + Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.0.0§

fn take(self, n: usize) -> Take<Self>where + Self: Sized,

Creates an iterator that yields the first n elements, or fewer +if the underlying iterator ends sooner. Read more
1.0.0§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where + Self: Sized, + F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but +unlike fold, produces a new iterator. Read more
1.0.0§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where + Self: Sized, + U: IntoIterator, + F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
1.0.0§

fn fuse(self) -> Fuse<Self>where + Self: Sized,

Creates an iterator which ends after the first [None]. Read more
1.0.0§

fn inspect<F>(self, f: F) -> Inspect<Self, F>where + Self: Sized, + F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.0.0§

fn by_ref(&mut self) -> &mut Selfwhere + Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.0.0§

fn collect<B>(self) -> Bwhere + B: FromIterator<Self::Item>, + Self: Sized,

Transforms an iterator into a collection. Read more
§

fn collect_into<E>(self, collection: &mut E) -> &mut Ewhere + E: Extend<Self::Item>, + Self: Sized,

🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.0.0§

fn partition<B, F>(self, f: F) -> (B, B)where + Self: Sized, + B: Default + Extend<Self::Item>, + F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
§

fn is_partitioned<P>(self, predicate: P) -> boolwhere + Self: Sized, + P: FnMut(Self::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate, +such that all those that return true precede all those that return false. Read more
1.27.0§

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try<Output = B>,

An iterator method that applies a function as long as it returns +successfully, producing a single, final value. Read more
1.27.0§

fn try_for_each<F, R>(&mut self, f: F) -> Rwhere + Self: Sized, + F: FnMut(Self::Item) -> R, + R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the +iterator, stopping at the first error and returning that error. Read more
1.0.0§

fn fold<B, F>(self, init: B, f: F) -> Bwhere + Self: Sized, + F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation, +returning the final result. Read more
1.51.0§

fn reduce<F>(self, f: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing +operation. Read more
§

fn try_reduce<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere + Self: Sized, + F: FnMut(Self::Item, Self::Item) -> R, + R: Try<Output = Self::Item>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the +closure returns a failure, the failure is propagated back to the caller immediately. Read more
1.0.0§

fn all<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.0.0§

fn any<F>(&mut self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.0.0§

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where + Self: Sized, + P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0§

fn find_map<B, F>(&mut self, f: F) -> Option<B>where + Self: Sized, + F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns +the first non-none result. Read more
§

fn try_find<F, R>( + &mut self, + f: F +) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere + Self: Sized, + F: FnMut(&Self::Item) -> R, + R: Try<Output = bool>, + <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns +the first true result or the first error. Read more
1.0.0§

fn position<P>(&mut self, predicate: P) -> Option<usize>where + Self: Sized, + P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0§

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the +specified function. Read more
1.15.0§

fn max_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the +specified comparison function. Read more
1.6.0§

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where + B: Ord, + Self: Sized, + F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the +specified function. Read more
1.15.0§

fn min_by<F>(self, compare: F) -> Option<Self::Item>where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the +specified comparison function. Read more
1.0.0§

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where + FromA: Default + Extend<A>, + FromB: Default + Extend<B>, + Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0§

fn copied<'a, T>(self) -> Copied<Self>where + T: 'a + Copy, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.0.0§

fn cloned<'a, T>(self) -> Cloned<Self>where + T: 'a + Clone, + Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
§

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>where + Self: Sized,

🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0§

fn sum<S>(self) -> Swhere + Self: Sized, + S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0§

fn product<P>(self) -> Pwhere + Self: Sized, + P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
§

fn cmp_by<I, F>(self, other: I, cmp: F) -> Orderingwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn partial_cmp<I>(self, other: I) -> Option<Ordering>where + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Lexicographically compares the [PartialOrd] elements of +this [Iterator] with those of another. The comparison works like short-circuit +evaluation, returning a result without comparing the remaining elements. +As soon as an order can be determined, the evaluation stops and a result is returned. Read more
§

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this [Iterator] with those +of another with respect to the specified comparison function. Read more
1.5.0§

fn eq<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are equal to those of +another. Read more
§

fn eq_by<I, F>(self, other: I, eq: F) -> boolwhere + Self: Sized, + I: IntoIterator, + F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this [Iterator] are equal to those of +another with respect to the specified equality function. Read more
1.5.0§

fn ne<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialEq<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are not equal to those of +another. Read more
1.5.0§

fn lt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less than those of another. Read more
1.5.0§

fn le<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +less or equal to those of another. Read more
1.5.0§

fn gt<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than those of another. Read more
1.5.0§

fn ge<I>(self, other: I) -> boolwhere + I: IntoIterator, + Self::Item: PartialOrd<<I as IntoIterator>::Item>, + Self: Sized,

Determines if the elements of this [Iterator] are lexicographically +greater than or equal to those of another. Read more
§

fn is_sorted_by<F>(self, compare: F) -> boolwhere + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
§

fn is_sorted_by_key<F, K>(self, f: F) -> boolwhere + Self: Sized, + F: FnMut(Self::Item) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction +function. Read more

Auto Trait Implementations§

§

impl<'a, T, const N: usize> RefUnwindSafe for OldestOrdered<'a, T, N>where + T: RefUnwindSafe,

§

impl<'a, T, const N: usize> Send for OldestOrdered<'a, T, N>where + T: Sync,

§

impl<'a, T, const N: usize> Sync for OldestOrdered<'a, T, N>where + T: Sync,

§

impl<'a, T, const N: usize> Unpin for OldestOrdered<'a, T, N>

§

impl<'a, T, const N: usize> UnwindSafe for OldestOrdered<'a, T, N>where + T: RefUnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<I> IntoIterator for Iwhere + I: Iterator,

§

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
§

type IntoIter = I

Which kind of iterator are we turning this into?
const: unstable§

fn into_iter(self) -> I

Creates an iterator from a value. Read more
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.String.html b/docs/doc/heapless/struct.String.html new file mode 100644 index 0000000..cfaf9a3 --- /dev/null +++ b/docs/doc/heapless/struct.String.html @@ -0,0 +1,1368 @@ +String in heapless - Rust

Struct heapless::String

source ·
pub struct String<const N: usize> { /* private fields */ }
Expand description

A fixed capacity String

+

Implementations§

source§

impl<const N: usize> String<N>

source

pub const fn new() -> Self

Constructs a new, empty String with a fixed capacity of N bytes

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+// allocate the string on the stack
+let mut s: String<4> = String::new();
+
+// allocate the string in a static variable
+static mut S: String<4> = String::new();
+
source

pub fn into_bytes(self) -> Vec<u8, N>

Converts a String into a byte vector.

+

This consumes the String, so we do not need to copy its contents.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let s: String<4> = String::from("ab");
+let b = s.into_bytes();
+assert!(b.len() == 2);
+
+assert_eq!(&['a' as u8, 'b' as u8], &b[..]);
+
source

pub fn as_str(&self) -> &str

Extracts a string slice containing the entire string.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::from("ab");
+assert!(s.as_str() == "ab");
+
+let _s = s.as_str();
+// s.push('c'); // <- cannot borrow `s` as mutable because it is also borrowed as immutable
+
source

pub fn as_mut_str(&mut self) -> &mut str

Converts a String into a mutable string slice.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::from("ab");
+let s = s.as_mut_str();
+s.make_ascii_uppercase();
+
source

pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, N>

Returns a mutable reference to the contents of this String.

+
Safety
+

This function is unsafe because it does not check that the bytes passed +to it are valid UTF-8. If this constraint is violated, it may cause +memory unsafety issues with future users of the String, as the rest of +the library assumes that Strings are valid UTF-8.

+
Examples
+

Basic usage:

+ +
let mut s = String::from("hello");
+
+unsafe {
+    let vec = s.as_mut_vec();
+    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
+
+    vec.reverse();
+}
+assert_eq!(s, "olleh");
+
source

pub fn push_str(&mut self, string: &str) -> Result<(), ()>

Appends a given string slice onto the end of this String.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+assert!(s.push_str("bar").is_ok());
+
+assert_eq!("foobar", s);
+
+assert!(s.push_str("tender").is_err());
+
source

pub fn capacity(&self) -> usize

Returns the maximum number of elements the String can hold

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<4> = String::new();
+assert!(s.capacity() == 4);
+
source

pub fn push(&mut self, c: char) -> Result<(), ()>

Appends the given char to the end of this String.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("abc");
+
+s.push('1').unwrap();
+s.push('2').unwrap();
+s.push('3').unwrap();
+
+assert!("abc123" == s.as_str());
+
+assert_eq!("abc123", s);
+
source

pub fn truncate(&mut self, new_len: usize)

Shortens this String to the specified length.

+

If new_len is greater than the string’s current length, this has no +effect.

+

Note that this method has no effect on the allocated capacity +of the string

+
Panics
+

Panics if new_len does not lie on a char boundary.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("hello");
+
+s.truncate(2);
+
+assert_eq!("he", s);
+
source

pub fn pop(&mut self) -> Option<char>

Removes the last character from the string buffer and returns it.

+

Returns None if this String is empty.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+assert_eq!(s.pop(), Some('o'));
+assert_eq!(s.pop(), Some('o'));
+assert_eq!(s.pop(), Some('f'));
+
+assert_eq!(s.pop(), None);
+
source

pub fn clear(&mut self)

Truncates this String, removing all contents.

+

While this means the String will have a length of zero, it does not +touch its capacity.

+
Examples
+

Basic usage:

+ +
use heapless::String;
+
+let mut s: String<8> = String::from("foo");
+
+s.clear();
+
+assert!(s.is_empty());
+assert_eq!(0, s.len());
+assert_eq!(8, s.capacity());
+

Methods from Deref<Target = str>§

1.0.0

pub fn len(&self) -> usize

Returns the length of self.

+

This length is in bytes, not chars or graphemes. In other words, +it might not be what a human considers the length of the string.

+
Examples
+
let len = "foo".len();
+assert_eq!(3, len);
+
+assert_eq!("ƒoo".len(), 4); // fancy f!
+assert_eq!("ƒoo".chars().count(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

+
Examples
+
let s = "";
+assert!(s.is_empty());
+
+let s = "not empty";
+assert!(!s.is_empty());
+
1.9.0

pub fn is_char_boundary(&self, index: usize) -> bool

Checks that index-th byte is the first byte in a UTF-8 code point +sequence or the end of the string.

+

The start and end of the string (when index == self.len()) are +considered to be boundaries.

+

Returns false if index is greater than self.len().

+
Examples
+
let s = "Löwe 老虎 Léopard";
+assert!(s.is_char_boundary(0));
+// start of `老`
+assert!(s.is_char_boundary(6));
+assert!(s.is_char_boundary(s.len()));
+
+// second byte of `ö`
+assert!(!s.is_char_boundary(2));
+
+// third byte of `老`
+assert!(!s.is_char_boundary(8));
+

pub fn floor_char_boundary(&self, index: usize) -> usize

🔬This is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not exceeding index where is_char_boundary(x) is true.

+

This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t +exceed a given number of bytes. Note that this is done purely at the character level +and can still visually split graphemes, even though the underlying characters aren’t +split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only +includes 🧑 (person) instead.

+
Examples
+
#![feature(round_char_boundary)]
+let s = "❤️🧡💛💚💙💜";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.floor_char_boundary(13);
+assert_eq!(closest, 10);
+assert_eq!(&s[..closest], "❤️🧡");
+

pub fn ceil_char_boundary(&self, index: usize) -> usize

🔬This is a nightly-only experimental API. (round_char_boundary)

Finds the closest x not below index where is_char_boundary(x) is true.

+

This method is the natural complement to floor_char_boundary. See that method +for more details.

+
Panics
+

Panics if index > self.len().

+
Examples
+
#![feature(round_char_boundary)]
+let s = "❤️🧡💛💚💙💜";
+assert_eq!(s.len(), 26);
+assert!(!s.is_char_boundary(13));
+
+let closest = s.ceil_char_boundary(13);
+assert_eq!(closest, 14);
+assert_eq!(&s[..closest], "❤️🧡💛");
+
1.0.0

pub fn as_bytes(&self) -> &[u8]

Converts a string slice to a byte slice. To convert the byte slice back +into a string slice, use the [from_utf8] function.

+
Examples
+
let bytes = "bors".as_bytes();
+assert_eq!(b"bors", bytes);
+
1.20.0

pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8]

Converts a mutable string slice to a mutable byte slice.

+
Safety
+

The caller must ensure that the content of the slice is valid UTF-8 +before the borrow ends and the underlying str is used.

+

Use of a str whose contents are not valid UTF-8 is undefined behavior.

+
Examples
+

Basic usage:

+ +
let mut s = String::from("Hello");
+let bytes = unsafe { s.as_bytes_mut() };
+
+assert_eq!(b"Hello", bytes);
+

Mutability:

+ +
let mut s = String::from("🗻∈🌏");
+
+unsafe {
+    let bytes = s.as_bytes_mut();
+
+    bytes[0] = 0xF0;
+    bytes[1] = 0x9F;
+    bytes[2] = 0x8D;
+    bytes[3] = 0x94;
+}
+
+assert_eq!("🍔∈🌏", s);
+
1.0.0

pub fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +[u8]. This pointer will be pointing to the first byte of the string +slice.

+

The caller must ensure that the returned pointer is never written to. +If you need to mutate the contents of the string slice, use as_mut_ptr.

+
Examples
+
let s = "Hello";
+let ptr = s.as_ptr();
+
1.36.0

pub fn as_mut_ptr(&mut self) -> *mut u8

Converts a mutable string slice to a raw pointer.

+

As string slices are a slice of bytes, the raw pointer points to a +[u8]. This pointer will be pointing to the first byte of the string +slice.

+

It is your responsibility to make sure that the string slice only gets +modified in a way that it remains valid UTF-8.

+
1.20.0

pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where + I: SliceIndex<str>,

Returns a subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +[None] whenever equivalent indexing operation would panic.

+
Examples
+
let v = String::from("🗻∈🌏");
+
+assert_eq!(Some("🗻"), v.get(0..4));
+
+// indices not on UTF-8 sequence boundaries
+assert!(v.get(1..).is_none());
+assert!(v.get(..8).is_none());
+
+// out of bounds
+assert!(v.get(..42).is_none());
+
1.20.0

pub fn get_mut<I>( + &mut self, + i: I +) -> Option<&mut <I as SliceIndex<str>>::Output>where + I: SliceIndex<str>,

Returns a mutable subslice of str.

+

This is the non-panicking alternative to indexing the str. Returns +[None] whenever equivalent indexing operation would panic.

+
Examples
+
let mut v = String::from("hello");
+// correct length
+assert!(v.get_mut(0..5).is_some());
+// out of bounds
+assert!(v.get_mut(..42).is_none());
+assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
+
+assert_eq!("hello", v);
+{
+    let s = v.get_mut(0..2);
+    let s = s.map(|s| {
+        s.make_ascii_uppercase();
+        &*s
+    });
+    assert_eq!(Some("HE"), s);
+}
+assert_eq!("HEllo", v);
+
1.20.0

pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere + I: SliceIndex<str>,

Returns an unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
Safety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
Examples
+
let v = "🗻∈🌏";
+unsafe {
+    assert_eq!("🗻", v.get_unchecked(0..4));
+    assert_eq!("∈", v.get_unchecked(4..7));
+    assert_eq!("🌏", v.get_unchecked(7..11));
+}
+
1.20.0

pub unsafe fn get_unchecked_mut<I>( + &mut self, + i: I +) -> &mut <I as SliceIndex<str>>::Outputwhere + I: SliceIndex<str>,

Returns a mutable, unchecked subslice of str.

+

This is the unchecked alternative to indexing the str.

+
Safety
+

Callers of this function are responsible that these preconditions are +satisfied:

+
    +
  • The starting index must not exceed the ending index;
  • +
  • Indexes must be within bounds of the original slice;
  • +
  • Indexes must lie on UTF-8 sequence boundaries.
  • +
+

Failing that, the returned string slice may reference invalid memory or +violate the invariants communicated by the str type.

+
Examples
+
let mut v = String::from("🗻∈🌏");
+unsafe {
+    assert_eq!("🗻", v.get_unchecked_mut(0..4));
+    assert_eq!("∈", v.get_unchecked_mut(4..7));
+    assert_eq!("🌏", v.get_unchecked_mut(7..11));
+}
+
1.0.0

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

👎Deprecated since 1.29.0: use get_unchecked(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks.

+

This is generally not recommended, use with caution! For a safe +alternative see [str] and Index.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get a mutable string slice instead, see the +slice_mut_unchecked method.

+
Safety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
Examples
+
let s = "Löwe 老虎 Léopard";
+
+unsafe {
+    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
+}
+
+let s = "Hello, world!";
+
+unsafe {
+    assert_eq!("world", s.slice_unchecked(7, 12));
+}
+
1.5.0

pub unsafe fn slice_mut_unchecked( + &mut self, + begin: usize, + end: usize +) -> &mut str

👎Deprecated since 1.29.0: use get_unchecked_mut(begin..end) instead

Creates a string slice from another string slice, bypassing safety +checks. +This is generally not recommended, use with caution! For a safe +alternative see [str] and IndexMut.

+

This new slice goes from begin to end, including begin but +excluding end.

+

To get an immutable string slice instead, see the +slice_unchecked method.

+
Safety
+

Callers of this function are responsible that three preconditions are +satisfied:

+
    +
  • begin must not exceed end.
  • +
  • begin and end must be byte positions within the string slice.
  • +
  • begin and end must lie on UTF-8 sequence boundaries.
  • +
+
1.4.0

pub fn split_at(&self, mid: usize) -> (&str, &str)

Divide one string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get mutable string slices instead, see the split_at_mut +method.

+
Panics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is +past the end of the last code point of the string slice.

+
Examples
+
let s = "Per Martin-Löf";
+
+let (first, last) = s.split_at(3);
+
+assert_eq!("Per", first);
+assert_eq!(" Martin-Löf", last);
+
1.4.0

pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)

Divide one mutable string slice into two at an index.

+

The argument, mid, should be a byte offset from the start of the +string. It must also be on the boundary of a UTF-8 code point.

+

The two slices returned go from the start of the string slice to mid, +and from mid to the end of the string slice.

+

To get immutable string slices instead, see the split_at method.

+
Panics
+

Panics if mid is not on a UTF-8 code point boundary, or if it is +past the end of the last code point of the string slice.

+
Examples
+
let mut s = "Per Martin-Löf".to_string();
+{
+    let (first, last) = s.split_at_mut(3);
+    first.make_ascii_uppercase();
+    assert_eq!("PER", first);
+    assert_eq!(" Martin-Löf", last);
+}
+assert_eq!("PER Martin-Löf", s);
+
1.0.0

pub fn chars(&self) -> Chars<'_>

Returns an iterator over the chars of a string slice.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns such an iterator.

+

It’s important to remember that char represents a Unicode Scalar +Value, and might not match your idea of what a ‘character’ is. Iteration +over grapheme clusters may be what you actually want. This functionality +is not provided by Rust’s standard library, check crates.io instead.

+
Examples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.chars().count();
+assert_eq!(7, count);
+
+let mut chars = word.chars();
+
+assert_eq!(Some('g'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('o'), chars.next());
+assert_eq!(Some('d'), chars.next());
+assert_eq!(Some('b'), chars.next());
+assert_eq!(Some('y'), chars.next());
+assert_eq!(Some('e'), chars.next());
+
+assert_eq!(None, chars.next());
+

Remember, chars might not match your intuition about characters:

+ +
let y = "y̆";
+
+let mut chars = y.chars();
+
+assert_eq!(Some('y'), chars.next()); // not 'y̆'
+assert_eq!(Some('\u{0306}'), chars.next());
+
+assert_eq!(None, chars.next());
+
1.0.0

pub fn char_indices(&self) -> CharIndices<'_>

Returns an iterator over the chars of a string slice, and their +positions.

+

As a string slice consists of valid UTF-8, we can iterate through a +string slice by char. This method returns an iterator of both +these chars, as well as their byte positions.

+

The iterator yields tuples. The position is first, the char is +second.

+
Examples
+

Basic usage:

+ +
let word = "goodbye";
+
+let count = word.char_indices().count();
+assert_eq!(7, count);
+
+let mut char_indices = word.char_indices();
+
+assert_eq!(Some((0, 'g')), char_indices.next());
+assert_eq!(Some((1, 'o')), char_indices.next());
+assert_eq!(Some((2, 'o')), char_indices.next());
+assert_eq!(Some((3, 'd')), char_indices.next());
+assert_eq!(Some((4, 'b')), char_indices.next());
+assert_eq!(Some((5, 'y')), char_indices.next());
+assert_eq!(Some((6, 'e')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+

Remember, chars might not match your intuition about characters:

+ +
let yes = "y̆es";
+
+let mut char_indices = yes.char_indices();
+
+assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
+assert_eq!(Some((1, '\u{0306}')), char_indices.next());
+
+// note the 3 here - the last character took up two bytes
+assert_eq!(Some((3, 'e')), char_indices.next());
+assert_eq!(Some((4, 's')), char_indices.next());
+
+assert_eq!(None, char_indices.next());
+
1.0.0

pub fn bytes(&self) -> Bytes<'_>

An iterator over the bytes of a string slice.

+

As a string slice consists of a sequence of bytes, we can iterate +through a string slice by byte. This method returns such an iterator.

+
Examples
+
let mut bytes = "bors".bytes();
+
+assert_eq!(Some(b'b'), bytes.next());
+assert_eq!(Some(b'o'), bytes.next());
+assert_eq!(Some(b'r'), bytes.next());
+assert_eq!(Some(b's'), bytes.next());
+
+assert_eq!(None, bytes.next());
+
1.1.0

pub fn split_whitespace(&self) -> SplitWhitespace<'_>

Splits a string slice by whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of whitespace.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space. If you only want to split on ASCII whitespace +instead, use split_ascii_whitespace.

+
Examples
+

Basic usage:

+ +
let mut iter = "A few words".split_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of whitespace are considered:

+ +
let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_whitespace().next(), None);
+assert_eq!("   ".split_whitespace().next(), None);
+
1.34.0

pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>

Splits a string slice by ASCII whitespace.

+

The iterator returned will return string slices that are sub-slices of +the original string slice, separated by any amount of ASCII whitespace.

+

To split by Unicode Whitespace instead, use split_whitespace.

+
Examples
+

Basic usage:

+ +
let mut iter = "A few words".split_ascii_whitespace();
+
+assert_eq!(Some("A"), iter.next());
+assert_eq!(Some("few"), iter.next());
+assert_eq!(Some("words"), iter.next());
+
+assert_eq!(None, iter.next());
+

All kinds of ASCII whitespace are considered:

+ +
let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
+assert_eq!(Some("Mary"), iter.next());
+assert_eq!(Some("had"), iter.next());
+assert_eq!(Some("a"), iter.next());
+assert_eq!(Some("little"), iter.next());
+assert_eq!(Some("lamb"), iter.next());
+
+assert_eq!(None, iter.next());
+

If the string is empty or all ASCII whitespace, the iterator yields no string slices:

+ +
assert_eq!("".split_ascii_whitespace().next(), None);
+assert_eq!("   ".split_ascii_whitespace().next(), None);
+
1.0.0

pub fn lines(&self) -> Lines<'_>

An iterator over the lines of a string, as string slices.

+

Lines are split at line endings that are either newlines (\n) or +sequences of a carriage return followed by a line feed (\r\n).

+

Line terminators are not included in the lines returned by the iterator.

+

The final line ending is optional. A string that ends with a final line +ending will return the same lines as an otherwise identical string +without a final line ending.

+
Examples
+

Basic usage:

+ +
let text = "foo\r\nbar\n\nbaz\n";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+

The final line ending isn’t required:

+ +
let text = "foo\nbar\n\r\nbaz";
+let mut lines = text.lines();
+
+assert_eq!(Some("foo"), lines.next());
+assert_eq!(Some("bar"), lines.next());
+assert_eq!(Some(""), lines.next());
+assert_eq!(Some("baz"), lines.next());
+
+assert_eq!(None, lines.next());
+
1.0.0

pub fn lines_any(&self) -> LinesAny<'_>

👎Deprecated since 1.4.0: use lines() instead now

An iterator over the lines of a string.

+
1.8.0

pub fn encode_utf16(&self) -> EncodeUtf16<'_>

Returns an iterator of u16 over the string encoded as UTF-16.

+
Examples
+
let text = "Zażółć gęślą jaźń";
+
+let utf8_len = text.len();
+let utf16_len = text.encode_utf16().count();
+
+assert!(utf16_len <= utf8_len);
+
1.0.0

pub fn contains<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>,

Returns true if the given pattern matches a sub-slice of +this string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.contains("nana"));
+assert!(!bananas.contains("apples"));
+
1.0.0

pub fn starts_with<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>,

Returns true if the given pattern matches a prefix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.starts_with("bana"));
+assert!(!bananas.starts_with("nana"));
+
1.0.0

pub fn ends_with<'a, P>(&'a self, pat: P) -> boolwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns true if the given pattern matches a suffix of this +string slice.

+

Returns false if it does not.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let bananas = "bananas";
+
+assert!(bananas.ends_with("anas"));
+assert!(!bananas.ends_with("nana"));
+
1.0.0

pub fn find<'a, P>(&'a self, pat: P) -> Option<usize>where + P: Pattern<'a>,

Returns the byte index of the first character of this string slice that +matches the pattern.

+

Returns [None] if the pattern doesn’t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
let s = "Löwe 老虎 Léopard Gepardi";
+
+assert_eq!(s.find('L'), Some(0));
+assert_eq!(s.find('é'), Some(14));
+assert_eq!(s.find("pard"), Some(17));
+

More complex patterns using point-free style and closures:

+ +
let s = "Löwe 老虎 Léopard";
+
+assert_eq!(s.find(char::is_whitespace), Some(5));
+assert_eq!(s.find(char::is_lowercase), Some(1));
+assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
+assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
+

Not finding the pattern:

+ +
let s = "Löwe 老虎 Léopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.find(x), None);
+
1.0.0

pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns the byte index for the first character of the last match of the pattern in +this string slice.

+

Returns [None] if the pattern doesn’t match.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
let s = "Löwe 老虎 Léopard Gepardi";
+
+assert_eq!(s.rfind('L'), Some(13));
+assert_eq!(s.rfind('é'), Some(14));
+assert_eq!(s.rfind("pard"), Some(24));
+

More complex patterns with closures:

+ +
let s = "Löwe 老虎 Léopard";
+
+assert_eq!(s.rfind(char::is_whitespace), Some(12));
+assert_eq!(s.rfind(char::is_lowercase), Some(20));
+

Not finding the pattern:

+ +
let s = "Löwe 老虎 Léopard";
+let x: &[_] = &['1', '2'];
+
+assert_eq!(s.rfind(x), None);
+
1.0.0

pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P>where + P: Pattern<'a>,

An iterator over substrings of this string slice, separated by +characters matched by a pattern.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rsplit method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
+assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
+
+let v: Vec<&str> = "".split('X').collect();
+assert_eq!(v, [""]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
+assert_eq!(v, ["lion", "", "tiger", "leopard"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
+assert_eq!(v, ["lion", "tiger", "leopard"]);
+
+let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
+assert_eq!(v, ["abc", "def", "ghi"]);
+
+let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
+assert_eq!(v, ["lion", "tiger", "leopard"]);
+

If the pattern is a slice of chars, split on each occurrence of any of the characters:

+ +
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
+assert_eq!(v, ["2020", "11", "03", "23", "59"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["abc", "def", "ghi"]);
+

If a string contains multiple contiguous separators, you will end up +with empty strings in the output:

+ +
let x = "||||a||b|c".to_string();
+let d: Vec<_> = x.split('|').collect();
+
+assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
+

Contiguous separators are separated by the empty string.

+ +
let x = "(///)".to_string();
+let d: Vec<_> = x.split('/').collect();
+
+assert_eq!(d, &["(", "", "", ")"]);
+

Separators at the start or end of a string are neighbored +by empty strings.

+ +
let d: Vec<_> = "010".split("0").collect();
+assert_eq!(d, &["", "1", ""]);
+

When the empty string is used as a separator, it separates +every character in the string, along with the beginning +and end of the string.

+ +
let f: Vec<_> = "rust".split("").collect();
+assert_eq!(f, &["", "r", "u", "s", "t", ""]);
+

Contiguous separators can lead to possibly surprising behavior +when whitespace is used as the separator. This code is correct:

+ +
let x = "    a  b c".to_string();
+let d: Vec<_> = x.split(' ').collect();
+
+assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
+

It does not give you:

+ +
assert_eq!(d, &["a", "b", "c"]);
+

Use split_whitespace for this behavior.

+
1.51.0

pub fn split_inclusive<'a, P>(&'a self, pat: P) -> SplitInclusive<'a, P>where + P: Pattern<'a>,

An iterator over substrings of this string slice, separated by +characters matched by a pattern. Differs from the iterator produced by +split in that split_inclusive leaves the matched part as the +terminator of the substring.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
+

If the last element of the string is matched, +that element will be considered the terminator of the preceding substring. +That substring will be the last item returned by the iterator.

+ +
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
+    .split_inclusive('\n').collect();
+assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
+
1.0.0

pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of the given string slice, separated by +characters matched by a pattern and yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the split method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
+assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
+
+let v: Vec<&str> = "".rsplit('X').collect();
+assert_eq!(v, [""]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
+assert_eq!(v, ["leopard", "tiger", "", "lion"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
+assert_eq!(v, ["leopard", "tiger", "lion"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["ghi", "def", "abc"]);
+
1.0.0

pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P>where + P: Pattern<'a>,

An iterator over substrings of the given string slice, separated by +characters matched by a pattern.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring +is skipped if empty.

+

This method can be used for string data that is terminated, +rather than separated by a pattern.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rsplit_terminator method can be used.

+
Examples
+
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
+assert_eq!(v, ["A", "B"]);
+
+let v: Vec<&str> = "A..B..".split_terminator(".").collect();
+assert_eq!(v, ["A", "", "B", ""]);
+
+let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
+assert_eq!(v, ["A", "B", "C", "D"]);
+
1.0.0

pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of self, separated by characters +matched by a pattern and yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+

Equivalent to split, except that the trailing substring is +skipped if empty.

+

This method can be used for string data that is terminated, +rather than separated by a pattern.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a +reverse search, and it will be double ended if a forward/reverse +search yields the same elements.

+

For iterating from the front, the split_terminator method can be +used.

+
Examples
+
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
+assert_eq!(v, ["B", "A"]);
+
+let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
+assert_eq!(v, ["", "B", "", "A"]);
+
+let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
+assert_eq!(v, ["D", "C", "B", "A"]);
+
1.0.0

pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P>where + P: Pattern<'a>,

An iterator over substrings of the given string slice, separated by a +pattern, restricted to returning at most n items.

+

If n substrings are returned, the last substring (the nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will not be double ended, because it is +not efficient to support.

+

If the pattern allows a reverse search, the rsplitn method can be +used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
+assert_eq!(v, ["Mary", "had", "a little lambda"]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
+assert_eq!(v, ["lion", "", "tigerXleopard"]);
+
+let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
+assert_eq!(v, ["abcXdef"]);
+
+let v: Vec<&str> = "".splitn(1, 'X').collect();
+assert_eq!(v, [""]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["abc", "defXghi"]);
+
1.0.0

pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over substrings of this string slice, separated by a +pattern, starting from the end of the string, restricted to returning +at most n items.

+

If n substrings are returned, the last substring (the nth substring) +will contain the remainder of the string.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will not be double ended, because it is not +efficient to support.

+

For splitting from the front, the splitn method can be used.

+
Examples
+

Simple patterns:

+ +
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
+assert_eq!(v, ["lamb", "little", "Mary had a"]);
+
+let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
+assert_eq!(v, ["leopard", "tiger", "lionX"]);
+
+let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
+assert_eq!(v, ["leopard", "lion::tiger"]);
+

A more complex pattern, using a closure:

+ +
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
+assert_eq!(v, ["ghi", "abc1def"]);
+
1.52.0

pub fn split_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where + P: Pattern<'a>,

Splits the string on the first occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
Examples
+
assert_eq!("cfg".split_once('='), None);
+assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
+assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
+
1.52.0

pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Splits the string on the last occurrence of the specified delimiter and +returns prefix before delimiter and suffix after delimiter.

+
Examples
+
assert_eq!("cfg".rsplit_once('='), None);
+assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
+assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
+
1.2.0

pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P>where + P: Pattern<'a>,

An iterator over the disjoint matches of a pattern within the given string +slice.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rmatches method can be used.

+
Examples
+
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
+assert_eq!(v, ["abc", "abc", "abc"]);
+
+let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
+assert_eq!(v, ["1", "2", "3"]);
+
1.2.0

pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over the disjoint matches of a pattern within this string slice, +yielded in reverse order.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the matches method can be used.

+
Examples
+
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
+assert_eq!(v, ["abc", "abc", "abc"]);
+
+let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
+assert_eq!(v, ["3", "2", "1"]);
+
1.5.0

pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P>where + P: Pattern<'a>,

An iterator over the disjoint matches of a pattern within this string +slice as well as the index that the match starts at.

+

For matches of pat within self that overlap, only the indices +corresponding to the first match are returned.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator will be a [DoubleEndedIterator] if the pattern +allows a reverse search and forward/reverse search yields the same +elements. This is true for, e.g., char, but not for &str.

+

If the pattern allows a reverse search but its results might differ +from a forward search, the rmatch_indices method can be used.

+
Examples
+
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
+assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
+
+let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
+assert_eq!(v, [(1, "abc"), (4, "abc")]);
+
+let v: Vec<_> = "ababa".match_indices("aba").collect();
+assert_eq!(v, [(0, "aba")]); // only the first `aba`
+
1.5.0

pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

An iterator over the disjoint matches of a pattern within self, +yielded in reverse order along with the index of the match.

+

For matches of pat within self that overlap, only the indices +corresponding to the last match are returned.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Iterator behavior
+

The returned iterator requires that the pattern supports a reverse +search, and it will be a [DoubleEndedIterator] if a forward/reverse +search yields the same elements.

+

For iterating from the front, the match_indices method can be used.

+
Examples
+
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
+assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
+
+let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
+assert_eq!(v, [(4, "abc"), (1, "abc")]);
+
+let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
+assert_eq!(v, [(2, "aba")]); // only the last `aba`
+
1.0.0

pub fn trim(&self) -> &str

Returns a string slice with leading and trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Examples
+
let s = "\n Hello\tworld\t\n";
+
+assert_eq!("Hello\tworld", s.trim());
+
1.30.0

pub fn trim_start(&self) -> &str

Returns a string slice with leading whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Text directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
Examples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("Hello\tworld\t\n", s.trim_start());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('E') == s.trim_start().chars().next());
+
+let s = "  עברית  ";
+assert!(Some('ע') == s.trim_start().chars().next());
+
1.30.0

pub fn trim_end(&self) -> &str

Returns a string slice with trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space, which includes newlines.

+
Text directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
Examples
+

Basic usage:

+ +
let s = "\n Hello\tworld\t\n";
+assert_eq!("\n Hello\tworld", s.trim_end());
+

Directionality:

+ +
let s = "  English  ";
+assert!(Some('h') == s.trim_end().chars().rev().next());
+
+let s = "  עברית  ";
+assert!(Some('ת') == s.trim_end().chars().rev().next());
+
1.0.0

pub fn trim_left(&self) -> &str

👎Deprecated since 1.33.0: superseded by trim_start

Returns a string slice with leading whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
Text directionality
+

A string is a sequence of bytes. ‘Left’ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the right side, not the left.

+
Examples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!("Hello\tworld\t", s.trim_left());
+

Directionality:

+ +
let s = "  English";
+assert!(Some('E') == s.trim_left().chars().next());
+
+let s = "  עברית";
+assert!(Some('ע') == s.trim_left().chars().next());
+
1.0.0

pub fn trim_right(&self) -> &str

👎Deprecated since 1.33.0: superseded by trim_end

Returns a string slice with trailing whitespace removed.

+

‘Whitespace’ is defined according to the terms of the Unicode Derived +Core Property White_Space.

+
Text directionality
+

A string is a sequence of bytes. ‘Right’ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the left side, not the right.

+
Examples
+

Basic usage:

+ +
let s = " Hello\tworld\t";
+
+assert_eq!(" Hello\tworld", s.trim_right());
+

Directionality:

+ +
let s = "English  ";
+assert!(Some('h') == s.trim_right().chars().rev().next());
+
+let s = "עברית  ";
+assert!(Some('ת') == s.trim_right().chars().rev().next());
+
1.0.0

pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,

Returns a string slice with all prefixes and suffixes that match a +pattern repeatedly removed.

+

The pattern can be a char, a slice of chars, or a function +or closure that determines if a character matches.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
+assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
+
1.30.0

pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>,

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. start in this context means the first +position of that byte string; for a left-to-right language like English or +Russian, this will be left side, and for right-to-left languages like +Arabic or Hebrew, this will be the right side.

+
Examples
+
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
+
1.45.0

pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<&'a str>where + P: Pattern<'a>,

Returns a string slice with the prefix removed.

+

If the string starts with the pattern prefix, returns substring after the prefix, wrapped +in Some. Unlike trim_start_matches, this method removes the prefix exactly once.

+

If the string does not start with prefix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
+assert_eq!("foo:bar".strip_prefix("bar"), None);
+assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
+
1.45.0

pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>where + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns a string slice with the suffix removed.

+

If the string ends with the pattern suffix, returns the substring before the suffix, +wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.

+

If the string does not end with suffix, returns None.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Examples
+
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
+assert_eq!("bar:foo".strip_suffix("bar"), None);
+assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
+
1.30.0

pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. end in this context means the last +position of that byte string; for a left-to-right language like English or +Russian, this will be right side, and for right-to-left languages like +Arabic or Hebrew, this will be the left side.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.0.0

pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>,

👎Deprecated since 1.33.0: superseded by trim_start_matches

Returns a string slice with all prefixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. ‘Left’ in this context means the first +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the right side, not the left.

+
Examples
+
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
+assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
+
1.0.0

pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a strwhere + P: Pattern<'a>, + <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,

👎Deprecated since 1.33.0: superseded by trim_end_matches

Returns a string slice with all suffixes that match a pattern +repeatedly removed.

+

The pattern can be a &str, char, a slice of chars, or a +function or closure that determines if a character matches.

+
Text directionality
+

A string is a sequence of bytes. ‘Right’ in this context means the last +position of that byte string; for a language like Arabic or Hebrew +which are ‘right to left’ rather than ‘left to right’, this will be +the left side, not the right.

+
Examples
+

Simple patterns:

+ +
assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
+assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
+
+let x: &[_] = &['1', '2'];
+assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
+

A more complex pattern, using a closure:

+ +
assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
+
1.0.0

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where + F: FromStr,

Parses this string slice into another type.

+

Because parse is so general, it can cause problems with type +inference. As such, parse is one of the few times you’ll see +the syntax affectionately known as the ‘turbofish’: ::<>. This +helps the inference algorithm understand specifically which type +you’re trying to parse into.

+

parse can parse into any type that implements the [FromStr] trait.

+
Errors
+

Will return Err if it’s not possible to parse this string slice into +the desired type.

+
Examples
+

Basic usage

+ +
let four: u32 = "4".parse().unwrap();
+
+assert_eq!(4, four);
+

Using the ‘turbofish’ instead of annotating four:

+ +
let four = "4".parse::<u32>();
+
+assert_eq!(Ok(4), four);
+

Failing to parse:

+ +
let nope = "j".parse::<u32>();
+
+assert!(nope.is_err());
+
1.23.0

pub fn is_ascii(&self) -> bool

Checks if all characters in this string are within the ASCII range.

+
Examples
+
let ascii = "hello!\n";
+let non_ascii = "Grüße, Jürgen ❤";
+
+assert!(ascii.is_ascii());
+assert!(!non_ascii.is_ascii());
+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this string slice is_ascii, returns it as a slice +of ASCII characters, otherwise returns None.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &str) -> bool

Checks that two strings are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
Examples
+
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
+assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
+assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
+
1.23.0

pub fn make_ascii_uppercase(&mut self)

Converts this string to its ASCII upper case equivalent in-place.

+

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, +but non-ASCII letters are unchanged.

+

To return a new uppercased value without modifying the existing one, use +to_ascii_uppercase().

+
Examples
+
let mut s = String::from("Grüße, Jürgen ❤");
+
+s.make_ascii_uppercase();
+
+assert_eq!("GRüßE, JüRGEN ❤", s);
+
1.23.0

pub fn make_ascii_lowercase(&mut self)

Converts this string to its ASCII lower case equivalent in-place.

+

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, +but non-ASCII letters are unchanged.

+

To return a new lowercased value without modifying the existing one, use +to_ascii_lowercase().

+
Examples
+
let mut s = String::from("GRÜßE, JÜRGEN ❤");
+
+s.make_ascii_lowercase();
+
+assert_eq!("grÜße, jÜrgen ❤", s);
+
1.34.0

pub fn escape_debug(&self) -> EscapeDebug<'_>

Return an iterator that escapes each char in self with [char::escape_debug].

+

Note: only extended grapheme codepoints that begin the string will be +escaped.

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_debug() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_debug());
+

Both are equivalent to:

+ +
println!("❤\\n!");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
+
1.34.0

pub fn escape_default(&self) -> EscapeDefault<'_>

Return an iterator that escapes each char in self with [char::escape_default].

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_default() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_default());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\n!");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
+
1.34.0

pub fn escape_unicode(&self) -> EscapeUnicode<'_>

Return an iterator that escapes each char in self with [char::escape_unicode].

+
Examples
+

As an iterator:

+ +
for c in "❤\n!".escape_unicode() {
+    print!("{c}");
+}
+println!();
+

Using println! directly:

+ +
println!("{}", "❤\n!".escape_unicode());
+

Both are equivalent to:

+ +
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
+

Using to_string:

+ +
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
+

Trait Implementations§

source§

impl<const N: usize> AsRef<[u8]> for String<N>

source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize> AsRef<str> for String<N>

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<const N: usize> Clone for String<N>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<const N: usize> Debug for String<N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<const N: usize> Default for String<N>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<const N: usize> Deref for String<N>

§

type Target = str

The resulting type after dereferencing.
source§

fn deref(&self) -> &str

Dereferences the value.
source§

impl<const N: usize> DerefMut for String<N>

source§

fn deref_mut(&mut self) -> &mut str

Mutably dereferences the value.
source§

impl<const N: usize> Display for String<N>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a, const N: usize> From<&'a str> for String<N>

source§

fn from(s: &'a str) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<i16> for String<N>

source§

fn from(s: i16) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<i32> for String<N>

source§

fn from(s: i32) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<i64> for String<N>

source§

fn from(s: i64) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<i8> for String<N>

source§

fn from(s: i8) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<u16> for String<N>

source§

fn from(s: u16) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<u32> for String<N>

source§

fn from(s: u32) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<u64> for String<N>

source§

fn from(s: u64) -> Self

Converts to this type from the input type.
source§

impl<const N: usize> From<u8> for String<N>

source§

fn from(s: u8) -> Self

Converts to this type from the input type.
source§

impl<'a, const N: usize> FromIterator<&'a char> for String<N>

source§

fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<'a, const N: usize> FromIterator<&'a str> for String<N>

source§

fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<const N: usize> FromIterator<char> for String<N>

source§

fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<const N: usize> FromStr for String<N>

§

type Err = ()

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl<const N: usize> Hash for String<N>

source§

fn hash<H: Hasher>(&self, hasher: &mut H)

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl<const N: usize> Hash for String<N>

source§

fn hash<H: Hasher>(&self, hasher: &mut H)

Feeds this value into the given Hasher.
source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.
source§

impl<const N: usize> Ord for String<N>

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<const N: usize> PartialEq<&str> for String<N>

source§

fn eq(&self, other: &&str) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &&str) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<String<N>> for &str

source§

fn eq(&self, other: &String<N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &String<N>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<String<N>> for str

source§

fn eq(&self, other: &String<N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &String<N>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N1: usize, const N2: usize> PartialEq<String<N2>> for String<N1>

source§

fn eq(&self, rhs: &String<N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, rhs: &String<N2>) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N: usize> PartialEq<str> for String<N>

source§

fn eq(&self, other: &str) -> bool

This method tests for self and other values to be equal, and is used +by ==.
source§

fn ne(&self, other: &str) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<const N1: usize, const N2: usize> PartialOrd<String<N2>> for String<N1>

source§

fn partial_cmp(&self, other: &String<N2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl<const N: usize> Write for String<N>

source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write +succeeded. Read more
source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a [char] into this writer, returning whether the write succeeded. Read more
1.0.0§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the [write!] macro with implementors of this trait. Read more
source§

impl<const N: usize> Eq for String<N>

Auto Trait Implementations§

§

impl<const N: usize> RefUnwindSafe for String<N>

§

impl<const N: usize> Send for String<N>

§

impl<const N: usize> Sync for String<N>

§

impl<const N: usize> Unpin for String<N>

§

impl<const N: usize> UnwindSafe for String<N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.VacantEntry.html b/docs/doc/heapless/struct.VacantEntry.html new file mode 100644 index 0000000..7cb637f --- /dev/null +++ b/docs/doc/heapless/struct.VacantEntry.html @@ -0,0 +1,24 @@ +VacantEntry in heapless - Rust

Struct heapless::VacantEntry

source ·
pub struct VacantEntry<'a, K, V, const N: usize> { /* private fields */ }
Expand description

A view into an empty slot in the underlying map

+

Implementations§

source§

impl<'a, K, V, const N: usize> VacantEntry<'a, K, V, N>where + K: Eq + Hash,

source

pub fn key(&self) -> &K

Get the key associated with this entry

+
source

pub fn into_key(self) -> K

Consumes this entry to yield to key associated with it

+
source

pub fn insert(self, value: V) -> Result<&'a mut V, V>

Inserts this entry into to underlying map, yields a mutable reference to the inserted value. +If the map is at capacity the value is returned instead.

+

Auto Trait Implementations§

§

impl<'a, K, V, const N: usize> RefUnwindSafe for VacantEntry<'a, K, V, N>where + K: RefUnwindSafe, + V: RefUnwindSafe,

§

impl<'a, K, V, const N: usize> Send for VacantEntry<'a, K, V, N>where + K: Send, + V: Send,

§

impl<'a, K, V, const N: usize> Sync for VacantEntry<'a, K, V, N>where + K: Sync, + V: Sync,

§

impl<'a, K, V, const N: usize> Unpin for VacantEntry<'a, K, V, N>where + K: Unpin,

§

impl<'a, K, V, const N: usize> !UnwindSafe for VacantEntry<'a, K, V, N>

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/struct.Vec.html b/docs/doc/heapless/struct.Vec.html new file mode 100644 index 0000000..ba99711 --- /dev/null +++ b/docs/doc/heapless/struct.Vec.html @@ -0,0 +1,2528 @@ +Vec in heapless - Rust

Struct heapless::Vec

source ·
pub struct Vec<T, const N: usize> { /* private fields */ }
Expand description

A fixed capacity Vec

+

Examples

+
use heapless::Vec;
+
+
+// A vector with a fixed capacity of 8 elements allocated on the stack
+let mut vec = Vec::<_, 8>::new();
+vec.push(1);
+vec.push(2);
+
+assert_eq!(vec.len(), 2);
+assert_eq!(vec[0], 1);
+
+assert_eq!(vec.pop(), Some(2));
+assert_eq!(vec.len(), 1);
+
+vec[0] = 7;
+assert_eq!(vec[0], 7);
+
+vec.extend([1, 2, 3].iter().cloned());
+
+for x in &vec {
+    println!("{}", x);
+}
+assert_eq!(*vec, [7, 1, 2, 3]);
+

Implementations§

source§

impl<T, const N: usize> Vec<T, N>

source

pub const fn new() -> Self

Constructs a new, empty vector with a fixed capacity of N

+
Examples
+
use heapless::Vec;
+
+// allocate the vector on the stack
+let mut x: Vec<u8, 16> = Vec::new();
+
+// allocate the vector in a static variable
+static mut X: Vec<u8, 16> = Vec::new();
+

Vec const constructor; wrap the returned value in Vec

+
source

pub fn from_slice(other: &[T]) -> Result<Self, ()>where + T: Clone,

Constructs a new vector with a fixed capacity of N and fills it +with the provided slice.

+

This is equivalent to the following code:

+ +
use heapless::Vec;
+
+let mut v: Vec<u8, 16> = Vec::new();
+v.extend_from_slice(&[1, 2, 3]).unwrap();
+
source

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the vector’s buffer.

+
source

pub fn as_mut_ptr(&mut self) -> *mut T

Returns a raw pointer to the vector’s buffer, which may be mutated through.

+
source

pub fn as_slice(&self) -> &[T]

Extracts a slice containing the entire vector.

+

Equivalent to &s[..].

+
Examples
+
use heapless::Vec;
+let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
+
source

pub fn into_array<const M: usize>(self) -> Result<[T; M], Self>

Returns the contents of the vector as an array of length M if the length +of the vector is exactly M, otherwise returns Err(self).

+
Examples
+
use heapless::Vec;
+let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+let array: [u8; 5] = buffer.into_array().unwrap();
+assert_eq!(array, [1, 2, 3, 5, 8]);
+
source

pub const fn capacity(&self) -> usize

Returns the maximum number of elements the vector can hold.

+
source

pub fn clear(&mut self)

Clears the vector, removing all values.

+
source

pub fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends the vec from an iterator.

+
Panic
+

Panics if the vec cannot hold all elements of the iterator.

+
source

pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>where + T: Clone,

Clones and appends all elements in a slice to the Vec.

+

Iterates over the slice other, clones each element, and then appends +it to this Vec. The other vector is traversed in-order.

+
Examples
+
use heapless::Vec;
+
+let mut vec = Vec::<u8, 8>::new();
+vec.push(1).unwrap();
+vec.extend_from_slice(&[2, 3, 4]).unwrap();
+assert_eq!(*vec, [1, 2, 3, 4]);
+
source

pub fn pop(&mut self) -> Option<T>

Removes the last element from a vector and returns it, or None if it’s empty

+
source

pub fn push(&mut self, item: T) -> Result<(), T>

Appends an item to the back of the collection

+

Returns back the item if the vector is full

+
source

pub unsafe fn pop_unchecked(&mut self) -> T

Removes the last element from a vector and returns it

+
Safety
+

This assumes the vec to have at least one element.

+
source

pub unsafe fn push_unchecked(&mut self, item: T)

Appends an item to the back of the collection

+
Safety
+

This assumes the vec is not full.

+
source

pub fn truncate(&mut self, len: usize)

Shortens the vector, keeping the first len elements and dropping the rest.

+
source

pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>where + T: Clone,

Resizes the Vec in-place so that len is equal to new_len.

+

If new_len is greater than len, the Vec is extended by the +difference, with each additional slot filled with value. If +new_len is less than len, the Vec is simply truncated.

+

See also resize_default.

+
source

pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>where + T: Clone + Default,

Resizes the Vec in-place so that len is equal to new_len.

+

If new_len is greater than len, the Vec is extended by the +difference, with each additional slot filled with Default::default(). +If new_len is less than len, the Vec is simply truncated.

+

See also resize.

+
source

pub unsafe fn set_len(&mut self, new_len: usize)

Forces the length of the vector to new_len.

+

This is a low-level operation that maintains none of the normal +invariants of the type. Normally changing the length of a vector +is done using one of the safe operations instead, such as +truncate, resize, extend, or clear.

+
Safety
+
    +
  • new_len must be less than or equal to capacity().
  • +
  • The elements at old_len..new_len must be initialized.
  • +
+
Examples
+

This method can be useful for situations in which the vector +is serving as a buffer for other code, particularly over FFI:

+ +
use heapless::Vec;
+
+pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
+    // Per the FFI method's docs, "32768 bytes is always enough".
+    let mut dict = Vec::new();
+    let mut dict_length = 0;
+    // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
+    // 1. `dict_length` elements were initialized.
+    // 2. `dict_length` <= the capacity (32_768)
+    // which makes `set_len` safe to call.
+    unsafe {
+        // Make the FFI call...
+        let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
+        if r == Z_OK {
+            // ...and update the length to what was initialized.
+            dict.set_len(dict_length);
+            Some(dict)
+        } else {
+            None
+        }
+    }
+}
+

While the following example is sound, there is a memory leak since +the inner vectors were not freed prior to the set_len call:

+ +
use core::iter::FromIterator;
+use heapless::Vec;
+
+let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
+    [
+        Vec::from_iter([1, 0, 0].iter().cloned()),
+        Vec::from_iter([0, 1, 0].iter().cloned()),
+        Vec::from_iter([0, 0, 1].iter().cloned()),
+    ]
+    .iter()
+    .cloned()
+);
+// SAFETY:
+// 1. `old_len..0` is empty so no elements need to be initialized.
+// 2. `0 <= capacity` always holds whatever `capacity` is.
+unsafe {
+    vec.set_len(0);
+}
+

Normally, here, one would use clear instead to correctly drop +the contents and thus not leak memory.

+
source

pub fn swap_remove(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

+

The removed element is replaced by the last element of the vector.

+

This does not preserve ordering, but is O(1).

+
Panics
+

Panics if index is out of bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::new();
+v.push("foo").unwrap();
+v.push("bar").unwrap();
+v.push("baz").unwrap();
+v.push("qux").unwrap();
+
+assert_eq!(v.swap_remove(1), "bar");
+assert_eq!(&*v, ["foo", "qux", "baz"]);
+
+assert_eq!(v.swap_remove(0), "foo");
+assert_eq!(&*v, ["baz", "qux"]);
+
source

pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T

Removes an element from the vector and returns it.

+

The removed element is replaced by the last element of the vector.

+

This does not preserve ordering, but is O(1).

+
Safety
+

Assumes index within bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::new();
+v.push("foo").unwrap();
+v.push("bar").unwrap();
+v.push("baz").unwrap();
+v.push("qux").unwrap();
+
+assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
+assert_eq!(&*v, ["foo", "qux", "baz"]);
+
+assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
+assert_eq!(&*v, ["baz", "qux"]);
+
source

pub fn is_full(&self) -> bool

Returns true if the vec is full

+
source

pub fn is_empty(&self) -> bool

Returns true if the vec is empty

+
source

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq,

Returns true if needle is a prefix of the Vec.

+

Always returns true if needle is an empty slice.

+
Examples
+
use heapless::Vec;
+
+let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+assert_eq!(v.starts_with(b""), true);
+assert_eq!(v.starts_with(b"ab"), true);
+assert_eq!(v.starts_with(b"bc"), false);
+
source

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq,

Returns true if needle is a suffix of the Vec.

+

Always returns true if needle is an empty slice.

+
Examples
+
use heapless::Vec;
+
+let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+assert_eq!(v.ends_with(b""), true);
+assert_eq!(v.ends_with(b"ab"), false);
+assert_eq!(v.ends_with(b"bc"), true);
+
source

pub fn insert(&mut self, index: usize, element: T) -> Result<(), T>

Inserts an element at position index within the vector, shifting all +elements after it to the right.

+

Returns back the element if the vector is full.

+
Panics
+

Panics if index > len.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+vec.insert(1, 4);
+assert_eq!(vec, [1, 4, 2, 3]);
+vec.insert(4, 5);
+assert_eq!(vec, [1, 4, 2, 3, 5]);
+
source

pub fn remove(&mut self, index: usize) -> T

Removes and returns the element at position index within the vector, +shifting all elements after it to the left.

+

Note: Because this shifts over the remaining elements, it has a +worst-case performance of O(n). If you don’t need the order of +elements to be preserved, use swap_remove instead. If you’d like to +remove elements from the beginning of the Vec, consider using +Deque::pop_front instead.

+
Panics
+

Panics if index is out of bounds.

+
Examples
+
use heapless::Vec;
+
+let mut v: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+assert_eq!(v.remove(1), 2);
+assert_eq!(v, [1, 3]);
+
source

pub fn retain<F>(&mut self, f: F)where + F: FnMut(&T) -> bool,

Retains only the elements specified by the predicate.

+

In other words, remove all elements e for which f(&e) returns false. +This method operates in place, visiting each element exactly once in the +original order, and preserves the order of the retained elements.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+vec.retain(|&x| x % 2 == 0);
+assert_eq!(vec, [2, 4]);
+

Because the elements are visited exactly once in the original order, +external state may be used to decide which elements to keep.

+ +
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4, 5]).unwrap();
+let keep = [false, true, true, false, true];
+let mut iter = keep.iter();
+vec.retain(|_| *iter.next().unwrap());
+assert_eq!(vec, [2, 3, 5]);
+
source

pub fn retain_mut<F>(&mut self, f: F)where + F: FnMut(&mut T) -> bool,

Retains only the elements specified by the predicate, passing a mutable reference to it.

+

In other words, remove all elements e such that f(&mut e) returns false. +This method operates in place, visiting each element exactly once in the +original order, and preserves the order of the retained elements.

+
Examples
+
use heapless::Vec;
+
+let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+vec.retain_mut(|x| if *x <= 3 {
+    *x += 1;
+    true
+} else {
+    false
+});
+assert_eq!(vec, [2, 3, 4]);
+

Methods from Deref<Target = [T]>§

1.23.0

pub fn is_ascii(&self) -> bool

Checks if all bytes in this slice are within the ASCII range.

+

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this slice is_ascii, returns it as a slice of +ASCII characters, otherwise returns None.

+

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this slice of bytes into a slice of ASCII characters, +without checking whether they’re valid.

+
Safety
+

Every byte in the slice must be in 0..=127, or else this is UB.

+
1.23.0

pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool

Checks that two slices are an ASCII case-insensitive match.

+

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), +but without allocating and copying temporaries.

+
1.23.0

pub fn make_ascii_uppercase(&mut self)

Converts this slice to its ASCII upper case equivalent in-place.

+

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, +but non-ASCII letters are unchanged.

+

To return a new uppercased value without modifying the existing one, use +to_ascii_uppercase.

+
1.23.0

pub fn make_ascii_lowercase(&mut self)

Converts this slice to its ASCII lower case equivalent in-place.

+

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, +but non-ASCII letters are unchanged.

+

To return a new lowercased value without modifying the existing one, use +to_ascii_lowercase.

+
1.60.0

pub fn escape_ascii(&self) -> EscapeAscii<'_>

Returns an iterator that produces an escaped version of this slice, +treating it as an ASCII string.

+
Examples
+

+let s = b"0\t\r\n'\"\\\x9d";
+let escaped = s.escape_ascii().to_string();
+assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
+

pub fn trim_ascii_start(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
+assert_eq!(b"  ".trim_ascii_start(), b"");
+assert_eq!(b"".trim_ascii_start(), b"");
+

pub fn trim_ascii_end(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with trailing ASCII whitespace bytes removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
+assert_eq!(b"  ".trim_ascii_end(), b"");
+assert_eq!(b"".trim_ascii_end(), b"");
+

pub fn trim_ascii(&self) -> &[u8]

🔬This is a nightly-only experimental API. (byte_slice_trim_ascii)

Returns a byte slice with leading and trailing ASCII whitespace bytes +removed.

+

‘Whitespace’ refers to the definition used by +u8::is_ascii_whitespace.

+
Examples
+
#![feature(byte_slice_trim_ascii)]
+
+assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
+assert_eq!(b"  ".trim_ascii(), b"");
+assert_eq!(b"".trim_ascii(), b"");
+

pub fn as_str(&self) -> &str

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a UTF-8 str.

+

pub fn as_bytes(&self) -> &[u8]

🔬This is a nightly-only experimental API. (ascii_char)

Views this slice of ASCII characters as a slice of u8 bytes.

+

pub fn flatten(&self) -> &[T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &[[T; N]], and flattens it to a &[T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), &[1, 2, 3, 4, 5, 6]);
+
+assert_eq!(
+    [[1, 2, 3], [4, 5, 6]].flatten(),
+    [[1, 2], [3, 4], [5, 6]].flatten(),
+);
+
+let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
+assert!(slice_of_empty_arrays.flatten().is_empty());
+
+let empty_slice_of_arrays: &[[u32; 10]] = &[];
+assert!(empty_slice_of_arrays.flatten().is_empty());
+

pub fn flatten_mut(&mut self) -> &mut [T]

🔬This is a nightly-only experimental API. (slice_flatten)

Takes a &mut [[T; N]], and flattens it to a &mut [T].

+
Panics
+

This panics if the length of the resulting slice would overflow a usize.

+

This is only possible when flattening a slice of arrays of zero-sized +types, and thus tends to be irrelevant in practice. If +size_of::<T>() > 0, this will never panic.

+
Examples
+
#![feature(slice_flatten)]
+
+fn add_5_to_all(slice: &mut [i32]) {
+    for i in slice {
+        *i += 5;
+    }
+}
+
+let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
+add_5_to_all(array.flatten_mut());
+assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
+
1.0.0

pub fn len(&self) -> usize

Returns the number of elements in the slice.

+
Examples
+
let a = [1, 2, 3];
+assert_eq!(a.len(), 3);
+
1.0.0

pub fn is_empty(&self) -> bool

Returns true if the slice has a length of 0.

+
Examples
+
let a = [1, 2, 3];
+assert!(!a.is_empty());
+
1.0.0

pub fn first(&self) -> Option<&T>

Returns the first element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&10), v.first());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.first());
+
1.0.0

pub fn first_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the first element of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(first) = x.first_mut() {
+    *first = 5;
+}
+assert_eq!(x, &[5, 1, 2]);
+
1.5.0

pub fn split_first(&self) -> Option<(&T, &[T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first() {
+    assert_eq!(first, &0);
+    assert_eq!(elements, &[1, 2]);
+}
+
1.5.0

pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the first and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_mut() {
+    *first = 3;
+    elements[0] = 4;
+    elements[1] = 5;
+}
+assert_eq!(x, &[3, 4, 5]);
+
1.5.0

pub fn split_last(&self) -> Option<(&T, &[T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last() {
+    assert_eq!(last, &2);
+    assert_eq!(elements, &[0, 1]);
+}
+
1.5.0

pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_mut() {
+    *last = 3;
+    elements[0] = 4;
+    elements[1] = 5;
+}
+assert_eq!(x, &[4, 5, 3]);
+
1.0.0

pub fn last(&self) -> Option<&T>

Returns the last element of the slice, or None if it is empty.

+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&30), v.last());
+
+let w: &[i32] = &[];
+assert_eq!(None, w.last());
+
1.0.0

pub fn last_mut(&mut self) -> Option<&mut T>

Returns a mutable pointer to the last item in the slice.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(last) = x.last_mut() {
+    *last = 10;
+}
+assert_eq!(x, &[0, 1, 10]);
+

pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice, or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.first_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.first_chunk::<0>());
+

pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable reference to the first N elements of the slice, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some(first) = x.first_chunk_mut::<2>() {
+    first[0] = 5;
+    first[1] = 4;
+}
+assert_eq!(x, &[5, 4, 2]);
+

pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk::<2>() {
+    assert_eq!(first, &[0, 1]);
+    assert_eq!(elements, &[2]);
+}
+

pub fn split_first_chunk_mut<const N: usize>( + &mut self +) -> Option<(&mut [T; N], &mut [T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable reference to the first N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
+    first[0] = 3;
+    first[1] = 4;
+    elements[0] = 5;
+}
+assert_eq!(x, &[3, 4, 5]);
+

pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last N elements of the slice and the remainder, +or None if it has fewer than N elements.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &[0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk::<2>() {
+    assert_eq!(last, &[1, 2]);
+    assert_eq!(elements, &[0]);
+}
+

pub fn split_last_chunk_mut<const N: usize>( + &mut self +) -> Option<(&mut [T; N], &mut [T])>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last and all the rest of the elements of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some((last, elements)) = x.split_last_chunk_mut::<2>() {
+    last[0] = 3;
+    last[1] = 4;
+    elements[0] = 5;
+}
+assert_eq!(x, &[5, 3, 4]);
+

pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns the last element of the slice, or None if it is empty.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let u = [10, 40, 30];
+assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
+
+let v: &[i32] = &[10];
+assert_eq!(None, v.last_chunk::<2>());
+
+let w: &[i32] = &[];
+assert_eq!(Some(&[]), w.last_chunk::<0>());
+

pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>

🔬This is a nightly-only experimental API. (slice_first_last_chunk)

Returns a mutable pointer to the last item in the slice.

+
Examples
+
#![feature(slice_first_last_chunk)]
+
+let x = &mut [0, 1, 2];
+
+if let Some(last) = x.last_chunk_mut::<2>() {
+    last[0] = 10;
+    last[1] = 20;
+}
+assert_eq!(x, &[0, 10, 20]);
+
1.0.0

pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a reference to an element or subslice depending on the type of +index.

+
    +
  • If given a position, returns a reference to the element at that +position or None if out of bounds.
  • +
  • If given a range, returns the subslice corresponding to that range, +or None if out of bounds.
  • +
+
Examples
+
let v = [10, 40, 30];
+assert_eq!(Some(&40), v.get(1));
+assert_eq!(Some(&[10, 40][..]), v.get(0..2));
+assert_eq!(None, v.get(3));
+assert_eq!(None, v.get(0..4));
+
1.0.0

pub fn get_mut<I>( + &mut self, + index: I +) -> Option<&mut <I as SliceIndex<[T]>>::Output>where + I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice depending on the +type of index (see get) or None if the index is out of bounds.

+
Examples
+
let x = &mut [0, 1, 2];
+
+if let Some(elem) = x.get_mut(1) {
+    *elem = 42;
+}
+assert_eq!(x, &[0, 42, 2]);
+
1.0.0

pub unsafe fn get_unchecked<I>( + &self, + index: I +) -> &<I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a reference to an element or subslice, without doing bounds +checking.

+

For a safe alternative see get.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &[1, 2, 4];
+
+unsafe {
+    assert_eq!(x.get_unchecked(1), &2);
+}
+
1.0.0

pub unsafe fn get_unchecked_mut<I>( + &mut self, + index: I +) -> &mut <I as SliceIndex<[T]>>::Outputwhere + I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice, without doing +bounds checking.

+

For a safe alternative see get_mut.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used.

+
Examples
+
let x = &mut [1, 2, 4];
+
+unsafe {
+    let elem = x.get_unchecked_mut(1);
+    *elem = 13;
+}
+assert_eq!(x, &[1, 13, 4]);
+
1.0.0

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

The caller must also ensure that the memory the pointer (non-transitively) points to +is never written to (except inside an UnsafeCell) using this pointer or any pointer +derived 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 +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &[1, 2, 4];
+let x_ptr = x.as_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
+    }
+}
+
1.0.0

pub fn as_mut_ptr(&mut self) -> *mut T

Returns an unsafe mutable pointer to the slice’s buffer.

+

The caller must ensure that the slice outlives the pointer this +function returns, or else it will end up pointing to garbage.

+

Modifying the container referenced by this slice may cause its buffer +to be reallocated, which would also make any pointers to it invalid.

+
Examples
+
let x = &mut [1, 2, 4];
+let x_ptr = x.as_mut_ptr();
+
+unsafe {
+    for i in 0..x.len() {
+        *x_ptr.add(i) += 2;
+    }
+}
+assert_eq!(x, &[3, 4, 6]);
+
1.48.0

pub fn as_ptr_range(&self) -> Range<*const T>

Returns the two raw pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_ptr for warnings on using these pointers. The end pointer +requires extra caution, as it does not point to a valid element in the +slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+

It can also be useful to check if a pointer to an element refers to an +element of this slice:

+ +
let a = [1, 2, 3];
+let x = &a[1] as *const _;
+let y = &5 as *const _;
+
+assert!(a.as_ptr_range().contains(&x));
+assert!(!a.as_ptr_range().contains(&y));
+
1.48.0

pub fn as_mut_ptr_range(&mut self) -> Range<*mut T>

Returns the two unsafe mutable pointers spanning the slice.

+

The returned range is half-open, which means that the end pointer +points one past the last element of the slice. This way, an empty +slice is represented by two equal pointers, and the difference between +the two pointers represents the size of the slice.

+

See as_mut_ptr for warnings on using these pointers. The end +pointer requires extra caution, as it does not point to a valid element +in the slice.

+

This function is useful for interacting with foreign interfaces which +use two pointers to refer to a range of elements in memory, as is +common in C++.

+
1.0.0

pub fn swap(&mut self, a: usize, b: usize)

Swaps two elements in the slice.

+

If a equals to b, it’s guaranteed that elements won’t change value.

+
Arguments
+
    +
  • a - The index of the first element
  • +
  • b - The index of the second element
  • +
+
Panics
+

Panics if a or b are out of bounds.

+
Examples
+
let mut v = ["a", "b", "c", "d", "e"];
+v.swap(2, 4);
+assert!(v == ["a", "b", "e", "d", "c"]);
+

pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)

🔬This is a nightly-only experimental API. (slice_swap_unchecked)

Swaps two elements in the slice, without doing bounds checking.

+

For a safe alternative see swap.

+
Arguments
+
    +
  • a - The index of the first element
  • +
  • b - The index of the second element
  • +
+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior. +The caller has to ensure that a < self.len() and b < self.len().

+
Examples
+
#![feature(slice_swap_unchecked)]
+
+let mut v = ["a", "b", "c", "d"];
+// SAFETY: we know that 1 and 3 are both indices of the slice
+unsafe { v.swap_unchecked(1, 3) };
+assert!(v == ["a", "d", "c", "b"]);
+
1.0.0

pub fn reverse(&mut self)

Reverses the order of elements in the slice, in place.

+
Examples
+
let mut v = [1, 2, 3];
+v.reverse();
+assert!(v == [3, 2, 1]);
+
1.0.0

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the slice.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &[1, 2, 4];
+let mut iterator = x.iter();
+
+assert_eq!(iterator.next(), Some(&1));
+assert_eq!(iterator.next(), Some(&2));
+assert_eq!(iterator.next(), Some(&4));
+assert_eq!(iterator.next(), None);
+
1.0.0

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns an iterator that allows modifying each value.

+

The iterator yields all items from start to end.

+
Examples
+
let x = &mut [1, 2, 4];
+for elem in x.iter_mut() {
+    *elem += 2;
+}
+assert_eq!(x, &[3, 4, 6]);
+
1.0.0

pub fn windows(&self, size: usize) -> Windows<'_, T>

Returns an iterator over all contiguous windows of length +size. The windows overlap. If the slice is shorter than +size, the iterator returns no values.

+
Panics
+

Panics if size is 0.

+
Examples
+
let slice = ['r', 'u', 's', 't'];
+let mut iter = slice.windows(2);
+assert_eq!(iter.next().unwrap(), &['r', 'u']);
+assert_eq!(iter.next().unwrap(), &['u', 's']);
+assert_eq!(iter.next().unwrap(), &['s', 't']);
+assert!(iter.next().is_none());
+

If the slice is shorter than size:

+ +
let slice = ['f', 'o', 'o'];
+let mut iter = slice.windows(4);
+assert!(iter.next().is_none());
+

There’s no windows_mut, as that existing would let safe code violate the +“only one &mut at a time to the same thing” rule. However, you can sometimes +use Cell::as_slice_of_cells in +conjunction with windows to accomplish something similar:

+ +
use std::cell::Cell;
+
+let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
+let slice = &mut array[..];
+let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
+for w in slice_of_cells.windows(3) {
+    Cell::swap(&w[0], &w[2]);
+}
+assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
+
1.0.0

pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and rchunks for the same iterator but starting at the end of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert_eq!(iter.next().unwrap(), &['m']);
+assert!(iter.next().is_none());
+
1.0.0

pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length 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 +exactly chunk_size elements, and rchunks_mut for the same iterator but starting at +the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.chunks_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 3]);
+
1.31.0

pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of chunks.

+

See chunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and rchunks_exact for the same iterator but starting at the end of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.chunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+
1.31.0

pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length of the slice, then the last up to chunk_size-1 elements will be omitted and can be +retrieved from the into_remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting 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 +smaller chunk, and rchunks_exact_mut for the same iterator but starting at the end of +the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.chunks_exact_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 0]);
+

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &[[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &[[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked() };
+assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
+

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (chunks, remainder) = slice.as_chunks();
+assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
+assert_eq!(remainder, &['m']);
+

If you expect the slice to be an exact multiple, you can combine +let-else with an empty slice pattern:

+ +
#![feature(slice_as_chunks)]
+let slice = ['R', 'u', 's', 't'];
+let (chunks, []) = slice.as_chunks::<2>() else {
+    panic!("slice didn't have even length")
+};
+assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
+

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let (remainder, chunks) = slice.as_rchunks();
+assert_eq!(remainder, &['l']);
+assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
+

pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are array references and do not overlap. If N does not divide the +length of the slice, then the last up to N-1 elements will be omitted and can be +retrieved from the remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.array_chunks();
+assert_eq!(iter.next().unwrap(), &['l', 'o']);
+assert_eq!(iter.next().unwrap(), &['r', 'e']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['m']);
+

pub unsafe fn as_chunks_unchecked_mut<const N: usize>( + &mut self +) -> &mut [[T; N]]

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +assuming that there’s no remainder.

+
Safety
+

This may only be called when

+
    +
  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • +
  • N != 0.
  • +
+
Examples
+
#![feature(slice_as_chunks)]
+let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
+let chunks: &mut [[char; 1]] =
+    // SAFETY: 1-element chunks never have remainder
+    unsafe { slice.as_chunks_unchecked_mut() };
+chunks[0] = ['L'];
+assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
+let chunks: &mut [[char; 3]] =
+    // SAFETY: The slice length (6) is a multiple of 3
+    unsafe { slice.as_chunks_unchecked_mut() };
+chunks[1] = ['a', 'x', '?'];
+assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
+
+// These would be unsound:
+// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
+// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
+

pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the beginning of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+let (chunks, remainder) = v.as_chunks_mut();
+remainder[0] = 9;
+for chunk in chunks {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 9]);
+

pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])

🔬This is a nightly-only experimental API. (slice_as_chunks)

Splits the slice into a slice of N-element arrays, +starting at the end of the slice, +and a remainder slice with length strictly less than N.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(slice_as_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+let (remainder, chunks) = v.as_rchunks_mut();
+remainder[0] = 9;
+for chunk in chunks {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[9, 1, 1, 2, 2]);
+

pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N>

🔬This is a nightly-only experimental API. (array_chunks)

Returns an iterator over N elements of the slice at a time, starting at the +beginning of the slice.

+

The chunks are mutable array references and do not overlap. If N does not divide +the length of the slice, then the last up to N-1 elements will be omitted and +can be retrieved from the into_remainder function of the iterator.

+

This method is the const generic equivalent of chunks_exact_mut.

+
Panics
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_chunks)]
+let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.array_chunks_mut() {
+    *chunk = [count; 2];
+    count += 1;
+}
+assert_eq!(v, &[1, 1, 2, 2, 0]);
+

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>

🔬This is a nightly-only experimental API. (array_windows)

Returns an iterator over overlapping windows of N elements of a slice, +starting 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
+

Panics if N is 0. This check will most probably get changed to a compile time +error before this method gets stabilized.

+
Examples
+
#![feature(array_windows)]
+let slice = [0, 1, 2, 3];
+let mut iter = slice.array_windows();
+assert_eq!(iter.next().unwrap(), &[0, 1]);
+assert_eq!(iter.next().unwrap(), &[1, 2]);
+assert_eq!(iter.next().unwrap(), &[2, 3]);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, 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 +chunk_size elements, and chunks for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert_eq!(iter.next().unwrap(), &['l']);
+assert!(iter.next().is_none());
+
1.31.0

pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length 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 +exactly chunk_size elements, and chunks_mut for the same iterator but starting at the +beginning of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.rchunks_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[3, 2, 2, 1, 1]);
+
1.31.0

pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the +end of the slice.

+

The chunks are slices and do not overlap. If chunk_size does not divide the length of the +slice, then the last up to chunk_size-1 elements will be omitted and can be retrieved +from the remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting code better than in the case of rchunks.

+

See rchunks for a variant of this iterator that also returns the remainder as a smaller +chunk, and chunks_exact for the same iterator but starting at the beginning of the +slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let slice = ['l', 'o', 'r', 'e', 'm'];
+let mut iter = slice.rchunks_exact(2);
+assert_eq!(iter.next().unwrap(), &['e', 'm']);
+assert_eq!(iter.next().unwrap(), &['o', 'r']);
+assert!(iter.next().is_none());
+assert_eq!(iter.remainder(), &['l']);
+
1.31.0

pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T>

Returns an iterator over chunk_size elements of the slice at a time, starting at the end +of the slice.

+

The chunks are mutable slices, and do not overlap. If chunk_size does not divide the +length of the slice, then the last up to chunk_size-1 elements will be omitted and can be +retrieved from the into_remainder function of the iterator.

+

Due to each chunk having exactly chunk_size elements, the compiler can often optimize the +resulting 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 +smaller chunk, and chunks_exact_mut for the same iterator but starting at the beginning +of the slice.

+
Panics
+

Panics if chunk_size is 0.

+
Examples
+
let v = &mut [0, 0, 0, 0, 0];
+let mut count = 1;
+
+for chunk in v.rchunks_exact_mut(2) {
+    for elem in chunk.iter_mut() {
+        *elem += count;
+    }
+    count += 1;
+}
+assert_eq!(v, &[0, 2, 2, 1, 1]);
+

pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping runs +of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&[3, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3][..]));
+assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+

pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>where + F: FnMut(&T, &T) -> bool,

🔬This is a nightly-only experimental API. (slice_group_by)

Returns an iterator over the slice producing non-overlapping mutable +runs of elements using the predicate to separate them.

+

The predicate is called on two elements following themselves, +it means the predicate is called on slice[0] and slice[1] +then on slice[1] and slice[2] and so on.

+
Examples
+
#![feature(slice_group_by)]
+
+let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
+
+let mut iter = slice.group_by_mut(|a, b| a == b);
+
+assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
+assert_eq!(iter.next(), Some(&mut [3, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
+assert_eq!(iter.next(), None);
+

This method can be used to extract the sorted subslices:

+ +
#![feature(slice_group_by)]
+
+let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
+
+let mut iter = slice.group_by_mut(|a, b| a <= b);
+
+assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 3][..]));
+assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
+assert_eq!(iter.next(), None);
+
1.0.0

pub fn split_at(&self, mid: usize) -> (&[T], &[T])

Divides one slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let v = [1, 2, 3, 4, 5, 6];
+
+{
+   let (left, right) = v.split_at(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_at(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+
1.0.0

pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])

Divides one mutable slice into two at an index.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+
Panics
+

Panics if mid > len.

+
Examples
+
let mut v = [1, 0, 3, 0, 5, 6];
+let (left, right) = v.split_at_mut(2);
+assert_eq!(left, [1, 0]);
+assert_eq!(right, [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let v = [1, 2, 3, 4, 5, 6];
+
+unsafe {
+   let (left, right) = v.split_at_unchecked(0);
+   assert_eq!(left, []);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(2);
+    assert_eq!(left, [1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+unsafe {
+    let (left, right) = v.split_at_unchecked(6);
+    assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub unsafe fn split_at_mut_unchecked( + &mut self, + mid: usize +) -> (&mut [T], &mut [T])

🔬This is a nightly-only experimental API. (slice_split_at_unchecked)

Divides one mutable slice into two at an index, without doing bounds checking.

+

The first will contain all indices from [0, mid) (excluding +the index mid itself) and the second will contain all +indices from [mid, len) (excluding the index len itself).

+

For a safe alternative see split_at_mut.

+
Safety
+

Calling this method with an out-of-bounds index is undefined behavior +even if the resulting reference is not used. The caller has to ensure that +0 <= mid <= self.len().

+
Examples
+
#![feature(slice_split_at_unchecked)]
+
+let mut v = [1, 0, 3, 0, 5, 6];
+// scoped to restrict the lifetime of the borrows
+unsafe {
+    let (left, right) = v.split_at_mut_unchecked(2);
+    assert_eq!(left, [1, 0]);
+    assert_eq!(right, [3, 0, 5, 6]);
+    left[1] = 2;
+    right[1] = 4;
+}
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.split_array_ref::<0>();
+   assert_eq!(left, &[]);
+   assert_eq!(right, [1, 2, 3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<2>();
+    assert_eq!(left, &[1, 2]);
+    assert_eq!(right, [3, 4, 5, 6]);
+}
+
+{
+    let (left, right) = v.split_array_ref::<6>();
+    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
+    assert_eq!(right, []);
+}
+

pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T])

🔬This is a nightly-only experimental API. (split_array)

Divides one mutable slice into an array and a remainder slice at an index.

+

The array will contain all indices from [0, N) (excluding +the index N itself) and the slice will contain all +indices from [N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let mut v = &mut [1, 0, 3, 0, 5, 6][..];
+let (left, right) = v.split_array_mut::<2>();
+assert_eq!(left, &mut [1, 0]);
+assert_eq!(right, [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+

pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one slice into an array and a remainder slice at an index from +the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index len - N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let v = &[1, 2, 3, 4, 5, 6][..];
+
+{
+   let (left, right) = v.rsplit_array_ref::<0>();
+   assert_eq!(left, [1, 2, 3, 4, 5, 6]);
+   assert_eq!(right, &[]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<2>();
+    assert_eq!(left, [1, 2, 3, 4]);
+    assert_eq!(right, &[5, 6]);
+}
+
+{
+    let (left, right) = v.rsplit_array_ref::<6>();
+    assert_eq!(left, []);
+    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
+}
+

pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N])

🔬This is a nightly-only experimental API. (split_array)

Divides one mutable slice into an array and a remainder slice at an +index from the end.

+

The slice will contain all indices from [0, len - N) (excluding +the index N itself) and the array will contain all +indices from [len - N, len) (excluding the index len itself).

+
Panics
+

Panics if N > len.

+
Examples
+
#![feature(split_array)]
+
+let mut v = &mut [1, 0, 3, 0, 5, 6][..];
+let (left, right) = v.rsplit_array_mut::<4>();
+assert_eq!(left, [1, 0]);
+assert_eq!(right, &mut [3, 0, 5, 6]);
+left[1] = 2;
+right[1] = 4;
+assert_eq!(v, [1, 2, 3, 4, 5, 6]);
+
1.0.0

pub fn split<F>(&self, pred: F) -> Split<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is not contained in the subslices.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the first element is matched, an empty slice will be the first item +returned by the iterator. Similarly, if the last element in the slice +is matched, an empty slice will be the last item returned by the +iterator:

+ +
let slice = [10, 40, 33];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert!(iter.next().is_none());
+

If two matched elements are directly adjacent, an empty slice will be +present between them:

+ +
let slice = [10, 6, 33, 20];
+let mut iter = slice.split(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10]);
+assert_eq!(iter.next().unwrap(), &[]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+
1.0.0

pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred. The matched element is not contained in the subslices.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.split_mut(|num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(v, [1, 40, 30, 1, 60, 1]);
+
1.51.0

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred. The matched element is contained in the end of the previous +subslice as a terminator.

+
Examples
+
let slice = [10, 40, 33, 20];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert_eq!(iter.next().unwrap(), &[20]);
+assert!(iter.next().is_none());
+

If the last element of the slice is matched, +that element will be considered the terminator of the preceding slice. +That slice will be the last item returned by the iterator.

+ +
let slice = [3, 10, 40, 33];
+let mut iter = slice.split_inclusive(|num| num % 3 == 0);
+
+assert_eq!(iter.next().unwrap(), &[3]);
+assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
+assert!(iter.next().is_none());
+
1.51.0

pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred. The matched element is contained in the previous +subslice as a terminator.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
+    let terminator_idx = group.len()-1;
+    group[terminator_idx] = 1;
+}
+assert_eq!(v, [10, 40, 1, 20, 1, 1]);
+
1.27.0

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, starting at the end of the slice and working backwards. +The matched element is not contained in the subslices.

+
Examples
+
let slice = [11, 22, 33, 0, 44, 55];
+let mut iter = slice.rsplit(|num| *num == 0);
+
+assert_eq!(iter.next().unwrap(), &[44, 55]);
+assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
+assert_eq!(iter.next(), None);
+

As with split(), if the first or last element is matched, an empty +slice will be the first (or last) item returned by the iterator.

+ +
let v = &[0, 1, 1, 2, 3, 5, 8];
+let mut it = v.rsplit(|n| *n % 2 == 0);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next().unwrap(), &[3, 5]);
+assert_eq!(it.next().unwrap(), &[1, 1]);
+assert_eq!(it.next().unwrap(), &[]);
+assert_eq!(it.next(), None);
+
1.27.0

pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that +match pred, starting at the end of the slice and working +backwards. The matched element is not contained in the subslices.

+
Examples
+
let mut v = [100, 400, 300, 200, 600, 500];
+
+let mut count = 0;
+for group in v.rsplit_mut(|num| *num % 3 == 0) {
+    count += 1;
+    group[0] = count;
+}
+assert_eq!(v, [3, 400, 300, 2, 600, 1]);
+
1.0.0

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once by numbers divisible by 3 (i.e., [10, 40], +[20, 60, 50]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over mutable subslices separated by elements that match +pred, limited to returning at most n items. The matched element is +not contained in the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+
let mut v = [10, 40, 30, 20, 60, 50];
+
+for group in v.splitn_mut(2, |num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(v, [1, 40, 30, 1, 60, 50]);
+
1.0.0

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+

Print the slice split once, starting from the end, by numbers divisible +by 3 (i.e., [50], [10, 40, 30, 20]):

+ +
let v = [10, 40, 30, 20, 60, 50];
+
+for group in v.rsplitn(2, |num| *num % 3 == 0) {
+    println!("{group:?}");
+}
+
1.0.0

pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>where + F: FnMut(&T) -> bool,

Returns an iterator over subslices separated by elements that match +pred limited to returning at most n items. This starts at the end of +the slice and works backwards. The matched element is not contained in +the subslices.

+

The last element returned, if any, will contain the remainder of the +slice.

+
Examples
+
let mut s = [10, 40, 30, 20, 60, 50];
+
+for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
+    group[0] = 1;
+}
+assert_eq!(s, [1, 40, 30, 20, 60, 1]);
+
1.0.0

pub fn contains(&self, x: &T) -> boolwhere + T: PartialEq<T>,

Returns true if the slice contains an element with the given value.

+

This operation is O(n).

+

Note that if you have a sorted slice, binary_search may be faster.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.contains(&30));
+assert!(!v.contains(&50));
+

If you do not have a &T, but some other value that you can compare +with one (for example, String implements PartialEq<str>), you can +use iter().any:

+ +
let v = [String::from("hello"), String::from("world")]; // slice of `String`
+assert!(v.iter().any(|e| e == "hello")); // search with `&str`
+assert!(!v.iter().any(|e| e == "hi"));
+
1.0.0

pub fn starts_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a prefix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.starts_with(&[10]));
+assert!(v.starts_with(&[10, 40]));
+assert!(!v.starts_with(&[50]));
+assert!(!v.starts_with(&[10, 50]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.starts_with(&[]));
+let v: &[u8] = &[];
+assert!(v.starts_with(&[]));
+
1.0.0

pub fn ends_with(&self, needle: &[T]) -> boolwhere + T: PartialEq<T>,

Returns true if needle is a suffix of the slice.

+
Examples
+
let v = [10, 40, 30];
+assert!(v.ends_with(&[30]));
+assert!(v.ends_with(&[40, 30]));
+assert!(!v.ends_with(&[50]));
+assert!(!v.ends_with(&[50, 30]));
+

Always returns true if needle is an empty slice:

+ +
let v = &[10, 40, 30];
+assert!(v.ends_with(&[]));
+let v: &[u8] = &[];
+assert!(v.ends_with(&[]));
+
1.51.0

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the prefix removed.

+

If the slice starts with prefix, returns the subslice after the prefix, wrapped in Some. +If prefix is empty, simply returns the original slice.

+

If the slice does not start with prefix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
+assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
+assert_eq!(v.strip_prefix(&[50]), None);
+assert_eq!(v.strip_prefix(&[10, 50]), None);
+
+let prefix : &str = "he";
+assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
+           Some(b"llo".as_ref()));
+
1.51.0

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>where + P: SlicePattern<Item = T> + ?Sized, + T: PartialEq<T>,

Returns a subslice with the suffix removed.

+

If the slice ends with suffix, returns the subslice before the suffix, wrapped in Some. +If suffix is empty, simply returns the original slice.

+

If the slice does not end with suffix, returns None.

+
Examples
+
let v = &[10, 40, 30];
+assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
+assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
+assert_eq!(v.strip_suffix(&[50]), None);
+assert_eq!(v.strip_suffix(&[50, 30]), None);
+

Binary searches this slice for a given element. +If the slice is not sorted, the returned result is unspecified and +meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search_by, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+assert_eq!(s.binary_search(&13),  Ok(9));
+assert_eq!(s.binary_search(&4),   Err(7));
+assert_eq!(s.binary_search(&100), Err(13));
+let r = s.binary_search(&1);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+

If you want to find that whole range of matching items, rather than +an 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];
+
+let low = s.partition_point(|x| x < &1);
+assert_eq!(low, 1);
+let high = s.partition_point(|x| x <= &1);
+assert_eq!(high, 5);
+let r = s.binary_search(&1);
+assert!((low..high).contains(&r.unwrap()));
+
+assert!(s[..low].iter().all(|&x| x < 1));
+assert!(s[low..high].iter().all(|&x| x == 1));
+assert!(s[high..].iter().all(|&x| x > 1));
+
+// For something not found, the "range" of equal items is empty
+assert_eq!(s.partition_point(|x| x < &11), 9);
+assert_eq!(s.partition_point(|x| x <= &11), 9);
+assert_eq!(s.binary_search(&11), Err(9));
+

If you want to insert an item to a sorted vector, while maintaining +sort order, consider using partition_point:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+// The above is equivalent to `let idx = s.binary_search(&num).unwrap_or_else(|x| x);`
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+
1.0.0

pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>where + F: FnMut(&'a T) -> Ordering,

Binary searches this slice with a comparator function.

+

The comparator function should return an order code that indicates +whether its argument is Less, Equal or Greater the desired +target. +If the slice is not sorted or if the comparator function does not +implement an order consistent with the sort order of the underlying +slice, the returned result is unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by_key, and partition_point.

+
Examples
+

Looks up a series of four elements. The first is found, with a +uniquely determined position; the second and third are not +found; the fourth could match any position in [1, 4].

+ +
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+let seek = 13;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
+let seek = 4;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
+let seek = 100;
+assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
+let seek = 1;
+let r = s.binary_search_by(|probe| probe.cmp(&seek));
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.10.0

pub fn binary_search_by_key<'a, B, F>( + &'a self, + b: &B, + f: F +) -> Result<usize, usize>where + F: FnMut(&'a T) -> B, + B: Ord,

Binary searches this slice with a key extraction function.

+

Assumes that the slice is sorted by the key, for instance with +sort_by_key using the same key extraction function. +If the slice is not sorted by the key, the returned result is +unspecified and meaningless.

+

If the value is found then [Result::Ok] is returned, containing the +index of the matching element. If there are multiple matches, then any +one of the matches could be returned. The index is chosen +deterministically, but is subject to change in future versions of Rust. +If the value is not found then [Result::Err] is returned, containing +the index where a matching element could be inserted while maintaining +sorted order.

+

See also binary_search, binary_search_by, and partition_point.

+
Examples
+

Looks up a series of four elements in a slice of pairs sorted by +their second elements. The first is found, with a uniquely +determined position; the second and third are not found; the +fourth could match any position in [1, 4].

+ +
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
+         (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
+         (1, 21), (2, 34), (4, 55)];
+
+assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
+assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
+assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
+let r = s.binary_search_by_key(&1, |&(a, b)| b);
+assert!(match r { Ok(1..=4) => true, _ => false, });
+
1.20.0

pub fn sort_unstable(&mut self)where + T: Ord,

Sorts the slice, but might not preserve the order of equal elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(n * log(n)) worst-case.

+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

It is typically faster than stable sorting, except in a few special cases, e.g., when the +slice consists of several concatenated sorted sequences.

+
Examples
+
let mut v = [-5, 4, 1, -3, 2];
+
+v.sort_unstable();
+assert!(v == [-5, -3, 1, 2, 4]);
+
1.20.0

pub fn sort_unstable_by<F>(&mut self, compare: F)where + F: FnMut(&T, &T) -> Ordering,

Sorts the slice with a comparator function, but might not preserve the order of equal +elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(n * log(n)) worst-case.

+

The comparator function must define a total ordering for the elements in the slice. If +the ordering is not total, the order of the elements is unspecified. An order is a +total order if it is (for all a, b and c):

+
    +
  • total and antisymmetric: exactly one of a < b, a == b or a > b is true, and
  • +
  • transitive, a < b and b < c implies a < c. The same must hold for both == and >.
  • +
+

For example, while [f64] doesn’t implement [Ord] because NaN != NaN, we can use +partial_cmp as our sort function when we know the slice doesn’t contain a NaN.

+ +
let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
+floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
+assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

It is typically faster than stable sorting, except in a few special cases, e.g., when the +slice consists of several concatenated sorted sequences.

+
Examples
+
let mut v = [5, 4, 1, 3, 2];
+v.sort_unstable_by(|a, b| a.cmp(b));
+assert!(v == [1, 2, 3, 4, 5]);
+
+// reverse sorting
+v.sort_unstable_by(|a, b| b.cmp(a));
+assert!(v == [5, 4, 3, 2, 1]);
+
1.20.0

pub fn sort_unstable_by_key<K, F>(&mut self, f: F)where + F: FnMut(&T) -> K, + K: Ord,

Sorts the slice with a key extraction function, but might not preserve the order of equal +elements.

+

This sort is unstable (i.e., may reorder equal elements), in-place +(i.e., does not allocate), and O(m * n * log(n)) worst-case, where the key function is +O(m).

+
Current implementation
+

The current algorithm is based on pattern-defeating quicksort by Orson Peters, +which combines the fast average case of randomized quicksort with the fast worst case of +heapsort, while achieving linear time on slices with certain patterns. It uses some +randomization to avoid degenerate cases, but with a fixed seed to always provide +deterministic behavior.

+

Due to its key calling strategy, sort_unstable_by_key +is likely to be slower than sort_by_cached_key in +cases where the key function is expensive.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+v.sort_unstable_by_key(|k| k.abs());
+assert!(v == [1, 2, -3, 4, -5]);
+
1.49.0

pub fn select_nth_unstable( + &mut self, + index: usize +) -> (&mut [T], &mut T, &mut [T])where + T: Ord,

Reorder the slice such that the element at index is at its final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index. Additionally, this reordering is +unstable (i.e. any number of equal elements may end up at position index), in-place +(i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from the reordered slice: +the subslice prior to index, the element at index, and the subslice after index; +accordingly, the values in those two subslices will respectively all be less-than-or-equal-to +and greater-than-or-equal-to the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Find the median
+v.select_nth_unstable(2);
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [-3, -5, 1, 2, 4] ||
+        v == [-5, -3, 1, 2, 4] ||
+        v == [-3, -5, 1, 4, 2] ||
+        v == [-5, -3, 1, 4, 2]);
+
1.49.0

pub fn select_nth_unstable_by<F>( + &mut self, + index: usize, + compare: F +) -> (&mut [T], &mut T, &mut [T])where + F: FnMut(&T, &T) -> Ordering,

Reorder the slice with a comparator function such that the element at index is at its +final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index using the comparator function. +Additionally, this reordering is unstable (i.e. any number of equal elements may end up at +position index), in-place (i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from +the slice reordered according to the provided comparator function: the subslice prior to +index, the element at index, and the subslice after index; accordingly, the values in +those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to +the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Find the median as if the slice were sorted in descending order.
+v.select_nth_unstable_by(2, |a, b| b.cmp(a));
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [2, 4, 1, -5, -3] ||
+        v == [2, 4, 1, -3, -5] ||
+        v == [4, 2, 1, -5, -3] ||
+        v == [4, 2, 1, -3, -5]);
+
1.49.0

pub fn select_nth_unstable_by_key<K, F>( + &mut self, + index: usize, + f: F +) -> (&mut [T], &mut T, &mut [T])where + F: FnMut(&T) -> K, + K: Ord,

Reorder the slice with a key extraction function such that the element at index is at its +final sorted position.

+

This reordering has the additional property that any value at position i < index will be +less than or equal to any value at a position j > index using the key extraction function. +Additionally, this reordering is unstable (i.e. any number of equal elements may end up at +position index), in-place (i.e. does not allocate), and runs in O(n) time. +This function is also known as “kth element” in other libraries.

+

It returns a triplet of the following from +the slice reordered according to the provided key extraction function: the subslice prior to +index, the element at index, and the subslice after index; accordingly, the values in +those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to +the value of the element at index.

+
Current implementation
+

The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also +the basis for sort_unstable. The fallback algorithm is Median of Medians using Tukey’s Ninther for +pivot selection, which guarantees linear runtime for all inputs.

+
Panics
+

Panics when index >= len(), meaning it always panics on empty slices.

+
Examples
+
let mut v = [-5i32, 4, 1, -3, 2];
+
+// Return the median as if the array were sorted according to absolute value.
+v.select_nth_unstable_by_key(2, |a| a.abs());
+
+// We are only guaranteed the slice will be one of the following, based on the way we sort
+// about the specified index.
+assert!(v == [1, 2, -3, 4, -5] ||
+        v == [1, 2, -3, -5, 4] ||
+        v == [2, 1, -3, 4, -5] ||
+        v == [2, 1, -3, -5, 4]);
+

pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where + T: PartialEq<T>,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all consecutive repeated elements to the end of the slice according to the +[PartialEq] trait implementation.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
+
+let (dedup, duplicates) = slice.partition_dedup();
+
+assert_eq!(dedup, [1, 2, 3, 2, 1]);
+assert_eq!(duplicates, [2, 3, 1]);
+

pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])where + F: FnMut(&mut T, &mut T) -> bool,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice satisfying +a given equality relation.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

The same_bucket function is passed references to two elements from the slice and +must determine if the elements compare equal. The elements are passed in opposite order +from their order in the slice, so if same_bucket(a, b) returns true, a is moved +at the end of the slice.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
+
+let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
+
+assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
+assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
+

pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])where + F: FnMut(&mut T) -> K, + K: PartialEq<K>,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice that resolve +to the same key.

+

Returns two slices. The first contains no consecutive repeated elements. +The second contains all the duplicates in no specified order.

+

If the slice is sorted, the first returned slice contains no duplicates.

+
Examples
+
#![feature(slice_partition_dedup)]
+
+let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
+
+let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
+
+assert_eq!(dedup, [10, 20, 30, 20, 11]);
+assert_eq!(duplicates, [21, 30, 13]);
+
1.26.0

pub fn rotate_left(&mut self, mid: usize)

Rotates the slice in-place such that the first mid elements of the +slice move to the end while the last self.len() - mid elements move to +the front. After calling rotate_left, the element previously at index +mid will become the first element in the slice.

+
Panics
+

This function will panic if mid is greater than the length of the +slice. Note that mid == self.len() does not panic and is a no-op +rotation.

+
Complexity
+

Takes linear (in self.len()) time.

+
Examples
+
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a.rotate_left(2);
+assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
+

Rotating a subslice:

+ +
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a[1..5].rotate_left(1);
+assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
+
1.26.0

pub fn rotate_right(&mut self, k: usize)

Rotates the slice in-place such that the first self.len() - k +elements of the slice move to the end while the last k elements move +to the front. After calling rotate_right, the element previously at +index self.len() - k will become the first element in the slice.

+
Panics
+

This function will panic if k is greater than the length of the +slice. Note that k == self.len() does not panic and is a no-op +rotation.

+
Complexity
+

Takes linear (in self.len()) time.

+
Examples
+
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a.rotate_right(2);
+assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
+

Rotate a subslice:

+ +
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
+a[1..5].rotate_right(1);
+assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
+
1.50.0

pub fn fill(&mut self, value: T)where + T: Clone,

Fills self with elements by cloning value.

+
Examples
+
let mut buf = vec![0; 10];
+buf.fill(1);
+assert_eq!(buf, vec![1; 10]);
+
1.51.0

pub fn fill_with<F>(&mut self, f: F)where + F: FnMut() -> T,

Fills self with elements returned by calling a closure repeatedly.

+

This method uses a closure to create new values. If you’d rather +[Clone] a given value, use fill. If you want to use the [Default] +trait to generate values, you can pass [Default::default] as the +argument.

+
Examples
+
let mut buf = vec![1; 10];
+buf.fill_with(Default::default);
+assert_eq!(buf, vec![0; 10]);
+
1.7.0

pub fn clone_from_slice(&mut self, src: &[T])where + T: Clone,

Copies the elements from src into self.

+

The length of src must be the same as self.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Examples
+

Cloning two elements from a slice into another:

+ +
let src = [1, 2, 3, 4];
+let mut dst = [0, 0];
+
+// Because the slices have to be the same length,
+// we slice the source slice from four elements
+// to two. It will panic if we don't do this.
+dst.clone_from_slice(&src[2..]);
+
+assert_eq!(src, [1, 2, 3, 4]);
+assert_eq!(dst, [3, 4]);
+

Rust enforces that there can only be one mutable reference with no +immutable references to a particular piece of data in a particular +scope. Because of this, attempting to use clone_from_slice on a +single slice will result in a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+slice[..2].clone_from_slice(&slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.clone_from_slice(&right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 4, 5]);
+
1.9.0

pub fn copy_from_slice(&mut self, src: &[T])where + T: Copy,

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.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Examples
+

Copying two elements from a slice into another:

+ +
let src = [1, 2, 3, 4];
+let mut dst = [0, 0];
+
+// Because the slices have to be the same length,
+// we slice the source slice from four elements
+// to two. It will panic if we don't do this.
+dst.copy_from_slice(&src[2..]);
+
+assert_eq!(src, [1, 2, 3, 4]);
+assert_eq!(dst, [3, 4]);
+

Rust enforces that there can only be one mutable reference with no +immutable references to a particular piece of data in a particular +scope. Because of this, attempting to use copy_from_slice on a +single slice will result in a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+slice[..2].copy_from_slice(&slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.copy_from_slice(&right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 4, 5]);
+
1.37.0

pub fn copy_within<R>(&mut self, src: R, dest: usize)where + R: RangeBounds<usize>, + T: Copy,

Copies elements from one part of the slice to another part of itself, +using a memmove.

+

src is the range within self to copy from. dest is the starting +index of the range within self to copy to, which will have the same +length as src. The two ranges may overlap. The ends of the two ranges +must be less than or equal to self.len().

+
Panics
+

This function will panic if either range exceeds the end of the slice, +or if the end of src is before the start.

+
Examples
+

Copying four bytes within a slice:

+ +
let mut bytes = *b"Hello, World!";
+
+bytes.copy_within(1..5, 8);
+
+assert_eq!(&bytes, b"Hello, Wello!");
+
1.27.0

pub fn swap_with_slice(&mut self, other: &mut [T])

Swaps all elements in self with those in other.

+

The length of other must be the same as self.

+
Panics
+

This function will panic if the two slices have different lengths.

+
Example
+

Swapping two elements across slices:

+ +
let mut slice1 = [0, 0];
+let mut slice2 = [1, 2, 3, 4];
+
+slice1.swap_with_slice(&mut slice2[2..]);
+
+assert_eq!(slice1, [3, 4]);
+assert_eq!(slice2, [1, 2, 0, 0]);
+

Rust enforces that there can only be one mutable reference to a +particular piece of data in a particular scope. Because of this, +attempting to use swap_with_slice on a single slice will result in +a compile failure:

+ +
let mut slice = [1, 2, 3, 4, 5];
+slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
+

To work around this, we can use split_at_mut to create two distinct +mutable sub-slices from a slice:

+ +
let mut slice = [1, 2, 3, 4, 5];
+
+{
+    let (left, right) = slice.split_at_mut(2);
+    left.swap_with_slice(&mut right[1..]);
+}
+
+assert_eq!(slice, [4, 5, 3, 1, 2]);
+
1.30.0

pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])

Transmute the slice to a slice of another type, ensuring alignment of the types is +maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+
1.30.0

pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])

Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the +types is maintained.

+

This method splits the slice into three distinct slices: prefix, correctly aligned middle +slice of a new type, and the suffix slice. How exactly the slice is split up is not +specified; the middle part may be smaller than necessary. However, if this fails to return a +maximal middle part, that is because code is running in a context where performance does not +matter, such as a sanitizer attempting to find alignment bugs. Regular code running +in a default (debug or release) execution will return a maximal middle part.

+

This method has no purpose when either input element T or output element U are +zero-sized and will return the original slice without splitting anything.

+
Safety
+

This method is essentially a transmute with respect to the elements in the returned +middle slice, so all the usual caveats pertaining to transmute::<T, U> also apply here.

+
Examples
+

Basic usage:

+ +
unsafe {
+    let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
+    let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
+    // less_efficient_algorithm_for_bytes(prefix);
+    // more_efficient_algorithm_for_aligned_shorts(shorts);
+    // less_efficient_algorithm_for_bytes(suffix);
+}
+

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])where + Simd<T, LANES>: AsRef<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a slice into a prefix, a middle of aligned SIMD types, and a suffix.

+

This is a safe wrapper around [slice::align_to], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+
Examples
+
#![feature(portable_simd)]
+use core::simd::SimdFloat;
+
+let short = &[1, 2, 3];
+let (prefix, middle, suffix) = short.as_simd::<4>();
+assert_eq!(middle, []); // Not enough elements for anything in the middle
+
+// They might be split in any possible way between prefix and suffix
+let it = prefix.iter().chain(suffix).copied();
+assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
+
+fn basic_simd_sum(x: &[f32]) -> f32 {
+    use std::ops::Add;
+    use std::simd::f32x4;
+    let (prefix, middle, suffix) = x.as_simd();
+    let sums = f32x4::from_array([
+        prefix.iter().copied().sum(),
+        0.0,
+        0.0,
+        suffix.iter().copied().sum(),
+    ]);
+    let sums = middle.iter().copied().fold(sums, f32x4::add);
+    sums.reduce_sum()
+}
+
+let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
+assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
+

pub fn as_simd_mut<const LANES: usize>( + &mut self +) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])where + Simd<T, LANES>: AsMut<[T; LANES]>, + T: SimdElement, + LaneCount<LANES>: SupportedLaneCount,

🔬This is a nightly-only experimental API. (portable_simd)

Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, +and a mutable suffix.

+

This is a safe wrapper around [slice::align_to_mut], so has the same weak +postconditions as that method. You’re only assured that +self.len() == prefix.len() + middle.len() * LANES + suffix.len().

+

Notably, all of the following are possible:

+
    +
  • prefix.len() >= LANES.
  • +
  • middle.is_empty() despite self.len() >= 3 * LANES.
  • +
  • suffix.len() >= LANES.
  • +
+

That said, this is a safe method, so if you’re only writing safe code, +then this can at most cause incorrect logic, not unsoundness.

+

This is the mutable version of [slice::as_simd]; see that for examples.

+
Panics
+

This will panic if the size of the SIMD type is different from +LANES times that of the scalar.

+

At the time of writing, the trait restrictions on Simd<T, LANES> keeps +that from ever happening, as only power-of-two numbers of lanes are +supported. It’s possible that, in the future, those restrictions might +be lifted in a way that would make it possible to see panics from this +method for something like LANES == 3.

+

pub fn is_sorted(&self) -> boolwhere + T: PartialOrd<T>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted.

+

That is, for each element a and its following element b, a <= b must hold. If the +slice yields exactly zero or one element, true is returned.

+

Note that if Self::Item is only PartialOrd, but not Ord, the above definition +implies that this function returns false if any two consecutive items are not +comparable.

+
Examples
+
#![feature(is_sorted)]
+let empty: [i32; 0] = [];
+
+assert!([1, 2, 2, 9].is_sorted());
+assert!(![1, 3, 2, 4].is_sorted());
+assert!([0].is_sorted());
+assert!(empty.is_sorted());
+assert!(![0.0, 1.0, f32::NAN].is_sorted());
+

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> boolwhere + F: FnMut(&'a T, &'a T) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given comparator function.

+

Instead of using PartialOrd::partial_cmp, this function uses the given compare +function to determine the ordering of two elements. Apart from that, it’s equivalent to +is_sorted; see its documentation for more information.

+

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> boolwhere + F: FnMut(&'a T) -> K, + K: PartialOrd<K>,

🔬This is a nightly-only experimental API. (is_sorted)

Checks if the elements of this slice are sorted using the given key extraction function.

+

Instead of comparing the slice’s elements directly, this function compares the keys of the +elements, as determined by f. Apart from that, it’s equivalent to is_sorted; see its +documentation for more information.

+
Examples
+
#![feature(is_sorted)]
+
+assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
+assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
+
1.52.0

pub fn partition_point<P>(&self, pred: P) -> usizewhere + P: FnMut(&T) -> bool,

Returns the index of the partition point according to the given predicate +(the index of the first element of the second partition).

+

The slice is assumed to be partitioned according to the given predicate. +This means that all elements for which the predicate returns true are at the start of the slice +and all elements for which the predicate returns false are at the end. +For example, [7, 15, 3, 5, 4, 12, 6] is partitioned under the predicate x % 2 != 0 +(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, +as this method performs a kind of binary search.

+

See also binary_search, binary_search_by, and binary_search_by_key.

+
Examples
+
let v = [1, 2, 3, 3, 5, 6, 7];
+let i = v.partition_point(|&x| x < 5);
+
+assert_eq!(i, 4);
+assert!(v[..i].iter().all(|&x| x < 5));
+assert!(v[i..].iter().all(|&x| !(x < 5)));
+

If all elements of the slice match the predicate, including if the slice +is empty, then the length of the slice will be returned:

+ +
let a = [2, 4, 8];
+assert_eq!(a.partition_point(|x| x < &100), a.len());
+let a: [i32; 0] = [];
+assert_eq!(a.partition_point(|x| x < &100), 0);
+

If you want to insert an item to a sorted vector, while maintaining +sort order:

+ +
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+let num = 42;
+let idx = s.partition_point(|&x| x < num);
+s.insert(idx, num);
+assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
+

pub fn take<R, 'a>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where + R: OneSidedRange<usize>,

🔬This is a nightly-only experimental API. (slice_take)

Removes the subslice corresponding to the given range +and returns a reference to it.

+

Returns None and does not modify the slice if the given +range is out of bounds.

+

Note that this method only accepts one-sided ranges such as +2.. or ..6, but not 2..6.

+
Examples
+

Taking the first three elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+let mut first_three = slice.take(..3).unwrap();
+
+assert_eq!(slice, &['d']);
+assert_eq!(first_three, &['a', 'b', 'c']);
+

Taking the last two elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+let mut tail = slice.take(2..).unwrap();
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(tail, &['c', 'd']);
+

Getting None when range is out of bounds:

+ +
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c', 'd'];
+
+assert_eq!(None, slice.take(5..));
+assert_eq!(None, slice.take(..5));
+assert_eq!(None, slice.take(..=4));
+let expected: &[char] = &['a', 'b', 'c', 'd'];
+assert_eq!(Some(expected), slice.take(..4));
+

pub fn take_mut<R, 'a>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>where + R: OneSidedRange<usize>,

🔬This is a nightly-only experimental API. (slice_take)

Removes the subslice corresponding to the given range +and returns a mutable reference to it.

+

Returns None and does not modify the slice if the given +range is out of bounds.

+

Note that this method only accepts one-sided ranges such as +2.. or ..6, but not 2..6.

+
Examples
+

Taking the first three elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+let mut first_three = slice.take_mut(..3).unwrap();
+
+assert_eq!(slice, &mut ['d']);
+assert_eq!(first_three, &mut ['a', 'b', 'c']);
+

Taking the last two elements of a slice:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+let mut tail = slice.take_mut(2..).unwrap();
+
+assert_eq!(slice, &mut ['a', 'b']);
+assert_eq!(tail, &mut ['c', 'd']);
+

Getting None when range is out of bounds:

+ +
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+
+assert_eq!(None, slice.take_mut(5..));
+assert_eq!(None, slice.take_mut(..5));
+assert_eq!(None, slice.take_mut(..=4));
+let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
+assert_eq!(Some(expected), slice.take_mut(..4));
+

pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the first element of the slice and returns a reference +to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c'];
+let first = slice.take_first().unwrap();
+
+assert_eq!(slice, &['b', 'c']);
+assert_eq!(first, &'a');
+

pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the first element of the slice and returns a mutable +reference to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
+let first = slice.take_first_mut().unwrap();
+*first = 'd';
+
+assert_eq!(slice, &['b', 'c']);
+assert_eq!(first, &'d');
+

pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the last element of the slice and returns a reference +to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &[_] = &['a', 'b', 'c'];
+let last = slice.take_last().unwrap();
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(last, &'c');
+

pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>

🔬This is a nightly-only experimental API. (slice_take)

Removes the last element of the slice and returns a mutable +reference to it.

+

Returns None if the slice is empty.

+
Examples
+
#![feature(slice_take)]
+
+let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
+let last = slice.take_last_mut().unwrap();
+*last = 'd';
+
+assert_eq!(slice, &['a', 'b']);
+assert_eq!(last, &'d');
+

pub unsafe fn get_many_unchecked_mut<const N: usize>( + &mut self, + indices: [usize; N] +) -> [&mut T; N]

🔬This is a nightly-only experimental API. (get_many_mut)

Returns mutable references to many indices at once, without doing any checks.

+

For a safe alternative see get_many_mut.

+
Safety
+

Calling this method with overlapping or out-of-bounds indices is undefined behavior +even if the resulting references are not used.

+
Examples
+
#![feature(get_many_mut)]
+
+let x = &mut [1, 2, 4];
+
+unsafe {
+    let [a, b] = x.get_many_unchecked_mut([0, 2]);
+    *a *= 10;
+    *b *= 100;
+}
+assert_eq!(x, &[10, 2, 400]);
+

pub fn get_many_mut<const N: usize>( + &mut self, + indices: [usize; N] +) -> Result<[&mut T; N], GetManyMutError<N>>

🔬This is a nightly-only experimental API. (get_many_mut)

Returns mutable references to many indices at once.

+

Returns an error if any index is out-of-bounds, or if the same index was +passed more than once.

+
Examples
+
#![feature(get_many_mut)]
+
+let v = &mut [1, 2, 3];
+if let Ok([a, b]) = v.get_many_mut([0, 2]) {
+    *a = 413;
+    *b = 612;
+}
+assert_eq!(v, &[413, 2, 612]);
+

pub fn sort_floats(&mut self)

🔬This is a nightly-only experimental API. (sort_floats)

Sorts the slice of floats.

+

This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses +the ordering defined by [f32::total_cmp].

+
Current implementation
+

This uses the same sorting algorithm as sort_unstable_by.

+
Examples
+
#![feature(sort_floats)]
+let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
+
+v.sort_floats();
+let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
+assert_eq!(&v[..8], &sorted[..8]);
+assert!(v[8].is_nan());
+

pub fn sort_floats(&mut self)

🔬This is a nightly-only experimental API. (sort_floats)

Sorts the slice of floats.

+

This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses +the ordering defined by [f64::total_cmp].

+
Current implementation
+

This uses the same sorting algorithm as sort_unstable_by.

+
Examples
+
#![feature(sort_floats)]
+let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
+
+v.sort_floats();
+let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
+assert_eq!(&v[..8], &sorted[..8]);
+assert!(v[8].is_nan());
+

Trait Implementations§

source§

impl<T, const N: usize> AsMut<[T]> for Vec<T, N>

source§

fn as_mut(&mut self) -> &mut [T]

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N>

source§

fn as_mut(&mut self) -> &mut Self

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsRef<[T]> for Vec<T, N>

source§

fn as_ref(&self) -> &[T]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N>

source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<T, const N: usize> Clone for Vec<T, N>where + T: Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, const N: usize> Debug for Vec<T, N>where + T: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, const N: usize> Default for Vec<T, N>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<T, const N: usize> Deref for Vec<T, N>

§

type Target = [T]

The resulting type after dereferencing.
source§

fn deref(&self) -> &[T]

Dereferences the value.
source§

impl<T, const N: usize> DerefMut for Vec<T, N>

source§

fn deref_mut(&mut self) -> &mut [T]

Mutably dereferences the value.
source§

impl<T, const N: usize> Drop for Vec<T, N>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>where + T: 'a + Copy,

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = &'a T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> Extend<T> for Vec<T, N>

source§

fn extend<I>(&mut self, iter: I)where + I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T, const N: usize> FromIterator<T> for Vec<T, N>

source§

fn from_iter<I>(iter: I) -> Selfwhere + I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
source§

impl<T, const N: usize> Hash for Vec<T, N>where + T: Hash,

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given [Hasher]. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given [Hasher]. Read more
source§

impl<T, const N: usize> Hash for Vec<T, N>where + T: Hash,

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher.
source§

fn hash_slice<H>(data: &[Self], state: &mut H)where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher.
source§

impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> IntoIterator for Vec<T, N>

§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T, N>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<T, const N: usize> Ord for Vec<T, N>where + T: Ord,

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an [Ordering] between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Selfwhere + Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Selfwhere + Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&[B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&[B; M]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &&mut [B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &[B]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>where + A: PartialEq<B>,

source§

fn eq(&self, other: &[B; M]) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for &[B; M]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for [B; M]where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<A, N>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>where + A: PartialEq<B>,

source§

fn eq(&self, other: &Vec<B, N2>) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>where + T: PartialOrd,

source§

fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= +operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= +operator. Read more
source§

impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec<T, N>

§

type Error = ()

The type returned in the event of a conversion error.
source§

fn try_from(slice: &'a [T]) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl<const N: usize> Write for Vec<u8, N>

source§

fn write_str(&mut self, s: &str) -> Result

Writes a string slice into this writer, returning whether the write +succeeded. Read more
1.1.0§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a [char] into this writer, returning whether the write succeeded. Read more
1.0.0§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the [write!] macro with implementors of this trait. Read more
source§

impl<T, const N: usize> Eq for Vec<T, N>where + T: Eq,

Auto Trait Implementations§

§

impl<T, const N: usize> RefUnwindSafe for Vec<T, N>where + T: RefUnwindSafe,

§

impl<T, const N: usize> Send for Vec<T, N>where + T: Send,

§

impl<T, const N: usize> Sync for Vec<T, N>where + T: Sync,

§

impl<T, const N: usize> Unpin for Vec<T, N>where + T: Unpin,

§

impl<T, const N: usize> UnwindSafe for Vec<T, N>where + T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for Twhere + T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for Twhere + T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for Twhere + T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T, U> Into<U> for Twhere + U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +[From]<T> for U chooses to do.

+
§

impl<T, U> TryFrom<U> for Twhere + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for Twhere + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
\ No newline at end of file diff --git a/docs/doc/heapless/type.FnvIndexMap.html b/docs/doc/heapless/type.FnvIndexMap.html new file mode 100644 index 0000000..a0a716a --- /dev/null +++ b/docs/doc/heapless/type.FnvIndexMap.html @@ -0,0 +1,38 @@ +FnvIndexMap in heapless - Rust

Type Definition heapless::FnvIndexMap

source ·
pub type FnvIndexMap<K, V, const N: usize> = IndexMap<K, V, BuildHasherDefault<FnvHasher>, N>;
Expand description

A heapless::IndexMap using the default FNV hasher

+

A list of all Methods and Traits available for FnvIndexMap can be found in +the heapless::IndexMap documentation.

+

Examples

+
use heapless::FnvIndexMap;
+
+// A hash map with a capacity of 16 key-value pairs allocated on the stack
+let mut book_reviews = FnvIndexMap::<_, _, 16>::new();
+
+// review some books.
+book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.").unwrap();
+book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.").unwrap();
+book_reviews.insert("Pride and Prejudice",               "Very enjoyable.").unwrap();
+book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.").unwrap();
+
+// check for a specific one.
+if !book_reviews.contains_key("Les Misérables") {
+    println!("We've got {} reviews, but Les Misérables ain't one.",
+             book_reviews.len());
+}
+
+// oops, this review has a lot of spelling mistakes, let's delete it.
+book_reviews.remove("The Adventures of Sherlock Holmes");
+
+// look up the values associated with some keys.
+let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
+for book in &to_find {
+    match book_reviews.get(book) {
+        Some(review) => println!("{}: {}", book, review),
+        None => println!("{} is unreviewed.", book)
+    }
+}
+
+// iterate over everything.
+for (book, review) in &book_reviews {
+    println!("{}: \"{}\"", book, review);
+}
+
\ No newline at end of file diff --git a/docs/doc/heapless/type.FnvIndexSet.html b/docs/doc/heapless/type.FnvIndexSet.html new file mode 100644 index 0000000..be964ee --- /dev/null +++ b/docs/doc/heapless/type.FnvIndexSet.html @@ -0,0 +1,30 @@ +FnvIndexSet in heapless - Rust

Type Definition heapless::FnvIndexSet

source ·
pub type FnvIndexSet<T, const N: usize> = IndexSet<T, BuildHasherDefault<FnvHasher>, N>;
Expand description

A heapless::IndexSet using the +default FNV hasher. +A list of all Methods and Traits available for FnvIndexSet can be found in +the heapless::IndexSet documentation.

+

Examples

+
use heapless::FnvIndexSet;
+
+// A hash set with a capacity of 16 elements allocated on the stack
+let mut books = FnvIndexSet::<_, 16>::new();
+
+// Add some books.
+books.insert("A Dance With Dragons").unwrap();
+books.insert("To Kill a Mockingbird").unwrap();
+books.insert("The Odyssey").unwrap();
+books.insert("The Great Gatsby").unwrap();
+
+// Check for a specific one.
+if !books.contains("The Winds of Winter") {
+    println!("We have {} books, but The Winds of Winter ain't one.",
+             books.len());
+}
+
+// Remove a book.
+books.remove("The Odyssey");
+
+// Iterate over everything.
+for book in &books {
+    println!("{}", book);
+}
+
\ No newline at end of file diff --git a/docs/doc/heapless/vec/struct.Vec.html b/docs/doc/heapless/vec/struct.Vec.html new file mode 100644 index 0000000..92b036d --- /dev/null +++ b/docs/doc/heapless/vec/struct.Vec.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to ../../heapless/struct.Vec.html...

+ + + \ No newline at end of file diff --git a/docs/doc/implementors/byteorder/trait.ByteOrder.js b/docs/doc/implementors/byteorder/trait.ByteOrder.js new file mode 100644 index 0000000..7b4af58 --- /dev/null +++ b/docs/doc/implementors/byteorder/trait.ByteOrder.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"byteorder":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/clone/trait.Clone.js b/docs/doc/implementors/core/clone/trait.Clone.js index 1a8eecb..d11bdf3 100644 --- a/docs/doc/implementors/core/clone/trait.Clone.js +++ b/docs/doc/implementors/core/clone/trait.Clone.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl Clone for Base"],["impl Clone for ButtonSet"],["impl Clone for Color"]] +"arduboy_rust":[["impl Clone for ButtonSet"],["impl Clone for Color"],["impl Clone for Base"]], +"byteorder":[["impl Clone for LittleEndian"],["impl Clone for BigEndian"]], +"critical_section":[["impl Clone for RestoreState"],["impl<'cs> Clone for CriticalSection<'cs>"]], +"hash32":[["impl<H> Clone for BuildHasherDefault<H>where\n H: Default + Hasher,"]], +"heapless":[["impl<'a, T: Clone, const N: usize> Clone for OldestOrdered<'a, T, N>"],["impl Clone for LinkedIndexUsize"],["impl<T, S, const N: usize> Clone for IndexSet<T, S, N>where\n T: Eq + Hash + Clone,\n S: Clone,"],["impl Clone for LinkedIndexU16"],["impl Clone for LinkedIndexU8"],["impl<T, const N: usize> Clone for Deque<T, N>where\n T: Clone,"],["impl<T, const N: usize> Clone for Vec<T, N>where\n T: Clone,"],["impl<K, V, S, const N: usize> Clone for IndexMap<K, V, S, N>where\n K: Eq + Hash + Clone,\n V: Clone,\n S: Clone,"],["impl<T, K, const N: usize> Clone for BinaryHeap<T, K, N>where\n K: Kind,\n T: Ord + Clone,"],["impl<K, V, const N: usize> Clone for LinearMap<K, V, N>where\n K: Eq + Clone,\n V: Clone,"],["impl<const N: usize> Clone for String<N>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/cmp/trait.Eq.js b/docs/doc/implementors/core/cmp/trait.Eq.js index 541d599..d4c92eb 100644 --- a/docs/doc/implementors/core/cmp/trait.Eq.js +++ b/docs/doc/implementors/core/cmp/trait.Eq.js @@ -1,3 +1,6 @@ (function() {var implementors = { -"arduboy_rust":[["impl Eq for Base"],["impl Eq for ButtonSet"],["impl Eq for Color"]] +"arduboy_rust":[["impl Eq for Base"],["impl Eq for ButtonSet"],["impl Eq for Color"]], +"byteorder":[["impl Eq for BigEndian"],["impl Eq for LittleEndian"]], +"hash32":[["impl<H: Default + Hasher> Eq for BuildHasherDefault<H>"]], +"heapless":[["impl<K, V, S, const N: usize> Eq for IndexMap<K, V, S, N>where\n K: Eq + Hash,\n V: Eq,\n S: BuildHasher,"],["impl Eq for LinkedIndexU16"],["impl Eq for LinkedIndexUsize"],["impl Eq for LinkedIndexU8"],["impl<const N: usize> Eq for String<N>"],["impl<T, const N: usize> Eq for Vec<T, N>where\n T: Eq,"],["impl<K, V, const N: usize> Eq for LinearMap<K, V, N>where\n K: Eq,\n V: PartialEq,"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/cmp/trait.Ord.js b/docs/doc/implementors/core/cmp/trait.Ord.js index 806e9c8..44af7be 100644 --- a/docs/doc/implementors/core/cmp/trait.Ord.js +++ b/docs/doc/implementors/core/cmp/trait.Ord.js @@ -1,3 +1,5 @@ (function() {var implementors = { -"arduboy_rust":[["impl Ord for Base"],["impl Ord for ButtonSet"],["impl Ord for Color"]] +"arduboy_rust":[["impl Ord for ButtonSet"],["impl Ord for Base"],["impl Ord for Color"]], +"byteorder":[["impl Ord for BigEndian"],["impl Ord for LittleEndian"]], +"heapless":[["impl Ord for LinkedIndexU8"],["impl<const N: usize> Ord for String<N>"],["impl<T, const N: usize> Ord for Vec<T, N>where\n T: Ord,"],["impl Ord for LinkedIndexUsize"],["impl Ord for LinkedIndexU16"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/cmp/trait.PartialEq.js b/docs/doc/implementors/core/cmp/trait.PartialEq.js index 684e13b..bed470a 100644 --- a/docs/doc/implementors/core/cmp/trait.PartialEq.js +++ b/docs/doc/implementors/core/cmp/trait.PartialEq.js @@ -1,3 +1,6 @@ (function() {var implementors = { -"arduboy_rust":[["impl PartialEq<Base> for Base"],["impl PartialEq<ButtonSet> for ButtonSet"],["impl PartialEq<Color> for Color"]] +"arduboy_rust":[["impl PartialEq<ButtonSet> for ButtonSet"],["impl PartialEq<Base> for Base"],["impl PartialEq<Color> for Color"]], +"byteorder":[["impl PartialEq<BigEndian> for BigEndian"],["impl PartialEq<LittleEndian> for LittleEndian"]], +"hash32":[["impl<H> PartialEq<BuildHasherDefault<H>> for BuildHasherDefault<H>where\n H: Default + Hasher,"]], +"heapless":[["impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>where\n A: PartialEq<B>,"],["impl<const N1: usize, const N2: usize> PartialEq<String<N2>> for String<N1>"],["impl<K, V, S, S2, const N: usize, const N2: usize> PartialEq<IndexMap<K, V, S2, N2>> for IndexMap<K, V, S, N>where\n K: Eq + Hash,\n V: Eq,\n S: BuildHasher,\n S2: BuildHasher,"],["impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for &[B; M]where\n A: PartialEq<B>,"],["impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]where\n A: PartialEq<B>,"],["impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>where\n A: PartialEq<B>,"],["impl PartialEq<LinkedIndexUsize> for LinkedIndexUsize"],["impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>where\n A: PartialEq<B>,"],["impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]where\n A: PartialEq<B>,"],["impl<const N: usize> PartialEq<String<N>> for str"],["impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>where\n A: PartialEq<B>,"],["impl<T, S1, S2, const N1: usize, const N2: usize> PartialEq<IndexSet<T, S2, N2>> for IndexSet<T, S1, N1>where\n T: Eq + Hash,\n S1: BuildHasher,\n S2: BuildHasher,"],["impl PartialEq<LinkedIndexU8> for LinkedIndexU8"],["impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>where\n A: PartialEq<B>,"],["impl<const N: usize> PartialEq<String<N>> for &str"],["impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for [B; M]where\n A: PartialEq<B>,"],["impl<const N: usize> PartialEq<str> for String<N>"],["impl<K, V, const N: usize, const N2: usize> PartialEq<LinearMap<K, V, N2>> for LinearMap<K, V, N>where\n K: Eq,\n V: PartialEq,"],["impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]where\n A: PartialEq<B>,"],["impl<const N: usize> PartialEq<&str> for String<N>"],["impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>where\n A: PartialEq<B>,"],["impl PartialEq<LinkedIndexU16> for LinkedIndexU16"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/cmp/trait.PartialOrd.js b/docs/doc/implementors/core/cmp/trait.PartialOrd.js index 94d56bc..4ceff96 100644 --- a/docs/doc/implementors/core/cmp/trait.PartialOrd.js +++ b/docs/doc/implementors/core/cmp/trait.PartialOrd.js @@ -1,3 +1,5 @@ (function() {var implementors = { -"arduboy_rust":[["impl PartialOrd<Base> for Base"],["impl PartialOrd<Color> for Color"],["impl PartialOrd<ButtonSet> for ButtonSet"]] +"arduboy_rust":[["impl PartialOrd<Color> for Color"],["impl PartialOrd<ButtonSet> for ButtonSet"],["impl PartialOrd<Base> for Base"]], +"byteorder":[["impl PartialOrd<BigEndian> for BigEndian"],["impl PartialOrd<LittleEndian> for LittleEndian"]], +"heapless":[["impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>where\n T: PartialOrd,"],["impl PartialOrd<LinkedIndexUsize> for LinkedIndexUsize"],["impl PartialOrd<LinkedIndexU8> for LinkedIndexU8"],["impl<const N1: usize, const N2: usize> PartialOrd<String<N2>> for String<N1>"],["impl PartialOrd<LinkedIndexU16> for LinkedIndexU16"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/convert/trait.AsMut.js b/docs/doc/implementors/core/convert/trait.AsMut.js new file mode 100644 index 0000000..a1c22d0 --- /dev/null +++ b/docs/doc/implementors/core/convert/trait.AsMut.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<T, const N: usize> AsMut<[T]> for Vec<T, N>"],["impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/convert/trait.AsRef.js b/docs/doc/implementors/core/convert/trait.AsRef.js new file mode 100644 index 0000000..24cb7b3 --- /dev/null +++ b/docs/doc/implementors/core/convert/trait.AsRef.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<T, const N: usize> AsRef<[T]> for Vec<T, N>"],["impl<T, const N: usize> AsRef<[T]> for HistoryBuffer<T, N>"],["impl<const N: usize> AsRef<str> for String<N>"],["impl<const N: usize> AsRef<[u8]> for String<N>"],["impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/convert/trait.From.js b/docs/doc/implementors/core/convert/trait.From.js new file mode 100644 index 0000000..2f8ad6a --- /dev/null +++ b/docs/doc/implementors/core/convert/trait.From.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<const N: usize> From<i32> for String<N>"],["impl<const N: usize> From<u16> for String<N>"],["impl<const N: usize> From<i16> for String<N>"],["impl<'a, const N: usize> From<&'a str> for String<N>"],["impl<const N: usize> From<u64> for String<N>"],["impl<const N: usize> From<u32> for String<N>"],["impl<const N: usize> From<i64> for String<N>"],["impl<const N: usize> From<u8> for String<N>"],["impl<const N: usize> From<i8> for String<N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/convert/trait.TryFrom.js b/docs/doc/implementors/core/convert/trait.TryFrom.js new file mode 100644 index 0000000..8969d7f --- /dev/null +++ b/docs/doc/implementors/core/convert/trait.TryFrom.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec<T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/default/trait.Default.js b/docs/doc/implementors/core/default/trait.Default.js new file mode 100644 index 0000000..5410b5e --- /dev/null +++ b/docs/doc/implementors/core/default/trait.Default.js @@ -0,0 +1,5 @@ +(function() {var implementors = { +"byteorder":[["impl Default for BigEndian"],["impl Default for LittleEndian"]], +"hash32":[["impl Default for Hasher"],["impl Default for Hasher"],["impl<H> Default for BuildHasherDefault<H>where\n H: Default + Hasher,"]], +"heapless":[["impl<K, V, S, const N: usize> Default for IndexMap<K, V, S, N>where\n K: Eq + Hash,\n S: BuildHasher + Default,"],["impl<T, K, const N: usize> Default for BinaryHeap<T, K, N>where\n T: Ord,\n K: Kind,"],["impl<T, const N: usize> Default for Vec<T, N>"],["impl<const N: usize> Default for String<N>"],["impl<T, S, const N: usize> Default for IndexSet<T, S, N>where\n T: Eq + Hash,\n S: BuildHasher + Default,"],["impl<T, const N: usize> Default for Deque<T, N>"],["impl<T, const N: usize> Default for HistoryBuffer<T, N>"],["impl<K, V, const N: usize> Default for LinearMap<K, V, N>where\n K: Eq,"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/fmt/trait.Debug.js b/docs/doc/implementors/core/fmt/trait.Debug.js index 92316f0..5944617 100644 --- a/docs/doc/implementors/core/fmt/trait.Debug.js +++ b/docs/doc/implementors/core/fmt/trait.Debug.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl Debug for Base"],["impl Debug for Color"],["impl Debug for ButtonSet"]] +"arduboy_rust":[["impl Debug for Color"],["impl Debug for Base"],["impl Debug for ButtonSet"]], +"byteorder":[["impl Debug for BigEndian"],["impl Debug for LittleEndian"]], +"critical_section":[["impl<'cs> Debug for CriticalSection<'cs>"],["impl<T: Debug> Debug for Mutex<T>"],["impl Debug for RestoreState"]], +"hash32":[["impl<H: Default + Hasher> Debug for BuildHasherDefault<H>"]], +"heapless":[["impl Debug for LinkedIndexUsize"],["impl<K, V, const N: usize> Debug for LinearMap<K, V, N>where\n K: Eq + Debug,\n V: Debug,"],["impl<T, const N: usize> Debug for Vec<T, N>where\n T: Debug,"],["impl<T, Idx, K, const N: usize> Debug for SortedLinkedList<T, Idx, K, N>where\n T: Ord + Debug,\n Idx: SortedLinkedListIndex,\n K: Kind,"],["impl<T, S, const N: usize> Debug for IndexSet<T, S, N>where\n T: Eq + Hash + Debug,\n S: BuildHasher,"],["impl Debug for LinkedIndexU8"],["impl<T, const N: usize> Debug for HistoryBuffer<T, N>where\n T: Debug,"],["impl<T, K, const N: usize> Debug for BinaryHeap<T, K, N>where\n K: Kind,\n T: Ord + Debug,"],["impl<T: Debug, const N: usize> Debug for Deque<T, N>"],["impl<const N: usize> Debug for String<N>"],["impl Debug for LinkedIndexU16"],["impl<K, V, S, const N: usize> Debug for IndexMap<K, V, S, N>where\n K: Eq + Hash + Debug,\n V: Debug,\n S: BuildHasher,"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/fmt/trait.Display.js b/docs/doc/implementors/core/fmt/trait.Display.js new file mode 100644 index 0000000..92d48f0 --- /dev/null +++ b/docs/doc/implementors/core/fmt/trait.Display.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<const N: usize> Display for String<N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/fmt/trait.Write.js b/docs/doc/implementors/core/fmt/trait.Write.js new file mode 100644 index 0000000..6769c48 --- /dev/null +++ b/docs/doc/implementors/core/fmt/trait.Write.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<const N: usize> Write for String<N>"],["impl<const N: usize> Write for Vec<u8, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/hash/trait.Hash.js b/docs/doc/implementors/core/hash/trait.Hash.js index 70ecadf..4b51e9e 100644 --- a/docs/doc/implementors/core/hash/trait.Hash.js +++ b/docs/doc/implementors/core/hash/trait.Hash.js @@ -1,3 +1,5 @@ (function() {var implementors = { -"arduboy_rust":[["impl Hash for Base"],["impl Hash for ButtonSet"],["impl Hash for Color"]] +"arduboy_rust":[["impl Hash for ButtonSet"],["impl Hash for Color"],["impl Hash for Base"]], +"byteorder":[["impl Hash for LittleEndian"],["impl Hash for BigEndian"]], +"heapless":[["impl<T, const N: usize> Hash for Vec<T, N>where\n T: Hash,"],["impl<const N: usize> Hash for String<N>"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/iter/traits/collect/trait.Extend.js b/docs/doc/implementors/core/iter/traits/collect/trait.Extend.js new file mode 100644 index 0000000..1b0390c --- /dev/null +++ b/docs/doc/implementors/core/iter/traits/collect/trait.Extend.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<'a, T, S, const N: usize> Extend<&'a T> for IndexSet<T, S, N>where\n T: 'a + Eq + Hash + Copy,\n S: BuildHasher,"],["impl<T, const N: usize> Extend<T> for Vec<T, N>"],["impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>where\n T: 'a + Copy,"],["impl<K, V, S, const N: usize> Extend<(K, V)> for IndexMap<K, V, S, N>where\n K: Eq + Hash,\n S: BuildHasher,"],["impl<T, S, const N: usize> Extend<T> for IndexSet<T, S, N>where\n T: Eq + Hash,\n S: BuildHasher,"],["impl<'a, T, const N: usize> Extend<&'a T> for HistoryBuffer<T, N>where\n T: 'a + Clone,"],["impl<'a, K, V, S, const N: usize> Extend<(&'a K, &'a V)> for IndexMap<K, V, S, N>where\n K: Eq + Hash + Copy,\n V: Copy,\n S: BuildHasher,"],["impl<T, const N: usize> Extend<T> for HistoryBuffer<T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/iter/traits/collect/trait.FromIterator.js b/docs/doc/implementors/core/iter/traits/collect/trait.FromIterator.js new file mode 100644 index 0000000..f29cdd0 --- /dev/null +++ b/docs/doc/implementors/core/iter/traits/collect/trait.FromIterator.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<T, const N: usize> FromIterator<T> for Vec<T, N>"],["impl<'a, const N: usize> FromIterator<&'a char> for String<N>"],["impl<K, V, const N: usize> FromIterator<(K, V)> for LinearMap<K, V, N>where\n K: Eq,"],["impl<T, S, const N: usize> FromIterator<T> for IndexSet<T, S, N>where\n T: Eq + Hash,\n S: BuildHasher + Default,"],["impl<const N: usize> FromIterator<char> for String<N>"],["impl<K, V, S, const N: usize> FromIterator<(K, V)> for IndexMap<K, V, S, N>where\n K: Eq + Hash,\n S: BuildHasher + Default,"],["impl<'a, const N: usize> FromIterator<&'a str> for String<N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/iter/traits/collect/trait.IntoIterator.js b/docs/doc/implementors/core/iter/traits/collect/trait.IntoIterator.js new file mode 100644 index 0000000..0a79cdb --- /dev/null +++ b/docs/doc/implementors/core/iter/traits/collect/trait.IntoIterator.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N>"],["impl<T, const N: usize> IntoIterator for Deque<T, N>"],["impl<'a, T, const N: usize> IntoIterator for &'a Deque<T, N>"],["impl<'a, T, S, const N: usize> IntoIterator for &'a IndexSet<T, S, N>where\n T: Eq + Hash,\n S: BuildHasher,"],["impl<'a, K, V, const N: usize> IntoIterator for &'a LinearMap<K, V, N>where\n K: Eq,"],["impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N>"],["impl<'a, K, V, S, const N: usize> IntoIterator for &'a mut IndexMap<K, V, S, N>where\n K: Eq + Hash,\n S: BuildHasher,"],["impl<K, V, S, const N: usize> IntoIterator for IndexMap<K, V, S, N>where\n K: Eq + Hash,\n S: BuildHasher,"],["impl<'a, K, V, S, const N: usize> IntoIterator for &'a IndexMap<K, V, S, N>where\n K: Eq + Hash,\n S: BuildHasher,"],["impl<'a, T, const N: usize> IntoIterator for &'a mut Deque<T, N>"],["impl<T, const N: usize> IntoIterator for Vec<T, N>"],["impl<'a, T, K, const N: usize> IntoIterator for &'a BinaryHeap<T, K, N>where\n K: Kind,\n T: Ord,"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/iter/traits/iterator/trait.Iterator.js b/docs/doc/implementors/core/iter/traits/iterator/trait.Iterator.js new file mode 100644 index 0000000..69c0974 --- /dev/null +++ b/docs/doc/implementors/core/iter/traits/iterator/trait.Iterator.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<'a, T, Idx, K, const N: usize> Iterator for Iter<'a, T, Idx, K, N>where\n T: Ord,\n Idx: SortedLinkedListIndex,\n K: Kind,"],["impl<'a, T, const N: usize> Iterator for OldestOrdered<'a, T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.Copy.js b/docs/doc/implementors/core/marker/trait.Copy.js index 423ebea..8781938 100644 --- a/docs/doc/implementors/core/marker/trait.Copy.js +++ b/docs/doc/implementors/core/marker/trait.Copy.js @@ -1,3 +1,6 @@ (function() {var implementors = { -"arduboy_rust":[["impl Copy for ButtonSet"],["impl Copy for Color"],["impl Copy for Base"]] +"arduboy_rust":[["impl Copy for ButtonSet"],["impl Copy for Color"],["impl Copy for Base"]], +"byteorder":[["impl Copy for LittleEndian"],["impl Copy for BigEndian"]], +"critical_section":[["impl Copy for RestoreState"],["impl<'cs> Copy for CriticalSection<'cs>"]], +"heapless":[["impl Copy for LinkedIndexU8"],["impl Copy for LinkedIndexU16"],["impl Copy for LinkedIndexUsize"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.Freeze.js b/docs/doc/implementors/core/marker/trait.Freeze.js index 285aca7..455b12b 100644 --- a/docs/doc/implementors/core/marker/trait.Freeze.js +++ b/docs/doc/implementors/core/marker/trait.Freeze.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl Freeze for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Freeze for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Freeze for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Freeze for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Freeze for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Freeze for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Freeze for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Freeze for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Freeze for Base",1,["arduboy_rust::print::Base"]]] +"arduboy_rust":[["impl Freeze for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Freeze for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Freeze for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Freeze for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Freeze for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Freeze for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Freeze for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Freeze for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Freeze for Base",1,["arduboy_rust::print::Base"]]], +"byteorder":[["impl Freeze for BigEndian",1,["byteorder::BigEndian"]],["impl Freeze for LittleEndian",1,["byteorder::LittleEndian"]]], +"critical_section":[["impl<T> !Freeze for Mutex<T>",1,["critical_section::mutex::Mutex"]],["impl<'cs> Freeze for CriticalSection<'cs>",1,["critical_section::CriticalSection"]],["impl Freeze for RestoreState",1,["critical_section::RestoreState"]]], +"hash32":[["impl Freeze for Hasher",1,["hash32::fnv::Hasher"]],["impl Freeze for Hasher",1,["hash32::murmur3::Hasher"]],["impl<H> Freeze for BuildHasherDefault<H>",1,["hash32::BuildHasherDefault"]]], +"heapless":[["impl<T, const N: usize> Freeze for Deque<T, N>where\n T: Freeze,",1,["heapless::deque::Deque"]],["impl<T, const N: usize> Freeze for HistoryBuffer<T, N>where\n T: Freeze,",1,["heapless::histbuf::HistoryBuffer"]],["impl<'a, T, const N: usize> Freeze for OldestOrdered<'a, T, N>",1,["heapless::histbuf::OldestOrdered"]],["impl<'a, K, V, const N: usize> Freeze for Entry<'a, K, V, N>where\n K: Freeze,",1,["heapless::indexmap::Entry"]],["impl<'a, K, V, const N: usize> Freeze for OccupiedEntry<'a, K, V, N>where\n K: Freeze,",1,["heapless::indexmap::OccupiedEntry"]],["impl<'a, K, V, const N: usize> Freeze for VacantEntry<'a, K, V, N>where\n K: Freeze,",1,["heapless::indexmap::VacantEntry"]],["impl<K, V, S, const N: usize> Freeze for IndexMap<K, V, S, N>where\n K: Freeze,\n S: Freeze,\n V: Freeze,",1,["heapless::indexmap::IndexMap"]],["impl<T, S, const N: usize> Freeze for IndexSet<T, S, N>where\n S: Freeze,\n T: Freeze,",1,["heapless::indexset::IndexSet"]],["impl<K, V, const N: usize> Freeze for LinearMap<K, V, N>where\n K: Freeze,\n V: Freeze,",1,["heapless::linear_map::LinearMap"]],["impl<const N: usize> Freeze for String<N>",1,["heapless::string::String"]],["impl<T, const N: usize> Freeze for Vec<T, N>where\n T: Freeze,",1,["heapless::vec::Vec"]],["impl Freeze for Min",1,["heapless::binary_heap::Min"]],["impl Freeze for Max",1,["heapless::binary_heap::Max"]],["impl<T, K, const N: usize> Freeze for BinaryHeap<T, K, N>where\n T: Freeze,",1,["heapless::binary_heap::BinaryHeap"]],["impl<'a, T, K, const N: usize> Freeze for PeekMut<'a, T, K, N>",1,["heapless::binary_heap::PeekMut"]],["impl Freeze for Min",1,["heapless::sorted_linked_list::Min"]],["impl Freeze for Max",1,["heapless::sorted_linked_list::Max"]],["impl<T, Idx> Freeze for Node<T, Idx>where\n Idx: Freeze,\n T: Freeze,",1,["heapless::sorted_linked_list::Node"]],["impl<T, Idx, K, const N: usize> Freeze for SortedLinkedList<T, Idx, K, N>where\n Idx: Freeze,\n T: Freeze,",1,["heapless::sorted_linked_list::SortedLinkedList"]],["impl Freeze for LinkedIndexU8",1,["heapless::sorted_linked_list::LinkedIndexU8"]],["impl Freeze for LinkedIndexU16",1,["heapless::sorted_linked_list::LinkedIndexU16"]],["impl Freeze for LinkedIndexUsize",1,["heapless::sorted_linked_list::LinkedIndexUsize"]],["impl<'a, T, Idx, K, const N: usize> Freeze for Iter<'a, T, Idx, K, N>where\n Idx: Freeze,",1,["heapless::sorted_linked_list::Iter"]],["impl<'a, T, Idx, K, const N: usize> Freeze for FindMut<'a, T, Idx, K, N>where\n Idx: Freeze,",1,["heapless::sorted_linked_list::FindMut"]]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.Send.js b/docs/doc/implementors/core/marker/trait.Send.js index c3ff268..9c9e871 100644 --- a/docs/doc/implementors/core/marker/trait.Send.js +++ b/docs/doc/implementors/core/marker/trait.Send.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl Send for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Send for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Send for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Send for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Send for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Send for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Send for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Send for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Send for Base",1,["arduboy_rust::print::Base"]]] +"arduboy_rust":[["impl Send for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Send for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Send for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Send for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Send for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Send for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Send for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Send for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Send for Base",1,["arduboy_rust::print::Base"]]], +"byteorder":[["impl Send for BigEndian",1,["byteorder::BigEndian"]],["impl Send for LittleEndian",1,["byteorder::LittleEndian"]]], +"critical_section":[["impl<T> Send for Mutex<T>where\n T: Send,",1,["critical_section::mutex::Mutex"]],["impl<'cs> Send for CriticalSection<'cs>",1,["critical_section::CriticalSection"]],["impl Send for RestoreState",1,["critical_section::RestoreState"]]], +"hash32":[["impl Send for Hasher",1,["hash32::fnv::Hasher"]],["impl Send for Hasher",1,["hash32::murmur3::Hasher"]],["impl<H> Send for BuildHasherDefault<H>where\n H: Send,",1,["hash32::BuildHasherDefault"]]], +"heapless":[["impl<T, const N: usize> Send for Deque<T, N>where\n T: Send,",1,["heapless::deque::Deque"]],["impl<T, const N: usize> Send for HistoryBuffer<T, N>where\n T: Send,",1,["heapless::histbuf::HistoryBuffer"]],["impl<'a, T, const N: usize> Send for OldestOrdered<'a, T, N>where\n T: Sync,",1,["heapless::histbuf::OldestOrdered"]],["impl<'a, K, V, const N: usize> Send for Entry<'a, K, V, N>where\n K: Send,\n V: Send,",1,["heapless::indexmap::Entry"]],["impl<'a, K, V, const N: usize> Send for OccupiedEntry<'a, K, V, N>where\n K: Send,\n V: Send,",1,["heapless::indexmap::OccupiedEntry"]],["impl<'a, K, V, const N: usize> Send for VacantEntry<'a, K, V, N>where\n K: Send,\n V: Send,",1,["heapless::indexmap::VacantEntry"]],["impl<K, V, S, const N: usize> Send for IndexMap<K, V, S, N>where\n K: Send,\n S: Send,\n V: Send,",1,["heapless::indexmap::IndexMap"]],["impl<T, S, const N: usize> Send for IndexSet<T, S, N>where\n S: Send,\n T: Send,",1,["heapless::indexset::IndexSet"]],["impl<K, V, const N: usize> Send for LinearMap<K, V, N>where\n K: Send,\n V: Send,",1,["heapless::linear_map::LinearMap"]],["impl<const N: usize> Send for String<N>",1,["heapless::string::String"]],["impl<T, const N: usize> Send for Vec<T, N>where\n T: Send,",1,["heapless::vec::Vec"]],["impl Send for Min",1,["heapless::binary_heap::Min"]],["impl Send for Max",1,["heapless::binary_heap::Max"]],["impl<T, K, const N: usize> Send for BinaryHeap<T, K, N>where\n K: Send,\n T: Send,",1,["heapless::binary_heap::BinaryHeap"]],["impl<'a, T, K, const N: usize> Send for PeekMut<'a, T, K, N>where\n K: Send,\n T: Send,",1,["heapless::binary_heap::PeekMut"]],["impl Send for Min",1,["heapless::sorted_linked_list::Min"]],["impl Send for Max",1,["heapless::sorted_linked_list::Max"]],["impl<T, Idx> Send for Node<T, Idx>where\n Idx: Send,\n T: Send,",1,["heapless::sorted_linked_list::Node"]],["impl<T, Idx, K, const N: usize> Send for SortedLinkedList<T, Idx, K, N>where\n Idx: Send,\n K: Send,\n T: Send,",1,["heapless::sorted_linked_list::SortedLinkedList"]],["impl Send for LinkedIndexU8",1,["heapless::sorted_linked_list::LinkedIndexU8"]],["impl Send for LinkedIndexU16",1,["heapless::sorted_linked_list::LinkedIndexU16"]],["impl Send for LinkedIndexUsize",1,["heapless::sorted_linked_list::LinkedIndexUsize"]],["impl<'a, T, Idx, K, const N: usize> Send for Iter<'a, T, Idx, K, N>where\n Idx: Send + Sync,\n K: Sync,\n T: Sync,",1,["heapless::sorted_linked_list::Iter"]],["impl<'a, T, Idx, K, const N: usize> Send for FindMut<'a, T, Idx, K, N>where\n Idx: Send,\n K: Send,\n T: Send,",1,["heapless::sorted_linked_list::FindMut"]]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.StructuralEq.js b/docs/doc/implementors/core/marker/trait.StructuralEq.js index 33d7c4e..6f448ac 100644 --- a/docs/doc/implementors/core/marker/trait.StructuralEq.js +++ b/docs/doc/implementors/core/marker/trait.StructuralEq.js @@ -1,3 +1,5 @@ (function() {var implementors = { -"arduboy_rust":[["impl StructuralEq for Color"],["impl StructuralEq for Base"],["impl StructuralEq for ButtonSet"]] +"arduboy_rust":[["impl StructuralEq for Color"],["impl StructuralEq for Base"],["impl StructuralEq for ButtonSet"]], +"byteorder":[["impl StructuralEq for LittleEndian"],["impl StructuralEq for BigEndian"]], +"heapless":[["impl StructuralEq for LinkedIndexU16"],["impl StructuralEq for LinkedIndexUsize"],["impl StructuralEq for LinkedIndexU8"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.StructuralPartialEq.js b/docs/doc/implementors/core/marker/trait.StructuralPartialEq.js index 792b501..54777a6 100644 --- a/docs/doc/implementors/core/marker/trait.StructuralPartialEq.js +++ b/docs/doc/implementors/core/marker/trait.StructuralPartialEq.js @@ -1,3 +1,5 @@ (function() {var implementors = { -"arduboy_rust":[["impl StructuralPartialEq for Base"],["impl StructuralPartialEq for Color"],["impl StructuralPartialEq for ButtonSet"]] +"arduboy_rust":[["impl StructuralPartialEq for ButtonSet"],["impl StructuralPartialEq for Color"],["impl StructuralPartialEq for Base"]], +"byteorder":[["impl StructuralPartialEq for LittleEndian"],["impl StructuralPartialEq for BigEndian"]], +"heapless":[["impl StructuralPartialEq for LinkedIndexUsize"],["impl StructuralPartialEq for LinkedIndexU8"],["impl StructuralPartialEq for LinkedIndexU16"]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.Sync.js b/docs/doc/implementors/core/marker/trait.Sync.js index 3319216..c5f326a 100644 --- a/docs/doc/implementors/core/marker/trait.Sync.js +++ b/docs/doc/implementors/core/marker/trait.Sync.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl Sync for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Sync for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Sync for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Sync for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Sync for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Sync for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Sync for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Sync for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Sync for Base",1,["arduboy_rust::print::Base"]]] +"arduboy_rust":[["impl Sync for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Sync for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Sync for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Sync for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Sync for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Sync for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Sync for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Sync for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Sync for Base",1,["arduboy_rust::print::Base"]]], +"byteorder":[["impl Sync for BigEndian",1,["byteorder::BigEndian"]],["impl Sync for LittleEndian",1,["byteorder::LittleEndian"]]], +"critical_section":[["impl<'cs> Sync for CriticalSection<'cs>",1,["critical_section::CriticalSection"]],["impl Sync for RestoreState",1,["critical_section::RestoreState"]],["impl<T> Sync for Mutex<T>where\n T: Send,"]], +"hash32":[["impl Sync for Hasher",1,["hash32::fnv::Hasher"]],["impl Sync for Hasher",1,["hash32::murmur3::Hasher"]],["impl<H> Sync for BuildHasherDefault<H>where\n H: Sync,",1,["hash32::BuildHasherDefault"]]], +"heapless":[["impl<T, const N: usize> Sync for Deque<T, N>where\n T: Sync,",1,["heapless::deque::Deque"]],["impl<T, const N: usize> Sync for HistoryBuffer<T, N>where\n T: Sync,",1,["heapless::histbuf::HistoryBuffer"]],["impl<'a, T, const N: usize> Sync for OldestOrdered<'a, T, N>where\n T: Sync,",1,["heapless::histbuf::OldestOrdered"]],["impl<'a, K, V, const N: usize> Sync for Entry<'a, K, V, N>where\n K: Sync,\n V: Sync,",1,["heapless::indexmap::Entry"]],["impl<'a, K, V, const N: usize> Sync for OccupiedEntry<'a, K, V, N>where\n K: Sync,\n V: Sync,",1,["heapless::indexmap::OccupiedEntry"]],["impl<'a, K, V, const N: usize> Sync for VacantEntry<'a, K, V, N>where\n K: Sync,\n V: Sync,",1,["heapless::indexmap::VacantEntry"]],["impl<K, V, S, const N: usize> Sync for IndexMap<K, V, S, N>where\n K: Sync,\n S: Sync,\n V: Sync,",1,["heapless::indexmap::IndexMap"]],["impl<T, S, const N: usize> Sync for IndexSet<T, S, N>where\n S: Sync,\n T: Sync,",1,["heapless::indexset::IndexSet"]],["impl<K, V, const N: usize> Sync for LinearMap<K, V, N>where\n K: Sync,\n V: Sync,",1,["heapless::linear_map::LinearMap"]],["impl<const N: usize> Sync for String<N>",1,["heapless::string::String"]],["impl<T, const N: usize> Sync for Vec<T, N>where\n T: Sync,",1,["heapless::vec::Vec"]],["impl Sync for Min",1,["heapless::binary_heap::Min"]],["impl Sync for Max",1,["heapless::binary_heap::Max"]],["impl<T, K, const N: usize> Sync for BinaryHeap<T, K, N>where\n K: Sync,\n T: Sync,",1,["heapless::binary_heap::BinaryHeap"]],["impl<'a, T, K, const N: usize> Sync for PeekMut<'a, T, K, N>where\n K: Sync,\n T: Sync,",1,["heapless::binary_heap::PeekMut"]],["impl Sync for Min",1,["heapless::sorted_linked_list::Min"]],["impl Sync for Max",1,["heapless::sorted_linked_list::Max"]],["impl<T, Idx> Sync for Node<T, Idx>where\n Idx: Sync,\n T: Sync,",1,["heapless::sorted_linked_list::Node"]],["impl<T, Idx, K, const N: usize> Sync for SortedLinkedList<T, Idx, K, N>where\n Idx: Sync,\n K: Sync,\n T: Sync,",1,["heapless::sorted_linked_list::SortedLinkedList"]],["impl Sync for LinkedIndexU8",1,["heapless::sorted_linked_list::LinkedIndexU8"]],["impl Sync for LinkedIndexU16",1,["heapless::sorted_linked_list::LinkedIndexU16"]],["impl Sync for LinkedIndexUsize",1,["heapless::sorted_linked_list::LinkedIndexUsize"]],["impl<'a, T, Idx, K, const N: usize> Sync for Iter<'a, T, Idx, K, N>where\n Idx: Sync,\n K: Sync,\n T: Sync,",1,["heapless::sorted_linked_list::Iter"]],["impl<'a, T, Idx, K, const N: usize> Sync for FindMut<'a, T, Idx, K, N>where\n Idx: Sync,\n K: Sync,\n T: Sync,",1,["heapless::sorted_linked_list::FindMut"]]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/marker/trait.Unpin.js b/docs/doc/implementors/core/marker/trait.Unpin.js index a3db3ab..0083908 100644 --- a/docs/doc/implementors/core/marker/trait.Unpin.js +++ b/docs/doc/implementors/core/marker/trait.Unpin.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl Unpin for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Unpin for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Unpin for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Unpin for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Unpin for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Unpin for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Unpin for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Unpin for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Unpin for Base",1,["arduboy_rust::print::Base"]]] +"arduboy_rust":[["impl Unpin for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl Unpin for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl Unpin for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl Unpin for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl Unpin for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl Unpin for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl Unpin for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl Unpin for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl Unpin for Base",1,["arduboy_rust::print::Base"]]], +"byteorder":[["impl Unpin for BigEndian",1,["byteorder::BigEndian"]],["impl Unpin for LittleEndian",1,["byteorder::LittleEndian"]]], +"critical_section":[["impl<T> Unpin for Mutex<T>where\n T: Unpin,",1,["critical_section::mutex::Mutex"]],["impl<'cs> Unpin for CriticalSection<'cs>",1,["critical_section::CriticalSection"]],["impl Unpin for RestoreState",1,["critical_section::RestoreState"]]], +"hash32":[["impl Unpin for Hasher",1,["hash32::fnv::Hasher"]],["impl Unpin for Hasher",1,["hash32::murmur3::Hasher"]],["impl<H> Unpin for BuildHasherDefault<H>where\n H: Unpin,",1,["hash32::BuildHasherDefault"]]], +"heapless":[["impl<T, const N: usize> Unpin for Deque<T, N>where\n T: Unpin,",1,["heapless::deque::Deque"]],["impl<T, const N: usize> Unpin for HistoryBuffer<T, N>where\n T: Unpin,",1,["heapless::histbuf::HistoryBuffer"]],["impl<'a, T, const N: usize> Unpin for OldestOrdered<'a, T, N>",1,["heapless::histbuf::OldestOrdered"]],["impl<'a, K, V, const N: usize> Unpin for Entry<'a, K, V, N>where\n K: Unpin,",1,["heapless::indexmap::Entry"]],["impl<'a, K, V, const N: usize> Unpin for OccupiedEntry<'a, K, V, N>where\n K: Unpin,",1,["heapless::indexmap::OccupiedEntry"]],["impl<'a, K, V, const N: usize> Unpin for VacantEntry<'a, K, V, N>where\n K: Unpin,",1,["heapless::indexmap::VacantEntry"]],["impl<K, V, S, const N: usize> Unpin for IndexMap<K, V, S, N>where\n K: Unpin,\n S: Unpin,\n V: Unpin,",1,["heapless::indexmap::IndexMap"]],["impl<T, S, const N: usize> Unpin for IndexSet<T, S, N>where\n S: Unpin,\n T: Unpin,",1,["heapless::indexset::IndexSet"]],["impl<K, V, const N: usize> Unpin for LinearMap<K, V, N>where\n K: Unpin,\n V: Unpin,",1,["heapless::linear_map::LinearMap"]],["impl<const N: usize> Unpin for String<N>",1,["heapless::string::String"]],["impl<T, const N: usize> Unpin for Vec<T, N>where\n T: Unpin,",1,["heapless::vec::Vec"]],["impl Unpin for Min",1,["heapless::binary_heap::Min"]],["impl Unpin for Max",1,["heapless::binary_heap::Max"]],["impl<T, K, const N: usize> Unpin for BinaryHeap<T, K, N>where\n K: Unpin,\n T: Unpin,",1,["heapless::binary_heap::BinaryHeap"]],["impl<'a, T, K, const N: usize> Unpin for PeekMut<'a, T, K, N>",1,["heapless::binary_heap::PeekMut"]],["impl Unpin for Min",1,["heapless::sorted_linked_list::Min"]],["impl Unpin for Max",1,["heapless::sorted_linked_list::Max"]],["impl<T, Idx> Unpin for Node<T, Idx>where\n Idx: Unpin,\n T: Unpin,",1,["heapless::sorted_linked_list::Node"]],["impl<T, Idx, K, const N: usize> Unpin for SortedLinkedList<T, Idx, K, N>where\n Idx: Unpin,\n K: Unpin,\n T: Unpin,",1,["heapless::sorted_linked_list::SortedLinkedList"]],["impl Unpin for LinkedIndexU8",1,["heapless::sorted_linked_list::LinkedIndexU8"]],["impl Unpin for LinkedIndexU16",1,["heapless::sorted_linked_list::LinkedIndexU16"]],["impl Unpin for LinkedIndexUsize",1,["heapless::sorted_linked_list::LinkedIndexUsize"]],["impl<'a, T, Idx, K, const N: usize> Unpin for Iter<'a, T, Idx, K, N>where\n Idx: Unpin,",1,["heapless::sorted_linked_list::Iter"]],["impl<'a, T, Idx, K, const N: usize> Unpin for FindMut<'a, T, Idx, K, N>where\n Idx: Unpin,",1,["heapless::sorted_linked_list::FindMut"]]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/ops/deref/trait.Deref.js b/docs/doc/implementors/core/ops/deref/trait.Deref.js new file mode 100644 index 0000000..b8fa81f --- /dev/null +++ b/docs/doc/implementors/core/ops/deref/trait.Deref.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<T, const N: usize> Deref for HistoryBuffer<T, N>"],["impl<T, Idx, K, const N: usize> Deref for FindMut<'_, T, Idx, K, N>where\n T: Ord,\n Idx: SortedLinkedListIndex,\n K: Kind,"],["impl<const N: usize> Deref for String<N>"],["impl<T, K, const N: usize> Deref for PeekMut<'_, T, K, N>where\n T: Ord,\n K: Kind,"],["impl<T, const N: usize> Deref for Vec<T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/ops/deref/trait.DerefMut.js b/docs/doc/implementors/core/ops/deref/trait.DerefMut.js new file mode 100644 index 0000000..91636e7 --- /dev/null +++ b/docs/doc/implementors/core/ops/deref/trait.DerefMut.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<const N: usize> DerefMut for String<N>"],["impl<T, const N: usize> DerefMut for Vec<T, N>"],["impl<T, Idx, K, const N: usize> DerefMut for FindMut<'_, T, Idx, K, N>where\n T: Ord,\n Idx: SortedLinkedListIndex,\n K: Kind,"],["impl<T, K, const N: usize> DerefMut for PeekMut<'_, T, K, N>where\n T: Ord,\n K: Kind,"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/ops/drop/trait.Drop.js b/docs/doc/implementors/core/ops/drop/trait.Drop.js new file mode 100644 index 0000000..bdd46f2 --- /dev/null +++ b/docs/doc/implementors/core/ops/drop/trait.Drop.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<T, Idx, K, const N: usize> Drop for FindMut<'_, T, Idx, K, N>where\n T: Ord,\n Idx: SortedLinkedListIndex,\n K: Kind,"],["impl<T, Idx, K, const N: usize> Drop for SortedLinkedList<T, Idx, K, N>where\n Idx: SortedLinkedListIndex,"],["impl<T, const N: usize> Drop for HistoryBuffer<T, N>"],["impl<T, K, const N: usize> Drop for PeekMut<'_, T, K, N>where\n T: Ord,\n K: Kind,"],["impl<T, const N: usize> Drop for Vec<T, N>"],["impl<K, V, const N: usize> Drop for LinearMap<K, V, N>"],["impl<T, const N: usize> Drop for Deque<T, N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/ops/index/trait.Index.js b/docs/doc/implementors/core/ops/index/trait.Index.js new file mode 100644 index 0000000..f839766 --- /dev/null +++ b/docs/doc/implementors/core/ops/index/trait.Index.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<'a, K, V, Q, const N: usize> Index<&'a Q> for LinearMap<K, V, N>where\n K: Borrow<Q> + Eq,\n Q: Eq + ?Sized,"],["impl<'a, K, Q, V, S, const N: usize> Index<&'a Q> for IndexMap<K, V, S, N>where\n K: Eq + Hash + Borrow<Q>,\n Q: ?Sized + Eq + Hash,\n S: BuildHasher,"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/ops/index/trait.IndexMut.js b/docs/doc/implementors/core/ops/index/trait.IndexMut.js new file mode 100644 index 0000000..5b1bdd9 --- /dev/null +++ b/docs/doc/implementors/core/ops/index/trait.IndexMut.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<'a, K, Q, V, S, const N: usize> IndexMut<&'a Q> for IndexMap<K, V, S, N>where\n K: Eq + Hash + Borrow<Q>,\n Q: ?Sized + Eq + Hash,\n S: BuildHasher,"],["impl<'a, K, V, Q, const N: usize> IndexMut<&'a Q> for LinearMap<K, V, N>where\n K: Borrow<Q> + Eq,\n Q: Eq + ?Sized,"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/panic/unwind_safe/trait.RefUnwindSafe.js b/docs/doc/implementors/core/panic/unwind_safe/trait.RefUnwindSafe.js index 1b0ed29..b35b39b 100644 --- a/docs/doc/implementors/core/panic/unwind_safe/trait.RefUnwindSafe.js +++ b/docs/doc/implementors/core/panic/unwind_safe/trait.RefUnwindSafe.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl RefUnwindSafe for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl RefUnwindSafe for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl RefUnwindSafe for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl RefUnwindSafe for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl RefUnwindSafe for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl RefUnwindSafe for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl RefUnwindSafe for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl RefUnwindSafe for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl RefUnwindSafe for Base",1,["arduboy_rust::print::Base"]]] +"arduboy_rust":[["impl RefUnwindSafe for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl RefUnwindSafe for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl RefUnwindSafe for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl RefUnwindSafe for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl RefUnwindSafe for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl RefUnwindSafe for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl RefUnwindSafe for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl RefUnwindSafe for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl RefUnwindSafe for Base",1,["arduboy_rust::print::Base"]]], +"byteorder":[["impl RefUnwindSafe for BigEndian",1,["byteorder::BigEndian"]],["impl RefUnwindSafe for LittleEndian",1,["byteorder::LittleEndian"]]], +"critical_section":[["impl<T> !RefUnwindSafe for Mutex<T>",1,["critical_section::mutex::Mutex"]],["impl<'cs> RefUnwindSafe for CriticalSection<'cs>",1,["critical_section::CriticalSection"]],["impl RefUnwindSafe for RestoreState",1,["critical_section::RestoreState"]]], +"hash32":[["impl RefUnwindSafe for Hasher",1,["hash32::fnv::Hasher"]],["impl RefUnwindSafe for Hasher",1,["hash32::murmur3::Hasher"]],["impl<H> RefUnwindSafe for BuildHasherDefault<H>where\n H: RefUnwindSafe,",1,["hash32::BuildHasherDefault"]]], +"heapless":[["impl<T, const N: usize> RefUnwindSafe for Deque<T, N>where\n T: RefUnwindSafe,",1,["heapless::deque::Deque"]],["impl<T, const N: usize> RefUnwindSafe for HistoryBuffer<T, N>where\n T: RefUnwindSafe,",1,["heapless::histbuf::HistoryBuffer"]],["impl<'a, T, const N: usize> RefUnwindSafe for OldestOrdered<'a, T, N>where\n T: RefUnwindSafe,",1,["heapless::histbuf::OldestOrdered"]],["impl<'a, K, V, const N: usize> RefUnwindSafe for Entry<'a, K, V, N>where\n K: RefUnwindSafe,\n V: RefUnwindSafe,",1,["heapless::indexmap::Entry"]],["impl<'a, K, V, const N: usize> RefUnwindSafe for OccupiedEntry<'a, K, V, N>where\n K: RefUnwindSafe,\n V: RefUnwindSafe,",1,["heapless::indexmap::OccupiedEntry"]],["impl<'a, K, V, const N: usize> RefUnwindSafe for VacantEntry<'a, K, V, N>where\n K: RefUnwindSafe,\n V: RefUnwindSafe,",1,["heapless::indexmap::VacantEntry"]],["impl<K, V, S, const N: usize> RefUnwindSafe for IndexMap<K, V, S, N>where\n K: RefUnwindSafe,\n S: RefUnwindSafe,\n V: RefUnwindSafe,",1,["heapless::indexmap::IndexMap"]],["impl<T, S, const N: usize> RefUnwindSafe for IndexSet<T, S, N>where\n S: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::indexset::IndexSet"]],["impl<K, V, const N: usize> RefUnwindSafe for LinearMap<K, V, N>where\n K: RefUnwindSafe,\n V: RefUnwindSafe,",1,["heapless::linear_map::LinearMap"]],["impl<const N: usize> RefUnwindSafe for String<N>",1,["heapless::string::String"]],["impl<T, const N: usize> RefUnwindSafe for Vec<T, N>where\n T: RefUnwindSafe,",1,["heapless::vec::Vec"]],["impl RefUnwindSafe for Min",1,["heapless::binary_heap::Min"]],["impl RefUnwindSafe for Max",1,["heapless::binary_heap::Max"]],["impl<T, K, const N: usize> RefUnwindSafe for BinaryHeap<T, K, N>where\n K: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::binary_heap::BinaryHeap"]],["impl<'a, T, K, const N: usize> RefUnwindSafe for PeekMut<'a, T, K, N>where\n K: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::binary_heap::PeekMut"]],["impl RefUnwindSafe for Min",1,["heapless::sorted_linked_list::Min"]],["impl RefUnwindSafe for Max",1,["heapless::sorted_linked_list::Max"]],["impl<T, Idx> RefUnwindSafe for Node<T, Idx>where\n Idx: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::sorted_linked_list::Node"]],["impl<T, Idx, K, const N: usize> RefUnwindSafe for SortedLinkedList<T, Idx, K, N>where\n Idx: RefUnwindSafe,\n K: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::sorted_linked_list::SortedLinkedList"]],["impl RefUnwindSafe for LinkedIndexU8",1,["heapless::sorted_linked_list::LinkedIndexU8"]],["impl RefUnwindSafe for LinkedIndexU16",1,["heapless::sorted_linked_list::LinkedIndexU16"]],["impl RefUnwindSafe for LinkedIndexUsize",1,["heapless::sorted_linked_list::LinkedIndexUsize"]],["impl<'a, T, Idx, K, const N: usize> RefUnwindSafe for Iter<'a, T, Idx, K, N>where\n Idx: RefUnwindSafe,\n K: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::sorted_linked_list::Iter"]],["impl<'a, T, Idx, K, const N: usize> RefUnwindSafe for FindMut<'a, T, Idx, K, N>where\n Idx: RefUnwindSafe,\n K: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::sorted_linked_list::FindMut"]]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/panic/unwind_safe/trait.UnwindSafe.js b/docs/doc/implementors/core/panic/unwind_safe/trait.UnwindSafe.js index 4f737aa..febdc9b 100644 --- a/docs/doc/implementors/core/panic/unwind_safe/trait.UnwindSafe.js +++ b/docs/doc/implementors/core/panic/unwind_safe/trait.UnwindSafe.js @@ -1,3 +1,7 @@ (function() {var implementors = { -"arduboy_rust":[["impl UnwindSafe for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl UnwindSafe for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl UnwindSafe for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl UnwindSafe for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl UnwindSafe for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl UnwindSafe for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl UnwindSafe for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl UnwindSafe for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl UnwindSafe for Base",1,["arduboy_rust::print::Base"]]] +"arduboy_rust":[["impl UnwindSafe for ButtonSet",1,["arduboy_rust::hardware::buttons::ButtonSet"]],["impl UnwindSafe for Color",1,["arduboy_rust::library::arduboy2::Color"]],["impl UnwindSafe for Rect",1,["arduboy_rust::library::arduboy2::Rect"]],["impl UnwindSafe for Point",1,["arduboy_rust::library::arduboy2::Point"]],["impl UnwindSafe for Arduboy2",1,["arduboy_rust::library::arduboy2::Arduboy2"]],["impl UnwindSafe for ArduboyTones",1,["arduboy_rust::library::arduboy_tone::ArduboyTones"]],["impl UnwindSafe for EEPROM",1,["arduboy_rust::library::eeprom::EEPROM"]],["impl UnwindSafe for EEPROMBYTE",1,["arduboy_rust::library::eeprom::EEPROMBYTE"]],["impl UnwindSafe for Base",1,["arduboy_rust::print::Base"]]], +"byteorder":[["impl UnwindSafe for BigEndian",1,["byteorder::BigEndian"]],["impl UnwindSafe for LittleEndian",1,["byteorder::LittleEndian"]]], +"critical_section":[["impl<T> UnwindSafe for Mutex<T>where\n T: UnwindSafe,",1,["critical_section::mutex::Mutex"]],["impl<'cs> UnwindSafe for CriticalSection<'cs>",1,["critical_section::CriticalSection"]],["impl UnwindSafe for RestoreState",1,["critical_section::RestoreState"]]], +"hash32":[["impl UnwindSafe for Hasher",1,["hash32::fnv::Hasher"]],["impl UnwindSafe for Hasher",1,["hash32::murmur3::Hasher"]],["impl<H> UnwindSafe for BuildHasherDefault<H>where\n H: UnwindSafe,",1,["hash32::BuildHasherDefault"]]], +"heapless":[["impl<T, const N: usize> UnwindSafe for Deque<T, N>where\n T: UnwindSafe,",1,["heapless::deque::Deque"]],["impl<T, const N: usize> UnwindSafe for HistoryBuffer<T, N>where\n T: UnwindSafe,",1,["heapless::histbuf::HistoryBuffer"]],["impl<'a, T, const N: usize> UnwindSafe for OldestOrdered<'a, T, N>where\n T: RefUnwindSafe,",1,["heapless::histbuf::OldestOrdered"]],["impl<'a, K, V, const N: usize> !UnwindSafe for Entry<'a, K, V, N>",1,["heapless::indexmap::Entry"]],["impl<'a, K, V, const N: usize> !UnwindSafe for OccupiedEntry<'a, K, V, N>",1,["heapless::indexmap::OccupiedEntry"]],["impl<'a, K, V, const N: usize> !UnwindSafe for VacantEntry<'a, K, V, N>",1,["heapless::indexmap::VacantEntry"]],["impl<K, V, S, const N: usize> UnwindSafe for IndexMap<K, V, S, N>where\n K: UnwindSafe,\n S: UnwindSafe,\n V: UnwindSafe,",1,["heapless::indexmap::IndexMap"]],["impl<T, S, const N: usize> UnwindSafe for IndexSet<T, S, N>where\n S: UnwindSafe,\n T: UnwindSafe,",1,["heapless::indexset::IndexSet"]],["impl<K, V, const N: usize> UnwindSafe for LinearMap<K, V, N>where\n K: UnwindSafe,\n V: UnwindSafe,",1,["heapless::linear_map::LinearMap"]],["impl<const N: usize> UnwindSafe for String<N>",1,["heapless::string::String"]],["impl<T, const N: usize> UnwindSafe for Vec<T, N>where\n T: UnwindSafe,",1,["heapless::vec::Vec"]],["impl UnwindSafe for Min",1,["heapless::binary_heap::Min"]],["impl UnwindSafe for Max",1,["heapless::binary_heap::Max"]],["impl<T, K, const N: usize> UnwindSafe for BinaryHeap<T, K, N>where\n K: UnwindSafe,\n T: UnwindSafe,",1,["heapless::binary_heap::BinaryHeap"]],["impl<'a, T, K, const N: usize> !UnwindSafe for PeekMut<'a, T, K, N>",1,["heapless::binary_heap::PeekMut"]],["impl UnwindSafe for Min",1,["heapless::sorted_linked_list::Min"]],["impl UnwindSafe for Max",1,["heapless::sorted_linked_list::Max"]],["impl<T, Idx> UnwindSafe for Node<T, Idx>where\n Idx: UnwindSafe,\n T: UnwindSafe,",1,["heapless::sorted_linked_list::Node"]],["impl<T, Idx, K, const N: usize> UnwindSafe for SortedLinkedList<T, Idx, K, N>where\n Idx: UnwindSafe,\n K: UnwindSafe,\n T: UnwindSafe,",1,["heapless::sorted_linked_list::SortedLinkedList"]],["impl UnwindSafe for LinkedIndexU8",1,["heapless::sorted_linked_list::LinkedIndexU8"]],["impl UnwindSafe for LinkedIndexU16",1,["heapless::sorted_linked_list::LinkedIndexU16"]],["impl UnwindSafe for LinkedIndexUsize",1,["heapless::sorted_linked_list::LinkedIndexUsize"]],["impl<'a, T, Idx, K, const N: usize> UnwindSafe for Iter<'a, T, Idx, K, N>where\n Idx: UnwindSafe + RefUnwindSafe,\n K: RefUnwindSafe,\n T: RefUnwindSafe,",1,["heapless::sorted_linked_list::Iter"]],["impl<'a, T, Idx, K, const N: usize> !UnwindSafe for FindMut<'a, T, Idx, K, N>",1,["heapless::sorted_linked_list::FindMut"]]] };if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/core/str/traits/trait.FromStr.js b/docs/doc/implementors/core/str/traits/trait.FromStr.js new file mode 100644 index 0000000..3760537 --- /dev/null +++ b/docs/doc/implementors/core/str/traits/trait.FromStr.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"heapless":[["impl<const N: usize> FromStr for String<N>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/hash32/trait.BuildHasher.js b/docs/doc/implementors/hash32/trait.BuildHasher.js new file mode 100644 index 0000000..e54f64a --- /dev/null +++ b/docs/doc/implementors/hash32/trait.BuildHasher.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"hash32":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/hash32/trait.Hash.js b/docs/doc/implementors/hash32/trait.Hash.js new file mode 100644 index 0000000..1bd6f6d --- /dev/null +++ b/docs/doc/implementors/hash32/trait.Hash.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"hash32":[], +"heapless":[["impl<const N: usize> Hash for String<N>"],["impl<T, const N: usize> Hash for Vec<T, N>where\n T: Hash,"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/hash32/trait.Hasher.js b/docs/doc/implementors/hash32/trait.Hasher.js new file mode 100644 index 0000000..e54f64a --- /dev/null +++ b/docs/doc/implementors/hash32/trait.Hasher.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"hash32":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/heapless/binary_heap/trait.Kind.js b/docs/doc/implementors/heapless/binary_heap/trait.Kind.js new file mode 100644 index 0000000..fd4f746 --- /dev/null +++ b/docs/doc/implementors/heapless/binary_heap/trait.Kind.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"arduboy_rust":[], +"heapless":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/heapless/sorted_linked_list/trait.Kind.js b/docs/doc/implementors/heapless/sorted_linked_list/trait.Kind.js new file mode 100644 index 0000000..fd4f746 --- /dev/null +++ b/docs/doc/implementors/heapless/sorted_linked_list/trait.Kind.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"arduboy_rust":[], +"heapless":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/heapless/sorted_linked_list/trait.SortedLinkedListIndex.js b/docs/doc/implementors/heapless/sorted_linked_list/trait.SortedLinkedListIndex.js new file mode 100644 index 0000000..fd4f746 --- /dev/null +++ b/docs/doc/implementors/heapless/sorted_linked_list/trait.SortedLinkedListIndex.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"arduboy_rust":[], +"heapless":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/stable_deref_trait/trait.CloneStableDeref.js b/docs/doc/implementors/stable_deref_trait/trait.CloneStableDeref.js new file mode 100644 index 0000000..ac9dfad --- /dev/null +++ b/docs/doc/implementors/stable_deref_trait/trait.CloneStableDeref.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"stable_deref_trait":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/implementors/stable_deref_trait/trait.StableDeref.js b/docs/doc/implementors/stable_deref_trait/trait.StableDeref.js new file mode 100644 index 0000000..ac9dfad --- /dev/null +++ b/docs/doc/implementors/stable_deref_trait/trait.StableDeref.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"stable_deref_trait":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/docs/doc/search-index.js b/docs/doc/search-index.js index 7df29d2..f02cb15 100644 --- a/docs/doc/search-index.js +++ b/docs/doc/search-index.js @@ -1,6 +1,12 @@ var searchIndex = JSON.parse('{\ -"arduboy_rust":{"doc":"This is the arduboy_rust crate To get started import the …","t":"DDNEDDRRRNAAAAOOOOAAOADNERRDDRNMMMMMMDARRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRFFFFAARRRRDRRRRRRRRMLLLLRRRRRRRDDRRRENNDERRNDDRRRNRRNQDIRRRRRDRRRNAALLLLLLLLLAGGGGGGGGGGGLLLLFKFLLOMLLLLLLLLOOOLLMLLLLLLALLLLLLKOLFFLAFLLLLLLLLLLLLLMLMMMMDNERRDDRNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMDALLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRDRRRRRRRRMRRRRRFFFFFFFFFF","n":["Arduboy2","ArduboyTones","Black","Color","EEPROM","EEPROMBYTE","FONT_SIZE","HEIGHT","WIDTH","White","arduboy2","arduboy_tone","arduino","c","f","get_sprite_addr","get_string_addr","get_tones_addr","hardware","prelude","progmem","sprites","Arduboy2","Black","Color","FONT_SIZE","HEIGHT","Point","Rect","WIDTH","White","height","width","x","x","y","y","ArduboyTones","arduboy_tone_pitch","NOTE_A0","NOTE_A0H","NOTE_A1","NOTE_A1H","NOTE_A2","NOTE_A2H","NOTE_A3","NOTE_A3H","NOTE_A4","NOTE_A4H","NOTE_A5","NOTE_A5H","NOTE_A6","NOTE_A6H","NOTE_A7","NOTE_A7H","NOTE_A8","NOTE_A8H","NOTE_A9","NOTE_A9H","NOTE_AS0","NOTE_AS0H","NOTE_AS1","NOTE_AS1H","NOTE_AS2","NOTE_AS2H","NOTE_AS3","NOTE_AS3H","NOTE_AS4","NOTE_AS4H","NOTE_AS5","NOTE_AS5H","NOTE_AS6","NOTE_AS6H","NOTE_AS7","NOTE_AS7H","NOTE_AS8","NOTE_AS8H","NOTE_AS9","NOTE_AS9H","NOTE_B0","NOTE_B0H","NOTE_B1","NOTE_B1H","NOTE_B2","NOTE_B2H","NOTE_B3","NOTE_B3H","NOTE_B4","NOTE_B4H","NOTE_B5","NOTE_B5H","NOTE_B6","NOTE_B6H","NOTE_B7","NOTE_B7H","NOTE_B8","NOTE_B8H","NOTE_B9","NOTE_B9H","NOTE_C0","NOTE_C0H","NOTE_C1","NOTE_C1H","NOTE_C2","NOTE_C2H","NOTE_C3","NOTE_C3H","NOTE_C4","NOTE_C4H","NOTE_C5","NOTE_C5H","NOTE_C6","NOTE_C6H","NOTE_C7","NOTE_C7H","NOTE_C8","NOTE_C8H","NOTE_C9","NOTE_C9H","NOTE_CS0","NOTE_CS0H","NOTE_CS1","NOTE_CS1H","NOTE_CS2","NOTE_CS2H","NOTE_CS3","NOTE_CS3H","NOTE_CS4","NOTE_CS4H","NOTE_CS5","NOTE_CS5H","NOTE_CS6","NOTE_CS6H","NOTE_CS7","NOTE_CS7H","NOTE_CS8","NOTE_CS8H","NOTE_CS9","NOTE_CS9H","NOTE_D0","NOTE_D0H","NOTE_D1","NOTE_D1H","NOTE_D2","NOTE_D2H","NOTE_D3","NOTE_D3H","NOTE_D4","NOTE_D4H","NOTE_D5","NOTE_D5H","NOTE_D6","NOTE_D6H","NOTE_D7","NOTE_D7H","NOTE_D8","NOTE_D8H","NOTE_D9","NOTE_D9H","NOTE_DS0","NOTE_DS0H","NOTE_DS1","NOTE_DS1H","NOTE_DS2","NOTE_DS2H","NOTE_DS3","NOTE_DS3H","NOTE_DS4","NOTE_DS4H","NOTE_DS5","NOTE_DS5H","NOTE_DS6","NOTE_DS6H","NOTE_DS7","NOTE_DS7H","NOTE_DS8","NOTE_DS8H","NOTE_DS9","NOTE_DS9H","NOTE_E0","NOTE_E0H","NOTE_E1","NOTE_E1H","NOTE_E2","NOTE_E2H","NOTE_E3","NOTE_E3H","NOTE_E4","NOTE_E4H","NOTE_E5","NOTE_E5H","NOTE_E6","NOTE_E6H","NOTE_E7","NOTE_E7H","NOTE_E8","NOTE_E8H","NOTE_E9","NOTE_E9H","NOTE_F0","NOTE_F0H","NOTE_F1","NOTE_F1H","NOTE_F2","NOTE_F2H","NOTE_F3","NOTE_F3H","NOTE_F4","NOTE_F4H","NOTE_F5","NOTE_F5H","NOTE_F6","NOTE_F6H","NOTE_F7","NOTE_F7H","NOTE_F8","NOTE_F8H","NOTE_F9","NOTE_F9H","NOTE_FS0","NOTE_FS0H","NOTE_FS1","NOTE_FS1H","NOTE_FS2","NOTE_FS2H","NOTE_FS3","NOTE_FS3H","NOTE_FS4","NOTE_FS4H","NOTE_FS5","NOTE_FS5H","NOTE_FS6","NOTE_FS6H","NOTE_FS7","NOTE_FS7H","NOTE_FS8","NOTE_FS8H","NOTE_FS9","NOTE_FS9H","NOTE_G0","NOTE_G0H","NOTE_G1","NOTE_G1H","NOTE_G2","NOTE_G2H","NOTE_G3","NOTE_G3H","NOTE_G4","NOTE_G4H","NOTE_G5","NOTE_G5H","NOTE_G6","NOTE_G6H","NOTE_G7","NOTE_G7H","NOTE_G8","NOTE_G8H","NOTE_G9","NOTE_G9H","NOTE_GS0","NOTE_GS0H","NOTE_GS1","NOTE_GS1H","NOTE_GS2","NOTE_GS2H","NOTE_GS3","NOTE_GS3H","NOTE_GS4","NOTE_GS4H","NOTE_GS5","NOTE_GS5H","NOTE_GS6","NOTE_GS6H","NOTE_GS7","NOTE_GS7H","NOTE_GS8","NOTE_GS8H","NOTE_GS9","NOTE_GS9H","NOTE_REST","TONES_END","TONES_REPEAT","TONE_HIGH_VOLUME","VOLUME_ALWAYS_HIGH","VOLUME_ALWAYS_NORMAL","VOLUME_IN_TONE","delay","random_between","random_less_than","strlen","buttons","led","A","A_BUTTON","B","B_BUTTON","ButtonSet","DOWN","DOWN_BUTTON","LEFT","LEFT_BUTTON","RIGHT","RIGHT_BUTTON","UP","UP_BUTTON","flag_set","just_pressed","just_released","not_pressed","pressed","BLUE_LED","GREEN_LED","RED_LED","RGB_OFF","RGB_ON","A","A_BUTTON","Arduboy2","ArduboyTones","B","BLUE_LED","B_BUTTON","Base","Bin","Black","ButtonSet","Color","DOWN","DOWN_BUTTON","Dec","EEPROM","EEPROMBYTE","FONT_SIZE","GREEN_LED","HEIGHT","Hex","LEFT","LEFT_BUTTON","Oct","Parameters","Point","Printable","RED_LED","RGB_OFF","RGB_ON","RIGHT","RIGHT_BUTTON","Rect","UP","UP_BUTTON","WIDTH","White","arduboy2","arduboy_tone","bitor","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","buttons","c_char","c_double","c_float","c_int","c_long","c_longlong","c_size_t","c_uchar","c_uint","c_ulong","c_ulonglong","clone","clone","cmp","cmp","constrain","default_parameters","delay","eq","eq","f","flag_set","fmt","fmt","from","from","from","from","get","get_direct","get_sprite_addr","get_string_addr","get_tones_addr","hash","hash","height","init","init","into","into","into","into","led","new","new","partial_cmp","partial_cmp","print","print","print_2","progmem","put","random_between","random_less_than","read","sprites","strlen","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","update","width","write","x","x","y","y","Arduboy2","Black","Color","FONT_SIZE","HEIGHT","Point","Rect","WIDTH","White","audio_enabled","audio_off","audio_on","audio_on_and_save","audio_save_on_off","audio_toggle","begin","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clear","clone","cmp","collide_point","collide_rect","digital_write_rgb","digital_write_rgb_single","display","display_and_clear_buffer","draw_circle","draw_fast_hline","draw_fast_vline","draw_pixel","draw_rect","draw_round_rect","draw_triangle","eq","every_x_frames","fill_circle","fill_rect","fill_round_rect","fill_triangle","flip_horizontal","flip_vertical","fmt","from","from","from","from","get_pixel","hash","height","idle","init_random_seed","into","into","into","into","invert","just_pressed","just_released","new","next_frame","not","not_pressed","partial_cmp","poll_buttons","pressed","print","set_cursor","set_cursor_x","set_cursor_y","set_frame_rate","set_text_background_color","set_text_color","set_text_size","set_text_wrap","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","width","x","x","y","y","ArduboyTones","arduboy_tone_pitch","borrow","borrow_mut","from","into","new","no_tone","playing","tone","tone2","tone3","tones","tones_in_ram","try_from","try_into","type_id","volume_mode","NOTE_A0","NOTE_A0H","NOTE_A1","NOTE_A1H","NOTE_A2","NOTE_A2H","NOTE_A3","NOTE_A3H","NOTE_A4","NOTE_A4H","NOTE_A5","NOTE_A5H","NOTE_A6","NOTE_A6H","NOTE_A7","NOTE_A7H","NOTE_A8","NOTE_A8H","NOTE_A9","NOTE_A9H","NOTE_AS0","NOTE_AS0H","NOTE_AS1","NOTE_AS1H","NOTE_AS2","NOTE_AS2H","NOTE_AS3","NOTE_AS3H","NOTE_AS4","NOTE_AS4H","NOTE_AS5","NOTE_AS5H","NOTE_AS6","NOTE_AS6H","NOTE_AS7","NOTE_AS7H","NOTE_AS8","NOTE_AS8H","NOTE_AS9","NOTE_AS9H","NOTE_B0","NOTE_B0H","NOTE_B1","NOTE_B1H","NOTE_B2","NOTE_B2H","NOTE_B3","NOTE_B3H","NOTE_B4","NOTE_B4H","NOTE_B5","NOTE_B5H","NOTE_B6","NOTE_B6H","NOTE_B7","NOTE_B7H","NOTE_B8","NOTE_B8H","NOTE_B9","NOTE_B9H","NOTE_C0","NOTE_C0H","NOTE_C1","NOTE_C1H","NOTE_C2","NOTE_C2H","NOTE_C3","NOTE_C3H","NOTE_C4","NOTE_C4H","NOTE_C5","NOTE_C5H","NOTE_C6","NOTE_C6H","NOTE_C7","NOTE_C7H","NOTE_C8","NOTE_C8H","NOTE_C9","NOTE_C9H","NOTE_CS0","NOTE_CS0H","NOTE_CS1","NOTE_CS1H","NOTE_CS2","NOTE_CS2H","NOTE_CS3","NOTE_CS3H","NOTE_CS4","NOTE_CS4H","NOTE_CS5","NOTE_CS5H","NOTE_CS6","NOTE_CS6H","NOTE_CS7","NOTE_CS7H","NOTE_CS8","NOTE_CS8H","NOTE_CS9","NOTE_CS9H","NOTE_D0","NOTE_D0H","NOTE_D1","NOTE_D1H","NOTE_D2","NOTE_D2H","NOTE_D3","NOTE_D3H","NOTE_D4","NOTE_D4H","NOTE_D5","NOTE_D5H","NOTE_D6","NOTE_D6H","NOTE_D7","NOTE_D7H","NOTE_D8","NOTE_D8H","NOTE_D9","NOTE_D9H","NOTE_DS0","NOTE_DS0H","NOTE_DS1","NOTE_DS1H","NOTE_DS2","NOTE_DS2H","NOTE_DS3","NOTE_DS3H","NOTE_DS4","NOTE_DS4H","NOTE_DS5","NOTE_DS5H","NOTE_DS6","NOTE_DS6H","NOTE_DS7","NOTE_DS7H","NOTE_DS8","NOTE_DS8H","NOTE_DS9","NOTE_DS9H","NOTE_E0","NOTE_E0H","NOTE_E1","NOTE_E1H","NOTE_E2","NOTE_E2H","NOTE_E3","NOTE_E3H","NOTE_E4","NOTE_E4H","NOTE_E5","NOTE_E5H","NOTE_E6","NOTE_E6H","NOTE_E7","NOTE_E7H","NOTE_E8","NOTE_E8H","NOTE_E9","NOTE_E9H","NOTE_F0","NOTE_F0H","NOTE_F1","NOTE_F1H","NOTE_F2","NOTE_F2H","NOTE_F3","NOTE_F3H","NOTE_F4","NOTE_F4H","NOTE_F5","NOTE_F5H","NOTE_F6","NOTE_F6H","NOTE_F7","NOTE_F7H","NOTE_F8","NOTE_F8H","NOTE_F9","NOTE_F9H","NOTE_FS0","NOTE_FS0H","NOTE_FS1","NOTE_FS1H","NOTE_FS2","NOTE_FS2H","NOTE_FS3","NOTE_FS3H","NOTE_FS4","NOTE_FS4H","NOTE_FS5","NOTE_FS5H","NOTE_FS6","NOTE_FS6H","NOTE_FS7","NOTE_FS7H","NOTE_FS8","NOTE_FS8H","NOTE_FS9","NOTE_FS9H","NOTE_G0","NOTE_G0H","NOTE_G1","NOTE_G1H","NOTE_G2","NOTE_G2H","NOTE_G3","NOTE_G3H","NOTE_G4","NOTE_G4H","NOTE_G5","NOTE_G5H","NOTE_G6","NOTE_G6H","NOTE_G7","NOTE_G7H","NOTE_G8","NOTE_G8H","NOTE_G9","NOTE_G9H","NOTE_GS0","NOTE_GS0H","NOTE_GS1","NOTE_GS1H","NOTE_GS2","NOTE_GS2H","NOTE_GS3","NOTE_GS3H","NOTE_GS4","NOTE_GS4H","NOTE_GS5","NOTE_GS5H","NOTE_GS6","NOTE_GS6H","NOTE_GS7","NOTE_GS7H","NOTE_GS8","NOTE_GS8H","NOTE_GS9","NOTE_GS9H","NOTE_REST","TONES_END","TONES_REPEAT","TONE_HIGH_VOLUME","VOLUME_ALWAYS_HIGH","VOLUME_ALWAYS_NORMAL","VOLUME_IN_TONE","A","A_BUTTON","B","B_BUTTON","ButtonSet","DOWN","DOWN_BUTTON","LEFT","LEFT_BUTTON","RIGHT","RIGHT_BUTTON","UP","UP_BUTTON","flag_set","BLUE_LED","GREEN_LED","RED_LED","RGB_OFF","RGB_ON","draw_erase","draw_external_mask","draw_override","draw_plus_mask","draw_self_masked","draw_erase","draw_external_mask","draw_override","draw_plus_mask","draw_self_masked"],"q":[[0,"arduboy_rust"],[22,"arduboy_rust::arduboy2"],[37,"arduboy_rust::arduboy_tone"],[39,"arduboy_rust::arduboy_tone::arduboy_tone_pitch"],[286,"arduboy_rust::arduino"],[289,"arduboy_rust::c"],[290,"arduboy_rust::hardware"],[292,"arduboy_rust::hardware::buttons"],[310,"arduboy_rust::hardware::led"],[315,"arduboy_rust::prelude"],[440,"arduboy_rust::prelude::arduboy2"],[538,"arduboy_rust::prelude::arduboy_tone"],[556,"arduboy_rust::prelude::arduboy_tone::arduboy_tone_pitch"],[803,"arduboy_rust::prelude::buttons"],[817,"arduboy_rust::prelude::led"],[822,"arduboy_rust::prelude::sprites"],[827,"arduboy_rust::sprites"]],"d":["This is the struct to interact in a save way with the …","This is the struct to interact in a save way with the …","Led is off","This item is to chose between Black or White","This is the struct to store and read structs objects …","Use this struct to store and read single bytes to/from …","The standard font size of the arduboy","The standard height of the arduboy","The standard width of the arduboy","Led is on","This is the Module to interact in a save way with the …","This is the Module to interact in a save way with the …","This is the Module to interact in a save way with the …","Clib functions you can use on the Arduboy","This is the way to go if you want print some random text","Create a const raw pointer to a sprite as u8, without …","Create a const raw pointer to a [u8;_] that saves text, …","Create a const raw pointer to a sprite as u16, without …","This is the Module to interact in a save way with the …","This is the important one to use this library effective in …","Create a space for Progmem variable","This is the module to interact in a save way with the …","This is the struct to interact in a save way with the …","Led is off","This item is to chose between Black or White","The standard font size of the arduboy","The standard height of the arduboy","This struct is used by a few Arduboy functions.","This struct is used by a few Arduboy functions.","The standard width of the arduboy","Led is on","Rect height","Rect width","Position X","Position X","Position Y","Position Y","This is the struct to interact in a save way with the …","A list of all tones available and used by the Sounds …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","A Arduino function to pause the cpu circles for a given …","A Arduino function to get a random number between 2 numbers","A Arduino function to get a random number smaller than the …","A C function to get the length of a string","A list of all six buttons available on the Arduboy","A list of all LED variables available","Just a const for the A button","Just a const for the A button","Just a const for the B button","Just a const for the B button","This struct gives the library a understanding what Buttons …","Just a const for the DOWN button","Just a const for the DOWN button","Just a const for the LEFT button","Just a const for the LEFT button","Just a const for the RIGHT button","Just a const for the RIGHT button","Just a const for the UP button","Just a const for the UP button","","","","","","Just a const for the blue led","Just a const for the green led","Just a const for the red led","Just a const for led off","Just a const for led on","Just a const for the A button","Just a const for the A button","This is the struct to interact in a save way with the …","This is the struct to interact in a save way with the …","Just a const for the B button","Just a const for the blue led","Just a const for the B button","","","Led is off","This struct gives the library a understanding what Buttons …","This item is to chose between Black or White","Just a const for the DOWN button","Just a const for the DOWN button","","This is the struct to store and read structs objects …","Use this struct to store and read single bytes to/from …","The standard font size of the arduboy","Just a const for the green led","The standard height of the arduboy","","Just a const for the LEFT button","Just a const for the LEFT button","","","This struct is used by a few Arduboy functions.","","Just a const for the red led","Just a const for led off","Just a const for led on","Just a const for the RIGHT button","Just a const for the RIGHT button","This struct is used by a few Arduboy functions.","Just a const for the UP button","Just a const for the UP button","The standard width of the arduboy","Led is on","This is the Module to interact in a save way with the …","This is the Module to interact in a save way with the …","","","","","","","","","","A list of all six buttons available on the Arduboy","Equivalent to C’s char type.","Equivalent to C’s double type.","Equivalent to C’s float type.","Equivalent to C’s signed int (int) type.","Equivalent to C’s signed long (long) type.","Equivalent to C’s signed long long (long long) type.","Equivalent to C’s size_t type, from stddef.h (or cstddef …","Equivalent to C’s unsigned char type.","Equivalent to C’s unsigned int type.","Equivalent to C’s unsigned long type.","Equivalent to C’s unsigned long long type.","","","","","","","A Arduino function to pause the cpu circles for a given …","","","This is the way to go if you want print some random text","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Create a const raw pointer to a sprite as u8, without …","Create a const raw pointer to a [u8;_] that saves text, …","Create a const raw pointer to a sprite as u16, without …","","","Rect height","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","A list of all LED variables available","","","","","","","","Create a space for Progmem variable","","A Arduino function to get a random number between 2 numbers","A Arduino function to get a random number smaller than the …","","This is the module to interact in a save way with the …","A C function to get the length of a string","","","","","","","","","","","","","","Rect width","","Position X","Position X","Position Y","Position Y","This is the struct to interact in a save way with the …","Led is off","This item is to chose between Black or White","The standard font size of the arduboy","The standard height of the arduboy","This struct is used by a few Arduboy functions.","This struct is used by a few Arduboy functions.","The standard width of the arduboy","Led is on","Get the current sound state.","Turn sound off (mute).","Turn sound on.","Combines the use function of audio_on() and …","Save the current sound state in EEPROM.","Toggle the sound on/off state.","Initialize the hardware, display the boot logo, provide …","","","","","","","","","Clear the display buffer and set the text cursor to …","","","Test if a point falls within a rectangle.","Test if a rectangle is intersecting with another rectangle.","Set the RGB LEDs digitally, to either fully on or fully …","Set one of the RGB LEDs digitally, to either fully on or …","Copy the contents of the display buffer to the display. …","Copy the contents of the display buffer to the display. …","Draw a circle of a given radius.","Draw a horizontal line.","Draw a vertical line.","Set a single pixel in the display buffer to the specified …","Draw a rectangle of a specified width and height.","Draw a rectangle with rounded corners.","Draw a triangle given the coordinates of each corner.","","Indicate if the specified number of frames has elapsed.","Draw a filled-in circle of a given radius.","Draw a filled-in rectangle of a specified width and height.","Draw a filled-in rectangle with rounded corners.","Draw a filled-in triangle given the coordinates of each …","Flip the display horizontally or set it back to normal.","Flip the display vertically or set it back to normal.","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the state of the given pixel in the screen buffer.","","Rect height","Idle the CPU to save power.","Seed the random number generator with a random value.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Invert the entire display or set it back to normal.","Check if a button has just been pressed.","Check if a button has just been released.","gives you a new instance of the Arduboy2","Indicate that it’s time to render the next frame.","","Test if the specified buttons are not pressed.","","Poll the buttons and track their state over time.","Test if the all of the specified buttons are pressed.","The Arduino Print class is available for writing text to …","Set the location of the text cursor.","Set the X coordinate of the text cursor location.","Set the Y coordinate of the text cursor location.","Set the frame rate used by the frame control functions.","Set the text background color.","Set the text foreground color.","Set the text character size.","Set or disable text wrap mode.","","","","","","","","","","","","","Rect width","Position X","Position X","Position Y","Position Y","This is the struct to interact in a save way with the …","A list of all tones available and used by the Sounds …","","","Returns the argument unchanged.","Calls U::from(self).","Get a new instance of ArduboyTones","Stop playing the tone or sequence.","Check if a tone or tone sequence is playing.","Play a single tone.","Play two tones in sequence.","Play three tones in sequence.","Play a tone sequence from frequency/duration pairs in a …","Play a tone sequence from frequency/duration pairs in an …","","","","Set the volume to always normal, always high, or tone …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Just a const for the A button","Just a const for the A button","Just a const for the B button","Just a const for the B button","This struct gives the library a understanding what Buttons …","Just a const for the DOWN button","Just a const for the DOWN button","Just a const for the LEFT button","Just a const for the LEFT button","Just a const for the RIGHT button","Just a const for the RIGHT button","Just a const for the UP button","Just a const for the UP button","","Just a const for the blue led","Just a const for the green led","Just a const for the red led","Just a const for led off","Just a const for led on","“Erase” a sprite.","Draw a sprite using a separate image and mask array.","Draw a sprite by replacing the existing content completely.","Draw a sprite using an array containing both image and …","Draw a sprite using only the bits set to 1.","“Erase” a sprite.","Draw a sprite using a separate image and mask array.","Draw a sprite by replacing the existing content completely.","Draw a sprite using an array containing both image and …","Draw a sprite using only the bits set to 1."],"i":[0,0,21,0,0,0,0,0,0,21,0,0,0,0,0,0,0,0,0,0,0,0,0,21,0,0,0,0,0,0,21,23,23,23,22,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,5,5,5,5,0,0,0,0,0,0,0,0,0,0,0,0,0,7,21,0,0,0,0,7,0,0,0,0,0,7,0,0,7,24,0,0,0,0,0,0,0,0,0,0,0,21,0,0,5,12,14,5,7,12,14,5,7,0,0,0,0,0,0,0,0,0,0,0,0,5,7,5,7,0,24,0,5,7,0,5,5,7,12,14,5,7,12,12,0,0,0,5,7,23,12,14,12,14,5,7,0,12,14,5,7,24,24,24,0,12,0,0,14,0,0,12,14,5,7,12,14,5,7,12,14,5,7,14,23,14,23,22,23,22,0,21,0,0,0,0,0,0,21,20,20,20,20,20,20,20,23,22,20,21,23,22,20,21,20,21,21,20,20,20,20,20,20,20,20,20,20,20,20,20,21,20,20,20,20,20,20,20,21,23,22,20,21,20,21,23,20,20,23,22,20,21,20,20,20,20,20,21,20,21,20,20,20,20,20,20,20,20,20,20,20,23,22,20,21,23,22,20,21,23,22,20,21,23,23,22,23,22,0,0,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1],[[2,2],2],[2,2],[3,4],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[5,6],[5,6],[5,6],[5,6],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[5,5],5],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,[5,5],[7,7],[[5,5],8],[[7,7],8],[[9,9,9],9],[[]],[1],[[5,5],6],[[7,7],6],0,0,[[5,10],11],[[7,10],11],[[]],[[]],[[]],[[]],[12],[12],0,0,0,[[5,13]],[[7,13]],0,[12],[14],[[]],[[]],[[]],[[]],0,[15,12],[15,14],[[5,5],[[16,[8]]]],[[7,7],[[16,[8]]]],[[]],[[]],[[]],0,[12],[[2,2],2],[2,2],[14,17],0,[3,4],[[],18],[[],18],[[],18],[[],18],[[],18],[[],18],[[],18],[[],18],[[],19],[[],19],[[],19],[[],19],[[14,17]],0,[[14,17]],0,0,0,0,0,0,0,0,0,0,0,0,0,[20,6],[20],[20],[20],[20],[20],[20],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[20],[21,21],[[21,21],8],[[20,22,23],6],[[20,23,23],6],[[20,17,17,17]],[[20,17,17]],[20],[20],[[20,15,15,17,21]],[[20,15,15,17,21]],[[20,15,15,17,21]],[[20,15,15,21]],[[20,15,15,17,17,21]],[[20,15,15,17,17,17,21]],[[20,15,15,15,15,15,15,21]],[[21,21],6],[[20,17],6],[[20,15,15,17,21]],[[20,15,15,17,17,21]],[[20,15,15,17,17,17,21]],[[20,15,15,15,15,15,15,21]],[[20,6]],[[20,6]],[[21,10],11],[[]],[[]],[[]],[[]],[[20,17,17],21],[[21,13]],0,[20],[20],[[]],[[]],[[]],[[]],[[20,6]],[[20,5],6],[[20,5],6],[[],20],[20,6],[21],[[20,5],6],[[21,21],[[16,[8]]]],[20],[[20,5],6],[[20,24]],[[20,15,15]],[[20,15]],[[20,15]],[[20,17]],[[20,21]],[[20,21]],[[20,17]],[[20,6]],[[],18],[[],18],[[],18],[[],18],[[],18],[[],18],[[],18],[[],18],[[],19],[[],19],[[],19],[[],19],0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[],25],[25],[25,6],[[25,26,1]],[[25,26,1,26,1]],[[25,26,1,26,1,26,1]],[[25,26]],[[25,1]],[[],18],[[],18],[[],19],[[25,17]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[15,15,17,17]],[[15,15,17,17,17,17]],[[15,15,17,17]],[[15,15,17,17]],[[15,15,17,17]],[[15,15,17,17]],[[15,15,17,17,17,17]],[[15,15,17,17]],[[15,15,17,17]],[[15,15,17,17]]],"c":[],"p":[[15,"u32"],[15,"i32"],[15,"i8"],[15,"usize"],[3,"ButtonSet"],[15,"bool"],[4,"Base"],[4,"Ordering"],[8,"Ord"],[3,"Formatter"],[6,"Result"],[3,"EEPROM"],[8,"Hasher"],[3,"EEPROMBYTE"],[15,"i16"],[4,"Option"],[15,"u8"],[4,"Result"],[3,"TypeId"],[3,"Arduboy2"],[4,"Color"],[3,"Point"],[3,"Rect"],[8,"Printable"],[3,"ArduboyTones"],[15,"u16"]]},\ -"panic_halt":{"doc":"Set the panicking behavior to halt","t":"","n":[],"q":[],"d":[],"i":[],"f":[],"c":[],"p":[]}\ +"arduboy_rust":{"doc":"This is the arduboy_rust crate To get started import the …","t":"DDNEDDRRRNAAAAOOOOAAOADNERRDDRNMMMMMMDARRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRFFFFAARRRRDRRRRRRRRMLLLLRRRRRDDEGGDDDDNDDDNDDLLLLLLLLLLLLLLLLLLALLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLALLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLDIEEDLLLLLLLLLLLLLLLLLLLLLLLLLDDIDDDDDDDILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLRRDDRRRENNDERRNDDRRRNRRDNQDIRRRRRDDRRDRNAALLLLLLLLLAGGGGGGGGGGGLLLLFKFLLOMLLLLLLLLOOOLLMLLLLLLALLLLLLKOLFFLAFLLLLLLLLLLLLLMLMMMMDNERRDDRNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMDALLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRDRRRRRRRRMRRRRRFFFFFFFFFF","n":["Arduboy2","ArduboyTones","Black","Color","EEPROM","EEPROMBYTE","FONT_SIZE","HEIGHT","WIDTH","White","arduboy2","arduboy_tone","arduino","c","f","get_sprite_addr","get_string_addr","get_tones_addr","hardware","prelude","progmem","sprites","Arduboy2","Black","Color","FONT_SIZE","HEIGHT","Point","Rect","WIDTH","White","height","width","x","x","y","y","ArduboyTones","arduboy_tone_pitch","NOTE_A0","NOTE_A0H","NOTE_A1","NOTE_A1H","NOTE_A2","NOTE_A2H","NOTE_A3","NOTE_A3H","NOTE_A4","NOTE_A4H","NOTE_A5","NOTE_A5H","NOTE_A6","NOTE_A6H","NOTE_A7","NOTE_A7H","NOTE_A8","NOTE_A8H","NOTE_A9","NOTE_A9H","NOTE_AS0","NOTE_AS0H","NOTE_AS1","NOTE_AS1H","NOTE_AS2","NOTE_AS2H","NOTE_AS3","NOTE_AS3H","NOTE_AS4","NOTE_AS4H","NOTE_AS5","NOTE_AS5H","NOTE_AS6","NOTE_AS6H","NOTE_AS7","NOTE_AS7H","NOTE_AS8","NOTE_AS8H","NOTE_AS9","NOTE_AS9H","NOTE_B0","NOTE_B0H","NOTE_B1","NOTE_B1H","NOTE_B2","NOTE_B2H","NOTE_B3","NOTE_B3H","NOTE_B4","NOTE_B4H","NOTE_B5","NOTE_B5H","NOTE_B6","NOTE_B6H","NOTE_B7","NOTE_B7H","NOTE_B8","NOTE_B8H","NOTE_B9","NOTE_B9H","NOTE_C0","NOTE_C0H","NOTE_C1","NOTE_C1H","NOTE_C2","NOTE_C2H","NOTE_C3","NOTE_C3H","NOTE_C4","NOTE_C4H","NOTE_C5","NOTE_C5H","NOTE_C6","NOTE_C6H","NOTE_C7","NOTE_C7H","NOTE_C8","NOTE_C8H","NOTE_C9","NOTE_C9H","NOTE_CS0","NOTE_CS0H","NOTE_CS1","NOTE_CS1H","NOTE_CS2","NOTE_CS2H","NOTE_CS3","NOTE_CS3H","NOTE_CS4","NOTE_CS4H","NOTE_CS5","NOTE_CS5H","NOTE_CS6","NOTE_CS6H","NOTE_CS7","NOTE_CS7H","NOTE_CS8","NOTE_CS8H","NOTE_CS9","NOTE_CS9H","NOTE_D0","NOTE_D0H","NOTE_D1","NOTE_D1H","NOTE_D2","NOTE_D2H","NOTE_D3","NOTE_D3H","NOTE_D4","NOTE_D4H","NOTE_D5","NOTE_D5H","NOTE_D6","NOTE_D6H","NOTE_D7","NOTE_D7H","NOTE_D8","NOTE_D8H","NOTE_D9","NOTE_D9H","NOTE_DS0","NOTE_DS0H","NOTE_DS1","NOTE_DS1H","NOTE_DS2","NOTE_DS2H","NOTE_DS3","NOTE_DS3H","NOTE_DS4","NOTE_DS4H","NOTE_DS5","NOTE_DS5H","NOTE_DS6","NOTE_DS6H","NOTE_DS7","NOTE_DS7H","NOTE_DS8","NOTE_DS8H","NOTE_DS9","NOTE_DS9H","NOTE_E0","NOTE_E0H","NOTE_E1","NOTE_E1H","NOTE_E2","NOTE_E2H","NOTE_E3","NOTE_E3H","NOTE_E4","NOTE_E4H","NOTE_E5","NOTE_E5H","NOTE_E6","NOTE_E6H","NOTE_E7","NOTE_E7H","NOTE_E8","NOTE_E8H","NOTE_E9","NOTE_E9H","NOTE_F0","NOTE_F0H","NOTE_F1","NOTE_F1H","NOTE_F2","NOTE_F2H","NOTE_F3","NOTE_F3H","NOTE_F4","NOTE_F4H","NOTE_F5","NOTE_F5H","NOTE_F6","NOTE_F6H","NOTE_F7","NOTE_F7H","NOTE_F8","NOTE_F8H","NOTE_F9","NOTE_F9H","NOTE_FS0","NOTE_FS0H","NOTE_FS1","NOTE_FS1H","NOTE_FS2","NOTE_FS2H","NOTE_FS3","NOTE_FS3H","NOTE_FS4","NOTE_FS4H","NOTE_FS5","NOTE_FS5H","NOTE_FS6","NOTE_FS6H","NOTE_FS7","NOTE_FS7H","NOTE_FS8","NOTE_FS8H","NOTE_FS9","NOTE_FS9H","NOTE_G0","NOTE_G0H","NOTE_G1","NOTE_G1H","NOTE_G2","NOTE_G2H","NOTE_G3","NOTE_G3H","NOTE_G4","NOTE_G4H","NOTE_G5","NOTE_G5H","NOTE_G6","NOTE_G6H","NOTE_G7","NOTE_G7H","NOTE_G8","NOTE_G8H","NOTE_G9","NOTE_G9H","NOTE_GS0","NOTE_GS0H","NOTE_GS1","NOTE_GS1H","NOTE_GS2","NOTE_GS2H","NOTE_GS3","NOTE_GS3H","NOTE_GS4","NOTE_GS4H","NOTE_GS5","NOTE_GS5H","NOTE_GS6","NOTE_GS6H","NOTE_GS7","NOTE_GS7H","NOTE_GS8","NOTE_GS8H","NOTE_GS9","NOTE_GS9H","NOTE_REST","TONES_END","TONES_REPEAT","TONE_HIGH_VOLUME","VOLUME_ALWAYS_HIGH","VOLUME_ALWAYS_NORMAL","VOLUME_IN_TONE","delay","random_between","random_less_than","strlen","buttons","led","A","A_BUTTON","B","B_BUTTON","ButtonSet","DOWN","DOWN_BUTTON","LEFT","LEFT_BUTTON","RIGHT","RIGHT_BUTTON","UP","UP_BUTTON","flag_set","just_pressed","just_released","not_pressed","pressed","BLUE_LED","GREEN_LED","RED_LED","RGB_OFF","RGB_ON","BinaryHeap","Deque","Entry","FnvIndexMap","FnvIndexSet","HistoryBuffer","IndexMap","IndexSet","LinearMap","Occupied","OccupiedEntry","OldestOrdered","String","Vacant","VacantEntry","Vec","as_mut","as_mut","as_mut_ptr","as_mut_slices","as_mut_str","as_mut_vec","as_ptr","as_ref","as_ref","as_ref","as_ref","as_ref","as_slice","as_slice","as_slices","as_str","back","back_mut","binary_heap","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","capacity","capacity","capacity","capacity","capacity","capacity","capacity","capacity","clear","clear","clear","clear","clear","clear","clear","clear","clear_with","clone","clone","clone","clone","clone","clone","clone","clone","cmp","cmp","contains","contains_key","contains_key","default","default","default","default","default","default","default","default","deref","deref","deref","deref_mut","deref_mut","difference","drop","drop","drop","drop","ends_with","entry","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","extend","extend","extend","extend","extend","extend","extend","extend","extend","extend_from_slice","extend_from_slice","first","first","first_mut","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from_iter","from_iter","from_iter","from_iter","from_iter","from_iter","from_iter","from_slice","from_str","front","front_mut","get","get","get","get_mut","get_mut","get_mut","hash","hash","hash","hash","index","index","index_mut","index_mut","insert","insert","insert","insert","insert","insert","intersection","into","into","into","into","into","into","into","into","into","into","into","into","into_array","into_bytes","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_key","into_mut","into_vec","is_disjoint","is_empty","is_empty","is_empty","is_empty","is_empty","is_empty","is_full","is_full","is_subset","is_superset","iter","iter","iter","iter","iter","iter_mut","iter_mut","iter_mut","iter_mut","key","key","keys","keys","last","last","last_mut","len","len","len","len","len","len","ne","ne","ne","new","new","new","new","new","new","new","new","new_with","next","oldest_ordered","partial_cmp","partial_cmp","peek","peek_mut","pop","pop","pop","pop_back","pop_back_unchecked","pop_front","pop_front_unchecked","pop_unchecked","pop_unchecked","push","push","push","push_back","push_back_unchecked","push_front","push_front_unchecked","push_str","push_unchecked","push_unchecked","recent","remove","remove","remove","remove","remove","remove_entry","resize","resize_default","retain","retain_mut","set_len","sorted_linked_list","starts_with","swap_remove","swap_remove","swap_remove_unchecked","symmetric_difference","truncate","truncate","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","union","values","values","values_mut","values_mut","write","write_char","write_str","write_str","BinaryHeap","Kind","Max","Min","PeekMut","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","deref","deref_mut","drop","from","from","from","into","into","into","pop","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","FindMut","Iter","Kind","LinkedIndexU16","LinkedIndexU8","LinkedIndexUsize","Max","Min","Node","SortedLinkedList","SortedLinkedListIndex","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","cmp","cmp","cmp","deref","deref_mut","drop","drop","eq","eq","eq","find_mut","finish","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","into","into","into","into","into","into","into","into","into","into_iter","is_empty","is_full","iter","new_u16","new_u8","new_usize","next","partial_cmp","partial_cmp","partial_cmp","peek","pop","pop","pop_unchecked","push","push_unchecked","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","A","A_BUTTON","Arduboy2","ArduboyTones","B","BLUE_LED","B_BUTTON","Base","Bin","Black","ButtonSet","Color","DOWN","DOWN_BUTTON","Dec","EEPROM","EEPROMBYTE","FONT_SIZE","GREEN_LED","HEIGHT","Hex","LEFT","LEFT_BUTTON","LinearMap","Oct","Parameters","Point","Printable","RED_LED","RGB_OFF","RGB_ON","RIGHT","RIGHT_BUTTON","Rect","String","UP","UP_BUTTON","Vec","WIDTH","White","arduboy2","arduboy_tone","bitor","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","buttons","c_char","c_double","c_float","c_int","c_long","c_longlong","c_size_t","c_uchar","c_uint","c_ulong","c_ulonglong","clone","clone","cmp","cmp","constrain","default_parameters","delay","eq","eq","f","flag_set","fmt","fmt","from","from","from","from","get","get_direct","get_sprite_addr","get_string_addr","get_tones_addr","hash","hash","height","init","init","into","into","into","into","led","new","new","partial_cmp","partial_cmp","print","print","print_2","progmem","put","random_between","random_less_than","read","sprites","strlen","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","update","width","write","x","x","y","y","Arduboy2","Black","Color","FONT_SIZE","HEIGHT","Point","Rect","WIDTH","White","audio_enabled","audio_off","audio_on","audio_on_and_save","audio_save_on_off","audio_toggle","begin","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clear","clone","cmp","collide_point","collide_rect","digital_write_rgb","digital_write_rgb_single","display","display_and_clear_buffer","draw_circle","draw_fast_hline","draw_fast_vline","draw_pixel","draw_rect","draw_round_rect","draw_triangle","eq","every_x_frames","fill_circle","fill_rect","fill_round_rect","fill_triangle","flip_horizontal","flip_vertical","fmt","from","from","from","from","get_pixel","hash","height","idle","init_random_seed","into","into","into","into","invert","just_pressed","just_released","new","next_frame","not","not_pressed","partial_cmp","poll_buttons","pressed","print","set_cursor","set_cursor_x","set_cursor_y","set_frame_rate","set_text_background_color","set_text_color","set_text_size","set_text_wrap","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","width","x","x","y","y","ArduboyTones","arduboy_tone_pitch","borrow","borrow_mut","from","into","new","no_tone","playing","tone","tone2","tone3","tones","tones_in_ram","try_from","try_into","type_id","volume_mode","NOTE_A0","NOTE_A0H","NOTE_A1","NOTE_A1H","NOTE_A2","NOTE_A2H","NOTE_A3","NOTE_A3H","NOTE_A4","NOTE_A4H","NOTE_A5","NOTE_A5H","NOTE_A6","NOTE_A6H","NOTE_A7","NOTE_A7H","NOTE_A8","NOTE_A8H","NOTE_A9","NOTE_A9H","NOTE_AS0","NOTE_AS0H","NOTE_AS1","NOTE_AS1H","NOTE_AS2","NOTE_AS2H","NOTE_AS3","NOTE_AS3H","NOTE_AS4","NOTE_AS4H","NOTE_AS5","NOTE_AS5H","NOTE_AS6","NOTE_AS6H","NOTE_AS7","NOTE_AS7H","NOTE_AS8","NOTE_AS8H","NOTE_AS9","NOTE_AS9H","NOTE_B0","NOTE_B0H","NOTE_B1","NOTE_B1H","NOTE_B2","NOTE_B2H","NOTE_B3","NOTE_B3H","NOTE_B4","NOTE_B4H","NOTE_B5","NOTE_B5H","NOTE_B6","NOTE_B6H","NOTE_B7","NOTE_B7H","NOTE_B8","NOTE_B8H","NOTE_B9","NOTE_B9H","NOTE_C0","NOTE_C0H","NOTE_C1","NOTE_C1H","NOTE_C2","NOTE_C2H","NOTE_C3","NOTE_C3H","NOTE_C4","NOTE_C4H","NOTE_C5","NOTE_C5H","NOTE_C6","NOTE_C6H","NOTE_C7","NOTE_C7H","NOTE_C8","NOTE_C8H","NOTE_C9","NOTE_C9H","NOTE_CS0","NOTE_CS0H","NOTE_CS1","NOTE_CS1H","NOTE_CS2","NOTE_CS2H","NOTE_CS3","NOTE_CS3H","NOTE_CS4","NOTE_CS4H","NOTE_CS5","NOTE_CS5H","NOTE_CS6","NOTE_CS6H","NOTE_CS7","NOTE_CS7H","NOTE_CS8","NOTE_CS8H","NOTE_CS9","NOTE_CS9H","NOTE_D0","NOTE_D0H","NOTE_D1","NOTE_D1H","NOTE_D2","NOTE_D2H","NOTE_D3","NOTE_D3H","NOTE_D4","NOTE_D4H","NOTE_D5","NOTE_D5H","NOTE_D6","NOTE_D6H","NOTE_D7","NOTE_D7H","NOTE_D8","NOTE_D8H","NOTE_D9","NOTE_D9H","NOTE_DS0","NOTE_DS0H","NOTE_DS1","NOTE_DS1H","NOTE_DS2","NOTE_DS2H","NOTE_DS3","NOTE_DS3H","NOTE_DS4","NOTE_DS4H","NOTE_DS5","NOTE_DS5H","NOTE_DS6","NOTE_DS6H","NOTE_DS7","NOTE_DS7H","NOTE_DS8","NOTE_DS8H","NOTE_DS9","NOTE_DS9H","NOTE_E0","NOTE_E0H","NOTE_E1","NOTE_E1H","NOTE_E2","NOTE_E2H","NOTE_E3","NOTE_E3H","NOTE_E4","NOTE_E4H","NOTE_E5","NOTE_E5H","NOTE_E6","NOTE_E6H","NOTE_E7","NOTE_E7H","NOTE_E8","NOTE_E8H","NOTE_E9","NOTE_E9H","NOTE_F0","NOTE_F0H","NOTE_F1","NOTE_F1H","NOTE_F2","NOTE_F2H","NOTE_F3","NOTE_F3H","NOTE_F4","NOTE_F4H","NOTE_F5","NOTE_F5H","NOTE_F6","NOTE_F6H","NOTE_F7","NOTE_F7H","NOTE_F8","NOTE_F8H","NOTE_F9","NOTE_F9H","NOTE_FS0","NOTE_FS0H","NOTE_FS1","NOTE_FS1H","NOTE_FS2","NOTE_FS2H","NOTE_FS3","NOTE_FS3H","NOTE_FS4","NOTE_FS4H","NOTE_FS5","NOTE_FS5H","NOTE_FS6","NOTE_FS6H","NOTE_FS7","NOTE_FS7H","NOTE_FS8","NOTE_FS8H","NOTE_FS9","NOTE_FS9H","NOTE_G0","NOTE_G0H","NOTE_G1","NOTE_G1H","NOTE_G2","NOTE_G2H","NOTE_G3","NOTE_G3H","NOTE_G4","NOTE_G4H","NOTE_G5","NOTE_G5H","NOTE_G6","NOTE_G6H","NOTE_G7","NOTE_G7H","NOTE_G8","NOTE_G8H","NOTE_G9","NOTE_G9H","NOTE_GS0","NOTE_GS0H","NOTE_GS1","NOTE_GS1H","NOTE_GS2","NOTE_GS2H","NOTE_GS3","NOTE_GS3H","NOTE_GS4","NOTE_GS4H","NOTE_GS5","NOTE_GS5H","NOTE_GS6","NOTE_GS6H","NOTE_GS7","NOTE_GS7H","NOTE_GS8","NOTE_GS8H","NOTE_GS9","NOTE_GS9H","NOTE_REST","TONES_END","TONES_REPEAT","TONE_HIGH_VOLUME","VOLUME_ALWAYS_HIGH","VOLUME_ALWAYS_NORMAL","VOLUME_IN_TONE","A","A_BUTTON","B","B_BUTTON","ButtonSet","DOWN","DOWN_BUTTON","LEFT","LEFT_BUTTON","RIGHT","RIGHT_BUTTON","UP","UP_BUTTON","flag_set","BLUE_LED","GREEN_LED","RED_LED","RGB_OFF","RGB_ON","draw_erase","draw_external_mask","draw_override","draw_plus_mask","draw_self_masked","draw_erase","draw_external_mask","draw_override","draw_plus_mask","draw_self_masked"],"q":[[0,"arduboy_rust"],[22,"arduboy_rust::arduboy2"],[37,"arduboy_rust::arduboy_tone"],[39,"arduboy_rust::arduboy_tone::arduboy_tone_pitch"],[286,"arduboy_rust::arduino"],[289,"arduboy_rust::c"],[290,"arduboy_rust::hardware"],[292,"arduboy_rust::hardware::buttons"],[310,"arduboy_rust::hardware::led"],[315,"arduboy_rust::heapless"],[678,"arduboy_rust::heapless::binary_heap"],[708,"arduboy_rust::heapless::sorted_linked_list"],[818,"arduboy_rust::prelude"],[946,"arduboy_rust::prelude::arduboy2"],[1044,"arduboy_rust::prelude::arduboy_tone"],[1062,"arduboy_rust::prelude::arduboy_tone::arduboy_tone_pitch"],[1309,"arduboy_rust::prelude::buttons"],[1323,"arduboy_rust::prelude::led"],[1328,"arduboy_rust::prelude::sprites"],[1333,"arduboy_rust::sprites"]],"d":["This is the struct to interact in a save way with the …","This is the struct to interact in a save way with the …","Led is off","This item is to chose between Black or White","This is the struct to store and read structs objects …","Use this struct to store and read single bytes to/from …","The standard font size of the arduboy","The standard height of the arduboy","The standard width of the arduboy","Led is on","This is the Module to interact in a save way with the …","This is the Module to interact in a save way with the …","This is the Module to interact in a save way with the …","Clib functions you can use on the Arduboy","This is the way to go if you want print some random text","Create a const raw pointer to a sprite as u8, without …","Create a const raw pointer to a [u8;_] that saves text, …","Create a const raw pointer to a sprite as u16, without …","This is the Module to interact in a save way with the …","This is the important one to use this library effective in …","Create a space for Progmem variable","This is the module to interact in a save way with the …","This is the struct to interact in a save way with the …","Led is off","This item is to chose between Black or White","The standard font size of the arduboy","The standard height of the arduboy","This struct is used by a few Arduboy functions.","This struct is used by a few Arduboy functions.","The standard width of the arduboy","Led is on","Rect height","Rect width","Position X","Position X","Position Y","Position Y","This is the struct to interact in a save way with the …","A list of all tones available and used by the Sounds …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","A Arduino function to pause the cpu circles for a given …","A Arduino function to get a random number between 2 numbers","A Arduino function to get a random number smaller than the …","A C function to get the length of a string","A list of all six buttons available on the Arduboy","A list of all LED variables available","Just a const for the A button","Just a const for the A button","Just a const for the B button","Just a const for the B button","This struct gives the library a understanding what Buttons …","Just a const for the DOWN button","Just a const for the DOWN button","Just a const for the LEFT button","Just a const for the LEFT button","Just a const for the RIGHT button","Just a const for the RIGHT button","Just a const for the UP button","Just a const for the UP button","","","","","","Just a const for the blue led","Just a const for the green led","Just a const for the red led","Just a const for led off","Just a const for led on","A priority queue implemented with a binary heap.","A fixed capacity double-ended queue.","A view into an entry in the map","A heapless::IndexMap using the default FNV hasher","A heapless::IndexSet using the default FNV hasher. A list …","A “history buffer”, similar to a write-only ring …","Fixed capacity IndexMap","Fixed capacity IndexSet.","A fixed capacity map / dictionary that performs lookups …","The entry corresponding to the key K exists in the map","An occupied entry which can be manipulated","An iterator on the underlying buffer ordered from oldest …","A fixed capacity String","The entry corresponding to the key K does not exist in the …","A view into an empty slot in the underlying map","A fixed capacity Vec","","","Returns a raw pointer to the vector’s buffer, which may …","Returns a pair of mutable slices which contain, in order, …","Converts a String into a mutable string slice.","Returns a mutable reference to the contents of this String.","Returns a raw pointer to the vector’s buffer.","","","","","","Returns the array slice backing the buffer, without …","Extracts a slice containing the entire vector.","Returns a pair of slices which contain, in order, the …","Extracts a string slice containing the entire string.","Provides a reference to the back element, or None if the …","Provides a mutable reference to the back element, or None …","A priority queue implemented with a binary heap.","","","","","","","","","","","","","","","","","","","","","","","","","Returns the maximum number of elements the deque can hold.","Returns the capacity of the buffer, which is the length of …","Returns the number of elements the map can hold","Returns the number of elements the set can hold","Returns the number of elements that the map can hold","Returns the maximum number of elements the String can hold","Returns the maximum number of elements the vector can hold.","Returns the capacity of the binary heap.","Clears the deque, removing all values.","Clears the buffer, replacing every element with the …","Remove all key-value pairs in the map, while preserving …","Clears the set, removing all values.","Clears the map, removing all key-value pairs","Truncates this String, removing all contents.","Clears the vector, removing all values.","Drops all items from the binary heap.","Clears the buffer, replacing every element with the given …","","","","","","","","","","","Returns true if the set contains a value.","Returns true if the map contains a value for the specified …","Returns true if the map contains a value for the specified …","","","","","","","","","","","","","","Visits the values representing the difference, i.e. the …","","","","","Returns true if needle is a suffix of the Vec.","Returns an entry for the corresponding key","","","","","","","","","","","","","","","","","","","","","Extends the vec from an iterator.","Clones and writes all elements in a slice to the buffer.","Clones and appends all elements in a slice to the Vec.","Get the first key-value pair","Get the first value","Get the first key-value pair, with mutable access to the …","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","","","","","Constructs a new vector with a fixed capacity of N and …","","Provides a reference to the front element, or None if the …","Provides a mutable reference to the front element, or None …","Gets a reference to the value associated with this entry","Returns a reference to the value corresponding to the key.","Returns a reference to the value corresponding to the key","Gets a mutable reference to the value associated with this …","Returns a mutable reference to the value corresponding to …","Returns a mutable reference to the value corresponding to …","","","","","","","","","Overwrites the underlying map’s value with this entry’…","Inserts this entry into to underlying map, yields a …","Inserts a key-value pair into the map.","Adds a value to the set.","Inserts a key-value pair into the map.","Inserts an element at position index within the vector, …","Visits the values representing the intersection, i.e. the …","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Returns the contents of the vector as an array of length M …","Converts a String into a byte vector.","","","","","","","","","","","","","","Consumes this entry to yield to key associated with it","Consumes this entry and yields a reference to the …","Returns the underlying Vec<T,N>. Order is arbitrary and …","Returns true if self has no elements in common with other. …","Returns whether the deque is empty.","Returns true if the map contains no elements.","Returns true if the set contains no elements.","Returns true if the map contains no elements","Returns true if the vec is empty","Checks if the binary heap is empty.","Returns whether the deque is full (i.e. if …","Returns true if the vec is full","Returns true if the set is a subset of another, i.e. other …","Examples","Returns an iterator over the deque.","Return an iterator over the key-value pairs of the map, in …","Return an iterator over the values of the set, in their …","An iterator visiting all key-value pairs in arbitrary …","Returns an iterator visiting all values in the underlying …","Returns an iterator that allows modifying each value.","Return an iterator over the key-value pairs of the map, in …","An iterator visiting all key-value pairs in arbitrary …","Returns a mutable iterator visiting all values in the …","Gets a reference to the key that this entity corresponds to","Get the key associated with this entry","Return an iterator over the keys of the map, in their order","An iterator visiting all keys in arbitrary order","Get the last key-value pair","Get the last value","Get the last key-value pair, with mutable access to the …","Returns the number of elements currently in the deque.","Returns the current fill level of the buffer.","Return the number of key-value pairs in the map.","Returns the number of elements in the set.","Returns the number of elements in this map","Returns the length of the binary heap.","","","","Constructs a new, empty deque with a fixed capacity of N","Constructs a new history buffer.","Creates an empty IndexMap.","Creates an empty IndexSet","Creates an empty LinearMap","Constructs a new, empty String with a fixed capacity of N …","Constructs a new, empty vector with a fixed capacity of N","Creates an empty BinaryHeap as a $K-heap.","Constructs a new history buffer, where every element is …","","Returns an iterator for iterating over the buffer from …","","","Returns the top (greatest if max-heap, smallest if …","Returns a mutable reference to the greatest item in the …","Removes the last character from the string buffer and …","Removes the last element from a vector and returns it, or …","Removes the top (greatest if max-heap, smallest if …","Removes the item from the back of the deque and returns …","Removes an item from the back of the deque and returns it, …","Removes the item from the front of the deque and returns …","Removes an item from the front of the deque and returns …","Removes the last element from a vector and returns it","Removes the top (greatest if max-heap, smallest if …","Appends the given char to the end of this String.","Appends an item to the back of the collection","Pushes an item onto the binary heap.","Appends an item to the back of the deque","Appends an item to the back of the deque","Appends an item to the front of the deque","Appends an item to the front of the deque","Appends a given string slice onto the end of this String.","Appends an item to the back of the collection","Pushes an item onto the binary heap without first checking …","Returns a reference to the most recently written value.","Removes this entry from the map and yields its value","Same as swap_remove","Removes a value from the set. Returns true if the value …","Removes a key from the map, returning the value at the key …","Removes and returns the element at position index within …","Removes this entry from the map and yields its …","Resizes the Vec in-place so that len is equal to new_len.","Resizes the Vec in-place so that len is equal to new_len.","Retains only the elements specified by the predicate.","Retains only the elements specified by the predicate, …","Forces the length of the vector to new_len.","A fixed sorted priority linked list, similar to BinaryHeap …","Returns true if needle is a prefix of the Vec.","Remove the key-value pair equivalent to key and return its …","Removes an element from the vector and returns it.","Removes an element from the vector and returns it.","Visits the values representing the symmetric difference, …","Shortens this String to the specified length.","Shortens the vector, keeping the first len elements and …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Visits the values representing the union, i.e. all the …","Return an iterator over the values of the map, in their …","An iterator visiting all values in arbitrary order","Return an iterator over mutable references to the the …","An iterator visiting all values mutably in arbitrary order","Writes an element to the buffer, overwriting the oldest …","","","","A priority queue implemented with a binary heap.","The binary heap kind: min-heap or max-heap","Max-heap","Min-heap","Structure wrapping a mutable reference to the greatest …","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Removes the peeked value from the heap and returns it.","","","","","","","","","","Comes from SortedLinkedList::find_mut.","Iterator for the linked list.","The linked list kind: min-list or max-list","Index for the SortedLinkedList with specific backing …","Index for the SortedLinkedList with specific backing …","Index for the SortedLinkedList with specific backing …","Marker for Max sorted SortedLinkedList.","Marker for Min sorted SortedLinkedList.","A node in the SortedLinkedList.","The linked list.","Trait for defining an index for the linked list, never …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Find an element in the list that can be changed and …","This will resort the element into the correct position in …","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Checks if the linked list is empty.","Checks if the linked list is full.","Get an iterator over the sorted list.","Create a new linked list.","Create a new linked list.","Create a new linked list.","","","","","Peek at the first element.","Pops the first element in the list.","This will pop the element from the list.","Pop an element from the list without checking so the list …","Pushes an element to the linked list and sorts it into …","Pushes a value onto the list without checking if the list …","","","","","","","","","","","","","","","","","","","","","","","","","","","","Just a const for the A button","Just a const for the A button","This is the struct to interact in a save way with the …","This is the struct to interact in a save way with the …","Just a const for the B button","Just a const for the blue led","Just a const for the B button","","","Led is off","This struct gives the library a understanding what Buttons …","This item is to chose between Black or White","Just a const for the DOWN button","Just a const for the DOWN button","","This is the struct to store and read structs objects …","Use this struct to store and read single bytes to/from …","The standard font size of the arduboy","Just a const for the green led","The standard height of the arduboy","","Just a const for the LEFT button","Just a const for the LEFT button","A fixed capacity map / dictionary that performs lookups …","","","This struct is used by a few Arduboy functions.","","Just a const for the red led","Just a const for led off","Just a const for led on","Just a const for the RIGHT button","Just a const for the RIGHT button","This struct is used by a few Arduboy functions.","A fixed capacity String","Just a const for the UP button","Just a const for the UP button","A fixed capacity Vec","The standard width of the arduboy","Led is on","This is the Module to interact in a save way with the …","This is the Module to interact in a save way with the …","","","","","","","","","","A list of all six buttons available on the Arduboy","Equivalent to C’s char type.","Equivalent to C’s double type.","Equivalent to C’s float type.","Equivalent to C’s signed int (int) type.","Equivalent to C’s signed long (long) type.","Equivalent to C’s signed long long (long long) type.","Equivalent to C’s size_t type, from stddef.h (or cstddef …","Equivalent to C’s unsigned char type.","Equivalent to C’s unsigned int type.","Equivalent to C’s unsigned long type.","Equivalent to C’s unsigned long long type.","","","","","","","A Arduino function to pause the cpu circles for a given …","","","This is the way to go if you want print some random text","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Create a const raw pointer to a sprite as u8, without …","Create a const raw pointer to a [u8;_] that saves text, …","Create a const raw pointer to a sprite as u16, without …","","","Rect height","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","A list of all LED variables available","","","","","","","","Create a space for Progmem variable","","A Arduino function to get a random number between 2 numbers","A Arduino function to get a random number smaller than the …","","This is the module to interact in a save way with the …","A C function to get the length of a string","","","","","","","","","","","","","","Rect width","","Position X","Position X","Position Y","Position Y","This is the struct to interact in a save way with the …","Led is off","This item is to chose between Black or White","The standard font size of the arduboy","The standard height of the arduboy","This struct is used by a few Arduboy functions.","This struct is used by a few Arduboy functions.","The standard width of the arduboy","Led is on","Get the current sound state.","Turn sound off (mute).","Turn sound on.","Combines the use function of audio_on() and …","Save the current sound state in EEPROM.","Toggle the sound on/off state.","Initialize the hardware, display the boot logo, provide …","","","","","","","","","Clear the display buffer and set the text cursor to …","","","Test if a point falls within a rectangle.","Test if a rectangle is intersecting with another rectangle.","Set the RGB LEDs digitally, to either fully on or fully …","Set one of the RGB LEDs digitally, to either fully on or …","Copy the contents of the display buffer to the display. …","Copy the contents of the display buffer to the display. …","Draw a circle of a given radius.","Draw a horizontal line.","Draw a vertical line.","Set a single pixel in the display buffer to the specified …","Draw a rectangle of a specified width and height.","Draw a rectangle with rounded corners.","Draw a triangle given the coordinates of each corner.","","Indicate if the specified number of frames has elapsed.","Draw a filled-in circle of a given radius.","Draw a filled-in rectangle of a specified width and height.","Draw a filled-in rectangle with rounded corners.","Draw a filled-in triangle given the coordinates of each …","Flip the display horizontally or set it back to normal.","Flip the display vertically or set it back to normal.","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the state of the given pixel in the screen buffer.","","Rect height","Idle the CPU to save power.","Seed the random number generator with a random value.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Invert the entire display or set it back to normal.","Check if a button has just been pressed.","Check if a button has just been released.","gives you a new instance of the Arduboy2","Indicate that it’s time to render the next frame.","","Test if the specified buttons are not pressed.","","Poll the buttons and track their state over time.","Test if the all of the specified buttons are pressed.","The Arduino Print class is available for writing text to …","Set the location of the text cursor.","Set the X coordinate of the text cursor location.","Set the Y coordinate of the text cursor location.","Set the frame rate used by the frame control functions.","Set the text background color.","Set the text foreground color.","Set the text character size.","Set or disable text wrap mode.","","","","","","","","","","","","","Rect width","Position X","Position X","Position Y","Position Y","This is the struct to interact in a save way with the …","A list of all tones available and used by the Sounds …","","","Returns the argument unchanged.","Calls U::from(self).","Get a new instance of ArduboyTones","Stop playing the tone or sequence.","Check if a tone or tone sequence is playing.","Play a single tone.","Play two tones in sequence.","Play three tones in sequence.","Play a tone sequence from frequency/duration pairs in a …","Play a tone sequence from frequency/duration pairs in an …","","","","Set the volume to always normal, always high, or tone …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Just a const for the A button","Just a const for the A button","Just a const for the B button","Just a const for the B button","This struct gives the library a understanding what Buttons …","Just a const for the DOWN button","Just a const for the DOWN button","Just a const for the LEFT button","Just a const for the LEFT button","Just a const for the RIGHT button","Just a const for the RIGHT button","Just a const for the UP button","Just a const for the UP button","","Just a const for the blue led","Just a const for the green led","Just a const for the red led","Just a const for led off","Just a const for led on","“Erase” a sprite.","Draw a sprite using a separate image and mask array.","Draw a sprite by replacing the existing content completely.","Draw a sprite using an array containing both image and …","Draw a sprite using only the bits set to 1.","“Erase” a sprite.","Draw a sprite using a separate image and mask array.","Draw a sprite by replacing the existing content completely.","Draw a sprite using an array containing both image and …","Draw a sprite using only the bits set to 1."],"i":[0,0,79,0,0,0,0,0,0,79,0,0,0,0,0,0,0,0,0,0,0,0,0,79,0,0,0,0,0,0,79,81,81,81,80,81,80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,5,5,5,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,33,0,0,0,33,0,0,7,7,7,9,10,10,7,13,10,10,7,7,13,7,9,10,9,9,0,9,13,33,44,48,18,19,20,10,7,23,26,9,13,33,44,48,18,19,20,10,7,23,26,9,13,18,19,20,10,7,23,9,13,18,19,20,10,7,23,13,9,18,19,20,10,7,23,26,10,7,19,18,20,9,13,18,19,20,10,7,23,13,10,7,10,7,19,9,13,20,7,7,18,18,19,20,10,10,10,7,7,7,7,7,7,13,13,18,18,19,19,7,7,7,13,7,18,19,18,9,13,18,19,20,10,10,7,23,9,13,33,44,48,18,19,20,10,10,10,10,10,10,10,10,10,10,7,23,26,18,19,20,10,10,10,7,7,10,9,9,44,18,20,44,18,20,10,10,7,7,18,20,18,20,44,48,18,19,20,7,19,9,13,33,44,48,18,19,20,10,7,23,26,7,10,9,9,9,18,18,18,19,20,7,7,7,23,26,48,44,23,19,9,18,19,20,7,23,9,7,19,19,9,18,19,20,23,9,18,20,23,44,48,18,20,18,19,18,9,13,18,19,20,23,10,10,10,9,13,18,19,20,10,7,23,13,26,13,10,7,23,23,10,7,23,9,9,9,9,7,23,10,7,23,9,9,9,9,10,7,23,13,44,18,19,20,7,44,7,7,7,7,7,0,7,18,7,7,19,10,7,9,13,33,44,48,18,19,20,10,7,7,23,26,9,13,33,44,48,18,19,20,10,7,23,26,9,13,33,44,48,18,19,20,10,7,23,26,19,18,20,18,20,13,10,10,7,0,0,0,0,0,84,85,62,84,85,62,62,62,62,84,85,62,84,85,62,62,84,85,62,84,85,62,84,85,62,0,0,0,0,0,0,0,0,0,0,0,86,87,88,72,73,71,66,67,68,86,87,88,72,73,71,66,67,68,66,67,68,66,67,68,71,71,72,71,66,67,68,72,71,72,66,67,68,86,87,88,72,73,71,66,67,68,86,87,88,72,73,71,66,67,68,73,72,72,72,72,72,72,73,66,67,68,72,72,71,72,72,72,86,87,88,72,73,71,66,67,68,86,87,88,72,73,71,66,67,68,86,87,88,72,73,71,66,67,68,0,0,0,0,0,0,0,0,74,79,0,0,0,0,74,0,0,0,0,0,74,0,0,0,74,82,0,0,0,0,0,0,0,0,0,0,0,0,0,79,0,0,5,76,77,5,74,76,77,5,74,0,0,0,0,0,0,0,0,0,0,0,0,5,74,5,74,0,82,0,5,74,0,5,5,74,76,77,5,74,76,76,0,0,0,5,74,81,76,77,76,77,5,74,0,76,77,5,74,82,82,82,0,76,0,0,77,0,0,76,77,5,74,76,77,5,74,76,77,5,74,77,81,77,81,80,81,80,0,79,0,0,0,0,0,0,79,78,78,78,78,78,78,78,81,80,78,79,81,80,78,79,78,79,79,78,78,78,78,78,78,78,78,78,78,78,78,78,79,78,78,78,78,78,78,78,79,81,80,78,79,78,79,81,78,78,81,80,78,79,78,78,78,78,78,79,78,79,78,78,78,78,78,78,78,78,78,78,78,81,80,78,79,81,80,78,79,81,80,78,79,81,81,80,81,80,0,0,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,83,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1],[[2,2],2],[2,2],[3,4],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[5,6],[5,6],[5,6],[5,6],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[7,7],[7,8],[7],[9],[10,11],[10,[[7,[12]]]],[7],[13,8],[10,11],[10,[[8,[12]]]],[7,7],[7,8],[13,8],[7,8],[9],[10,11],[9,14],[9,14],0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[9,4],[13,4],[[[18,[[0,[15,16]],17]]],4],[[[19,[[0,[15,16]],17]]],4],[[[20,[15]]],4],[10,4],[7,4],[[[23,[21,22]]],4],[9],[13],[[[18,[[0,[15,16]],17]]]],[[[19,[[0,[15,16]],17]]]],[[[20,[15]]]],[10],[7],[[[23,[21,22]]]],[[[13,[[0,[24,25]]]],[0,[24,25]]]],[[[9,[25]]],[[9,[25]]]],[[[18,[[0,[15,16,25]],25,25]]],[[18,[[0,[15,16,25]],25,25]]]],[[[19,[[0,[15,16,25]],25]]],[[19,[[0,[15,16,25]],25]]]],[[[20,[[0,[15,25]],25]]],[[20,[[0,[15,25]],25]]]],[10,10],[[[7,[25]]],[[7,[25]]]],[[[23,[[0,[21,25]],22]]],[[23,[[0,[21,25]],22]]]],[[[26,[25]]],[[26,[25]]]],[[10,10],27],[[[7,[21]],[7,[21]]],27],[[[19,[[29,[[0,[15,16,28]]]],[0,[15,16]],17]],[0,[15,16,28]]],6],[[[18,[[29,[[0,[15,16,28]]]],[0,[15,16]],17]],[0,[15,16,28]]],6],[[[20,[15]],15],6],[[],9],[[],13],[[],[[18,[[0,[15,16]],[0,[17,30]]]]]],[[],[[19,[[0,[15,16]],[0,[17,30]]]]]],[[],[[20,[15]]]],[[],10],[[],7],[[],[[23,[21,22]]]],[13,8],[10,11],[7,8],[10,11],[7,8],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],[[31,[[0,[15,16]],17]]]],[9],[13],[20],[7],[[[7,[[32,[[32,[[32,[32]]]]]]]],[8,[[32,[[32,[[32,[32]]]]]]]]],6],[[[18,[[0,[15,16]],17]],[0,[15,16]]],[[33,[[0,[15,16]]]]]],[[[18,[[0,[15,16]],15,17]],[18,[[0,[15,16]],15,17]]],6],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],6],[[[20,[15,[32,[[32,[[32,[32]]]]]]]],[20,[15,[32,[[32,[[32,[32]]]]]]]]],6],[[10,11],6],[[10,11],6],[[10,10],6],[[[7,[32]],8],6],[[[7,[32]],8],6],[[[7,[32]],34],6],[[[7,[32]],8],6],[[[7,[32]],7],6],[[[7,[32]],34],6],[[13,35]],[[[13,[25]],35]],[[[18,[[0,[15,16,24]],24,17]],35]],[[[18,[[0,[15,16]],17]],35]],[[[19,[[0,[15,16]],17]],35]],[[[19,[[0,[15,16,24]],17]],35]],[[[7,[24]],35]],[[7,35]],[[7,35]],[[[13,[25]],[8,[25]]]],[[[7,[25]],[8,[25]]],36],[[[18,[[0,[15,16]],17]]],14],[[[19,[[0,[15,16]],17]]],[[14,[[0,[15,16]]]]]],[[[18,[[0,[15,16]],17]]],14],[[[9,[37]],38],[[36,[39]]]],[[[13,[37]],38],[[36,[39]]]],[[[18,[[0,[15,16,37]],37,17]],38],[[36,[39]]]],[[[19,[[0,[15,16,37]],17]],38],[[36,[39]]]],[[[20,[[0,[15,37]],37]],38],[[36,[39]]]],[[10,38],[[36,[39]]]],[[10,38],[[36,[39]]]],[[[7,[37]],38],[[36,[39]]]],[[[23,[[0,[21,37]],22]],38],[[36,[39]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[2,10],[40,10],[41,10],[11,10],[42,10],[1,10],[43,10],[12,10],[3,10],[[]],[[]],[[]],[35,[[18,[[0,[15,16]],[0,[17,30]]]]]],[35,[[19,[[0,[15,16]],[0,[17,30]]]]]],[35,[[20,[15]]]],[35,10],[35,10],[35,10],[35,7],[[[8,[25]]],[[36,[[7,[25]]]]]],[11,[[36,[10]]]],[9,14],[9,14],[[[44,[[0,[15,16]]]]]],[[[18,[[29,[[0,[16,15,28]]]],[0,[15,16]],17]],[0,[16,15,28]]],14],[[[20,[[29,[[0,[15,28]]]],15]],[0,[15,28]]],14],[[[44,[[0,[15,16]]]]]],[[[18,[[29,[[0,[16,15,28]]]],[0,[15,16]],17]],[0,[16,15,28]]],14],[[[20,[[29,[[0,[15,28]]]],15]],[0,[15,28]]],14],[[10,45]],[[10,46]],[[[7,[16]],45]],[[[7,[47]],46]],[[[18,[[0,[15,16,[29,[[0,[15,16,28]]]]]],17]],[0,[15,16,28]]]],[[[20,[[0,[[29,[[0,[15,28]]]],15]]]],[0,[15,28]]]],[[[18,[[0,[15,16,[29,[[0,[15,16,28]]]]]],17]],[0,[15,16,28]]]],[[[20,[[0,[[29,[[0,[15,28]]]],15]]]],[0,[15,28]]]],[[[44,[[0,[15,16]]]]]],[[[48,[[0,[15,16]]]]],36],[[[18,[[0,[15,16]],17]],[0,[15,16]]],[[36,[14]]]],[[[19,[[0,[15,16]],17]],[0,[15,16]]],[[36,[6,[0,[15,16]]]]]],[[[20,[15]],15],[[36,[14]]]],[[7,4],36],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],[[49,[[0,[15,16]],17]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[7,[[36,[34,7]]]],[10,[[7,[12]]]],[9],[9],[9],[[[18,[[0,[15,16]],17]]]],[[[18,[[0,[15,16]],17]]]],[[[18,[[0,[15,16]],17]]]],[[[19,[[0,[15,16]],17]]]],[[[20,[15]]]],[7],[7],[7],[[[23,[21,22]]]],[[]],[[[48,[[0,[15,16]]]]],[[0,[15,16]]]],[[[44,[[0,[15,16]]]]]],[[[23,[21,22]]],[[7,[21]]]],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],6],[9,6],[[[18,[[0,[15,16]],17]]],6],[[[19,[[0,[15,16]],17]]],6],[[[20,[15]]],6],[7,6],[[[23,[21,22]]],6],[9,6],[7,6],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],6],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],6],[9,50],[[[18,[[0,[15,16]],17]]],[[51,[[0,[15,16]]]]]],[[[19,[[0,[15,16]],17]]],[[52,[[0,[15,16]]]]]],[[[20,[15]]],[[53,[15]]]],[[[23,[21,22]]],[[54,[21]]]],[9,55],[[[18,[[0,[15,16]],17]]],[[56,[[0,[15,16]]]]]],[[[20,[15]]],[[57,[15]]]],[[[23,[21,22]]],[[58,[21]]]],[[[44,[[0,[15,16]]]]],[[0,[15,16]]]],[[[48,[[0,[15,16]]]]],[[0,[15,16]]]],[[[18,[[0,[15,16]],17]]],59],[[[20,[15]]],59],[[[18,[[0,[15,16]],17]]],14],[[[19,[[0,[15,16]],17]]],[[14,[[0,[15,16]]]]]],[[[18,[[0,[15,16]],17]]],14],[9,4],[13,4],[[[18,[[0,[15,16]],17]]],4],[[[19,[[0,[15,16]],17]]],4],[[[20,[15]]],4],[[[23,[21,22]]],4],[[10,10],6],[[10,11],6],[[10,11],6],[[],9],[[],13],[[],[[18,[60]]]],[[],[[19,[60]]]],[[],20],[[],10],[[],7],[[],23],[[[0,[24,25]]],[[13,[[0,[24,25]]]]]],[26,14],[13,26],[[10,10],[[14,[27]]]],[[[7,[[61,[[61,[[61,[61]]]]]]]],[7,[[61,[[61,[[61,[61]]]]]]]]],[[14,[27]]]],[[[23,[21,22]]],[[14,[21]]]],[[[23,[21,22]]],[[14,[[62,[21,22]]]]]],[10,[[14,[63]]]],[7,14],[[[23,[21,22]]],[[14,[21]]]],[9,14],[9],[9,14],[9],[7],[[[23,[21,22]]],21],[[10,63],36],[7,36],[[[23,[21,22]],21],[[36,[21]]]],[9,36],[9],[9,36],[9],[[10,11],36],[7],[[[23,[21,22]],21]],[13,14],[[[44,[[0,[15,16]]]]]],[[[18,[[29,[[0,[16,15,28]]]],[0,[15,16]],17]],[0,[16,15,28]]],14],[[[19,[[29,[[0,[15,16,28]]]],[0,[15,16]],17]],[0,[15,16,28]]],6],[[[20,[[29,[[0,[15,28]]]],15]],[0,[15,28]]],14],[[7,4]],[[[44,[[0,[15,16]]]]]],[[[7,[25]],4,25],36],[[[7,[[0,[25,30]]]],4],36],[[7,64]],[[7,64]],[[7,4]],0,[[[7,[[32,[[32,[[32,[32]]]]]]]],[8,[[32,[[32,[[32,[32]]]]]]]]],6],[[[18,[[29,[[0,[16,15,28]]]],[0,[15,16]],17]],[0,[16,15,28]]],14],[[7,4]],[[7,4]],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],59],[[10,4]],[[7,4]],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[[8,[25]]],[[36,[[7,[25]]]]]],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[[19,[[0,[15,16]],17]],[19,[[0,[15,16]],17]]],59],[[[18,[[0,[15,16]],17]]],59],[[[20,[15]]],59],[[[18,[[0,[15,16]],17]]],59],[[[20,[15]]],59],[13],[[10,63],[[36,[39]]]],[[10,11],[[36,[39]]]],[[[7,[12]],11],[[36,[39]]]],0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[[62,[21,22]]],21],[[[62,[21,22]]],21],[[[62,[21,22]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[[62,[21,22]]],21],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],65],[[],65],[[],65],0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[66,66],[67,67],[68,68],[[66,66],27],[[67,67],27],[[68,68],27],[[[71,[21,69,70]]]],[[[71,[21,69,70]]]],[[[72,[69]]]],[[[71,[21,69,70]]]],[[66,66],6],[[67,67],6],[[68,68],6],[[[72,[21,69,70]],64],[[14,[[71,[21,69,70]]]]]],[[[71,[21,69,70]]]],[[[72,[[0,[21,37]],69,70]],38],[[36,[39]]]],[[66,38],[[36,[39]]]],[[67,38],[[36,[39]]]],[[68,38],[[36,[39]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[72,[21,69,70]]],6],[[[72,[21,69,70]]],6],[[[72,[21,69,70]]],[[73,[21,69,70]]]],[[],[[72,[67]]]],[[],[[72,[66]]]],[[],[[72,[68]]]],[[[73,[21,69,70]]],14],[[66,66],[[14,[27]]]],[[67,67],[[14,[27]]]],[[68,68],[[14,[27]]]],[[[72,[21,69,70]]],[[14,[21]]]],[[[72,[21,69,70]]],[[36,[21]]]],[[[71,[21,69,70]]],21],[[[72,[21,69,70]]],21],[[[72,[21,69,70]],21],[[36,[21]]]],[[[72,[21,69,70]],21]],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],[[],65],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[5,5],5],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],0,0,0,0,0,0,0,0,0,0,0,0,[5,5],[74,74],[[5,5],27],[[74,74],27],[[21,21,21],21],[[]],[1],[[5,5],6],[[74,74],6],0,0,[[5,38],75],[[74,38],75],[[]],[[]],[[]],[[]],[76],[76],0,0,0,[[5,46]],[[74,46]],0,[76],[77],[[]],[[]],[[]],[[]],0,[41,76],[41,77],[[5,5],[[14,[27]]]],[[74,74],[[14,[27]]]],[[]],[[]],[[]],0,[76],[[2,2],2],[2,2],[77,12],0,[3,4],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],65],[[],65],[[],65],[[],65],[[77,12]],0,[[77,12]],0,0,0,0,0,0,0,0,0,0,0,0,0,[78,6],[78],[78],[78],[78],[78],[78],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[78],[79,79],[[79,79],27],[[78,80,81],6],[[78,81,81],6],[[78,12,12,12]],[[78,12,12]],[78],[78],[[78,41,41,12,79]],[[78,41,41,12,79]],[[78,41,41,12,79]],[[78,41,41,79]],[[78,41,41,12,12,79]],[[78,41,41,12,12,12,79]],[[78,41,41,41,41,41,41,79]],[[79,79],6],[[78,12],6],[[78,41,41,12,79]],[[78,41,41,12,12,79]],[[78,41,41,12,12,12,79]],[[78,41,41,41,41,41,41,79]],[[78,6]],[[78,6]],[[79,38],75],[[]],[[]],[[]],[[]],[[78,12,12],79],[[79,46]],0,[78],[78],[[]],[[]],[[]],[[]],[[78,6]],[[78,5],6],[[78,5],6],[[],78],[78,6],[79],[[78,5],6],[[79,79],[[14,[27]]]],[78],[[78,5],6],[[78,82]],[[78,41,41]],[[78,41]],[[78,41]],[[78,12]],[[78,79]],[[78,79]],[[78,12]],[[78,6]],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],36],[[],65],[[],65],[[],65],[[],65],0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[],83],[83],[83,6],[[83,40,1]],[[83,40,1,40,1]],[[83,40,1,40,1,40,1]],[[83,40]],[[83,1]],[[],36],[[],36],[[],65],[[83,12]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[41,41,12,12]],[[41,41,12,12,12,12]],[[41,41,12,12]],[[41,41,12,12]],[[41,41,12,12]],[[41,41,12,12]],[[41,41,12,12,12,12]],[[41,41,12,12]],[[41,41,12,12]],[[41,41,12,12]]],"c":[],"p":[[15,"u32"],[15,"i32"],[15,"i8"],[15,"usize"],[3,"ButtonSet"],[15,"bool"],[3,"Vec"],[15,"slice"],[3,"Deque"],[3,"String"],[15,"str"],[15,"u8"],[3,"HistoryBuffer"],[4,"Option"],[8,"Eq"],[8,"Hash"],[8,"BuildHasher"],[3,"IndexMap"],[3,"IndexSet"],[3,"LinearMap"],[8,"Ord"],[8,"Kind"],[3,"BinaryHeap"],[8,"Copy"],[8,"Clone"],[3,"OldestOrdered"],[4,"Ordering"],[8,"Sized"],[8,"Borrow"],[8,"Default"],[3,"Difference"],[8,"PartialEq"],[4,"Entry"],[15,"array"],[8,"IntoIterator"],[4,"Result"],[8,"Debug"],[3,"Formatter"],[3,"Error"],[15,"u16"],[15,"i16"],[15,"u64"],[15,"i64"],[3,"OccupiedEntry"],[8,"Hasher"],[8,"Hasher"],[8,"Hash"],[3,"VacantEntry"],[3,"Intersection"],[3,"Iter"],[3,"Iter"],[3,"Iter"],[3,"Iter"],[3,"Iter"],[3,"IterMut"],[3,"IterMut"],[3,"IterMut"],[3,"IterMut"],[8,"Iterator"],[3,"BuildHasherDefault"],[8,"PartialOrd"],[3,"PeekMut"],[15,"char"],[8,"FnMut"],[3,"TypeId"],[3,"LinkedIndexU8"],[3,"LinkedIndexU16"],[3,"LinkedIndexUsize"],[8,"SortedLinkedListIndex"],[8,"Kind"],[3,"FindMut"],[3,"SortedLinkedList"],[3,"Iter"],[4,"Base"],[6,"Result"],[3,"EEPROM"],[3,"EEPROMBYTE"],[3,"Arduboy2"],[4,"Color"],[3,"Point"],[3,"Rect"],[8,"Printable"],[3,"ArduboyTones"],[4,"Min"],[4,"Max"],[3,"Min"],[3,"Max"],[3,"Node"]]},\ +"atomic_polyfill":{"doc":"","t":"RNNDDDENNNLLLLLLLLLLLLFLLLLFLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLFLLLLLLLLLLLLLLL","n":["ATOMIC_BOOL_INIT","AcqRel","Acquire","AtomicBool","AtomicI8","AtomicU8","Ordering","Relaxed","Release","SeqCst","as_ptr","as_ptr","as_ptr","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","compiler_fence","default","default","default","eq","fence","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from_mut","from_mut","from_mut","from_mut_slice","from_mut_slice","from_mut_slice","from_ptr","from_ptr","from_ptr","get_mut","get_mut","get_mut","get_mut_slice","get_mut_slice","get_mut_slice","hash","into","into","into","into","into_inner","into_inner","into_inner","load","load","load","new","new","new","spin_loop_hint","store","store","store","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id"],"q":[[0,"atomic_polyfill"]],"d":["An AtomicBool initialized to false.","Has the effects of both Acquire and Release together: For …","When coupled with a load, if the loaded value was written …","A boolean type which can be safely shared between threads.","An integer type which can be safely shared between threads.","An integer type which can be safely shared between threads.","Atomic memory orderings","No ordering constraints, only atomic operations.","When coupled with a store, all previous operations become …","Like Acquire/Release/AcqRel (for load, store, and …","Returns a mutable pointer to the underlying bool.","Returns a mutable pointer to the underlying integer.","Returns a mutable pointer to the underlying integer.","","","","","","","","","","A compiler memory fence.","Creates an AtomicBool initialized to false.","","","","An atomic fence.","","","","","Converts a bool into an AtomicBool.","Returns the argument unchanged.","Returns the argument unchanged.","Converts an i8 into an AtomicI8.","Returns the argument unchanged.","Converts an u8 into an AtomicU8.","Returns the argument unchanged.","Get atomic access to a &mut bool.","Get atomic access to a &mut i8.","Get atomic access to a &mut u8.","Get atomic access to a &mut [bool] slice.","Get atomic access to a &mut [i8] slice.","Get atomic access to a &mut [u8] slice.","Creates a new AtomicBool from a pointer.","Creates a new reference to an atomic integer from a …","Creates a new reference to an atomic integer from a …","Returns a mutable reference to the underlying bool.","Returns a mutable reference to the underlying integer.","Returns a mutable reference to the underlying integer.","Get non-atomic access to a &mut [AtomicBool] slice.","Get non-atomic access to a &mut [AtomicI8] slice","Get non-atomic access to a &mut [AtomicU8] slice","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Consumes the atomic and returns the contained value.","Consumes the atomic and returns the contained value.","Consumes the atomic and returns the contained value.","Loads a value from the bool.","Loads a value from the atomic integer.","Loads a value from the atomic integer.","Creates a new AtomicBool.","Creates a new atomic integer.","Creates a new atomic integer.","Signals the processor that it is inside a busy-wait …","Stores a value into the bool.","Stores a value into the atomic integer.","Stores a value into the atomic integer.","","","","","","","","","","","",""],"i":[0,7,7,0,0,0,0,7,7,7,1,3,5,1,7,3,5,1,7,3,5,7,0,1,3,5,7,0,1,7,3,5,1,1,7,3,3,5,5,1,3,5,1,3,5,1,3,5,1,3,5,1,3,5,7,1,7,3,5,1,3,5,1,3,5,1,3,5,0,1,3,5,1,7,3,5,1,7,3,5,1,7,3,5],"f":[0,0,0,0,0,0,0,0,0,0,[1,2],[3,4],[5,6],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[7,7],[7],[[],1],[[],3],[[],5],[[7,7],2],[7],[[1,8],[[10,[9]]]],[[7,8],[[10,[9]]]],[[3,8],[[10,[9]]]],[[5,8],[[10,[9]]]],[2,1],[[]],[[]],[4,3],[[]],[6,5],[[]],[2,1],[4,3],[6,5],[[[11,[2]]],[[11,[1]]]],[[[11,[4]]],[[11,[3]]]],[[[11,[6]]],[[11,[5]]]],[2,1],[4,3],[6,5],[1,2],[3,4],[5,6],[[[11,[1]]],[[11,[2]]]],[[[11,[3]]],[[11,[4]]]],[[[11,[5]]],[[11,[6]]]],[[7,12]],[[]],[[]],[[]],[[]],[1,2],[3,4],[5,6],[[1,7],2],[[3,7],4],[[5,7],6],[2,1],[4,3],[6,5],[[]],[[1,2,7]],[[3,4,7]],[[5,6,7]],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],10],[[],13],[[],13],[[],13],[[],13]],"c":[0,68],"p":[[3,"AtomicBool"],[15,"bool"],[3,"AtomicI8"],[15,"i8"],[3,"AtomicU8"],[15,"u8"],[4,"Ordering"],[3,"Formatter"],[3,"Error"],[4,"Result"],[15,"slice"],[8,"Hasher"],[3,"TypeId"]]},\ +"byteorder":{"doc":"This crate provides convenience methods for encoding and …","t":"GEIGEGGLLLLLLLLLLLLLLLLKLLKLLLLLLKLLKLLKLLKLLLLLLLLLLLLLLLLLLLLLLLLLLKLLKLLKLLKLLLKLLKLLLKLLKLLKLLKLLLLLLLLLLLLLLLLLLLLLLLLLKLLKLLKLLKLLLKLLKLLLKLLKLLKLLKLL","n":["BE","BigEndian","ByteOrder","LE","LittleEndian","NativeEndian","NetworkEndian","borrow","borrow","borrow_mut","borrow_mut","clone","clone","cmp","cmp","default","default","eq","eq","fmt","fmt","from","from","from_slice_f32","from_slice_f32","from_slice_f32","from_slice_f64","from_slice_f64","from_slice_f64","from_slice_i128","from_slice_i16","from_slice_i32","from_slice_i64","from_slice_u128","from_slice_u128","from_slice_u128","from_slice_u16","from_slice_u16","from_slice_u16","from_slice_u32","from_slice_u32","from_slice_u32","from_slice_u64","from_slice_u64","from_slice_u64","hash","hash","into","into","partial_cmp","partial_cmp","read_f32","read_f32_into","read_f32_into_unchecked","read_f64","read_f64_into","read_f64_into_unchecked","read_i128","read_i128_into","read_i16","read_i16_into","read_i24","read_i32","read_i32_into","read_i48","read_i64","read_i64_into","read_int","read_int128","read_u128","read_u128","read_u128","read_u128_into","read_u128_into","read_u128_into","read_u16","read_u16","read_u16","read_u16_into","read_u16_into","read_u16_into","read_u24","read_u32","read_u32","read_u32","read_u32_into","read_u32_into","read_u32_into","read_u48","read_u64","read_u64","read_u64","read_u64_into","read_u64_into","read_u64_into","read_uint","read_uint","read_uint","read_uint128","read_uint128","read_uint128","try_from","try_from","try_into","try_into","type_id","type_id","write_f32","write_f32_into","write_f64","write_f64_into","write_i128","write_i128_into","write_i16","write_i16_into","write_i24","write_i32","write_i32_into","write_i48","write_i64","write_i64_into","write_i8_into","write_int","write_int128","write_u128","write_u128","write_u128","write_u128_into","write_u128_into","write_u128_into","write_u16","write_u16","write_u16","write_u16_into","write_u16_into","write_u16_into","write_u24","write_u32","write_u32","write_u32","write_u32_into","write_u32_into","write_u32_into","write_u48","write_u64","write_u64","write_u64","write_u64_into","write_u64_into","write_u64_into","write_uint","write_uint","write_uint","write_uint128","write_uint128","write_uint128"],"q":[[0,"byteorder"]],"d":["A type alias for BigEndian.","Defines big-endian serialization.","ByteOrder describes types that can serialize integers as …","A type alias for LittleEndian.","Defines little-endian serialization.","Defines system native-endian serialization.","Defines network byte order serialization.","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Converts the given slice of IEEE754 single-precision (4 …","","","Converts the given slice of IEEE754 double-precision (8 …","","","Converts the given slice of signed 128 bit integers to a …","Converts the given slice of signed 16 bit integers to a …","Converts the given slice of signed 32 bit integers to a …","Converts the given slice of signed 64 bit integers to a …","Converts the given slice of unsigned 128 bit integers to a …","","","Converts the given slice of unsigned 16 bit integers to a …","","","Converts the given slice of unsigned 32 bit integers to a …","","","Converts the given slice of unsigned 64 bit integers to a …","","","","","Calls U::from(self).","Calls U::from(self).","","","Reads a IEEE754 single-precision (4 bytes) floating point …","Reads IEEE754 single-precision (4 bytes) floating point …","DEPRECATED.","Reads a IEEE754 double-precision (8 bytes) floating point …","Reads IEEE754 single-precision (4 bytes) floating point …","DEPRECATED.","Reads a signed 128 bit integer from buf.","Reads signed 128 bit integers from src into dst.","Reads a signed 16 bit integer from buf.","Reads signed 16 bit integers from src to dst.","Reads a signed 24 bit integer from buf, stored in i32.","Reads a signed 32 bit integer from buf.","Reads signed 32 bit integers from src into dst.","Reads a signed 48 bit integer from buf, stored in i64.","Reads a signed 64 bit integer from buf.","Reads signed 64 bit integers from src into dst.","Reads a signed n-bytes integer from buf.","Reads a signed n-bytes integer from buf.","Reads an unsigned 128 bit integer from buf.","","","Reads unsigned 128 bit integers from src into dst.","","","Reads an unsigned 16 bit integer from buf.","","","Reads unsigned 16 bit integers from src into dst.","","","Reads an unsigned 24 bit integer from buf, stored in u32.","Reads an unsigned 32 bit integer from buf.","","","Reads unsigned 32 bit integers from src into dst.","","","Reads an unsigned 48 bit integer from buf, stored in u64.","Reads an unsigned 64 bit integer from buf.","","","Reads unsigned 64 bit integers from src into dst.","","","Reads an unsigned n-bytes integer from buf.","","","Reads an unsigned n-bytes integer from buf.","","","","","","","","","Writes a IEEE754 single-precision (4 bytes) floating point …","Writes IEEE754 single-precision (4 bytes) floating point …","Writes a IEEE754 double-precision (8 bytes) floating point …","Writes IEEE754 double-precision (8 bytes) floating point …","Writes a signed 128 bit integer n to buf.","Writes signed 128 bit integers from src into dst.","Writes a signed 16 bit integer n to buf.","Writes signed 16 bit integers from src into dst.","Writes a signed 24 bit integer n to buf, stored in i32.","Writes a signed 32 bit integer n to buf.","Writes signed 32 bit integers from src into dst.","Writes a signed 48 bit integer n to buf, stored in i64.","Writes a signed 64 bit integer n to buf.","Writes signed 64 bit integers from src into dst.","Writes signed 8 bit integers from src into dst.","Writes a signed integer n to buf using only nbytes.","Writes a signed integer n to buf using only nbytes.","Writes an unsigned 128 bit integer n to buf.","","","Writes unsigned 128 bit integers from src into dst.","","","Writes an unsigned 16 bit integer n to buf.","","","Writes unsigned 16 bit integers from src into dst.","","","Writes an unsigned 24 bit integer n to buf, stored in u32.","Writes an unsigned 32 bit integer n to buf.","","","Writes unsigned 32 bit integers from src into dst.","","","Writes an unsigned 48 bit integer n to buf, stored in u64.","Writes an unsigned 64 bit integer n to buf.","","","Writes unsigned 64 bit integers from src into dst.","","","Writes an unsigned integer n to buf using only nbytes.","","","Writes an unsigned integer n to buf using only nbytes.","",""],"i":[0,0,0,0,0,0,0,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,25,1,2,25,1,2,25,25,25,25,25,1,2,25,1,2,25,1,2,25,1,2,1,2,1,2,1,2,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,1,2,25,1,2,25,1,2,25,1,2,25,25,1,2,25,1,2,25,25,1,2,25,1,2,25,1,2,25,1,2,1,2,1,2,1,2,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,1,2,25,1,2,25,1,2,25,1,2,25,25,1,2,25,1,2,25,25,1,2,25,1,2,25,1,2,25,1,2],"f":[0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[1,1],[2,2],[[1,1],3],[[2,2],3],[[],1],[[],2],[[1,1],4],[[2,2],4],[[1,5],6],[[2,5],6],[[]],[[]],[[[8,[7]]]],[[[8,[7]]]],[[[8,[7]]]],[[[8,[9]]]],[[[8,[9]]]],[[[8,[9]]]],[[[8,[10]]]],[[[8,[11]]]],[[[8,[12]]]],[[[8,[13]]]],[[[8,[14]]]],[[[8,[14]]]],[[[8,[14]]]],[[[8,[15]]]],[[[8,[15]]]],[[[8,[15]]]],[[[8,[16]]]],[[[8,[16]]]],[[[8,[16]]]],[[[8,[17]]]],[[[8,[17]]]],[[[8,[17]]]],[[1,18]],[[2,18]],[[]],[[]],[[1,1],[[19,[3]]]],[[2,2],[[19,[3]]]],[[[8,[20]]],7],[[[8,[20]],[8,[7]]]],[[[8,[20]],[8,[7]]]],[[[8,[20]]],9],[[[8,[20]],[8,[9]]]],[[[8,[20]],[8,[9]]]],[[[8,[20]]],10],[[[8,[20]],[8,[10]]]],[[[8,[20]]],11],[[[8,[20]],[8,[11]]]],[[[8,[20]]],12],[[[8,[20]]],12],[[[8,[20]],[8,[12]]]],[[[8,[20]]],13],[[[8,[20]]],13],[[[8,[20]],[8,[13]]]],[[[8,[20]],21],13],[[[8,[20]],21],10],[[[8,[20]]],14],[[[8,[20]]],14],[[[8,[20]]],14],[[[8,[20]],[8,[14]]]],[[[8,[20]],[8,[14]]]],[[[8,[20]],[8,[14]]]],[[[8,[20]]],15],[[[8,[20]]],15],[[[8,[20]]],15],[[[8,[20]],[8,[15]]]],[[[8,[20]],[8,[15]]]],[[[8,[20]],[8,[15]]]],[[[8,[20]]],16],[[[8,[20]]],16],[[[8,[20]]],16],[[[8,[20]]],16],[[[8,[20]],[8,[16]]]],[[[8,[20]],[8,[16]]]],[[[8,[20]],[8,[16]]]],[[[8,[20]]],17],[[[8,[20]]],17],[[[8,[20]]],17],[[[8,[20]]],17],[[[8,[20]],[8,[17]]]],[[[8,[20]],[8,[17]]]],[[[8,[20]],[8,[17]]]],[[[8,[20]],21],17],[[[8,[20]],21],17],[[[8,[20]],21],17],[[[8,[20]],21],14],[[[8,[20]],21],14],[[[8,[20]],21],14],[[],22],[[],22],[[],22],[[],22],[[],23],[[],23],[[[8,[20]],7]],[[[8,[7]],[8,[20]]]],[[[8,[20]],9]],[[[8,[9]],[8,[20]]]],[[[8,[20]],10]],[[[8,[10]],[8,[20]]]],[[[8,[20]],11]],[[[8,[11]],[8,[20]]]],[[[8,[20]],12]],[[[8,[20]],12]],[[[8,[12]],[8,[20]]]],[[[8,[20]],13]],[[[8,[20]],13]],[[[8,[13]],[8,[20]]]],[[[8,[24]],[8,[20]]]],[[[8,[20]],13,21]],[[[8,[20]],10,21]],[[[8,[20]],14]],[[[8,[20]],14]],[[[8,[20]],14]],[[[8,[14]],[8,[20]]]],[[[8,[14]],[8,[20]]]],[[[8,[14]],[8,[20]]]],[[[8,[20]],15]],[[[8,[20]],15]],[[[8,[20]],15]],[[[8,[15]],[8,[20]]]],[[[8,[15]],[8,[20]]]],[[[8,[15]],[8,[20]]]],[[[8,[20]],16]],[[[8,[20]],16]],[[[8,[20]],16]],[[[8,[20]],16]],[[[8,[16]],[8,[20]]]],[[[8,[16]],[8,[20]]]],[[[8,[16]],[8,[20]]]],[[[8,[20]],17]],[[[8,[20]],17]],[[[8,[20]],17]],[[[8,[20]],17]],[[[8,[17]],[8,[20]]]],[[[8,[17]],[8,[20]]]],[[[8,[17]],[8,[20]]]],[[[8,[20]],17,21]],[[[8,[20]],17,21]],[[[8,[20]],17,21]],[[[8,[20]],14,21]],[[[8,[20]],14,21]],[[[8,[20]],14,21]]],"c":[53,56],"p":[[4,"BigEndian"],[4,"LittleEndian"],[4,"Ordering"],[15,"bool"],[3,"Formatter"],[6,"Result"],[15,"f32"],[15,"slice"],[15,"f64"],[15,"i128"],[15,"i16"],[15,"i32"],[15,"i64"],[15,"u128"],[15,"u16"],[15,"u32"],[15,"u64"],[8,"Hasher"],[4,"Option"],[15,"u8"],[15,"usize"],[4,"Result"],[3,"TypeId"],[15,"i8"],[8,"ByteOrder"]]},\ +"critical_section":{"doc":"critical-section","t":"DIDGDFKLLLLLLLLLLLLLLLLLLLLLLLLLFKLLOLLLLLLLLLLF","n":["CriticalSection","Impl","Mutex","RawRestoreState","RestoreState","acquire","acquire","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_ref","borrow_ref_mut","clone","clone","fmt","fmt","fmt","from","from","from","get_mut","into","into","into","into_inner","invalid","new","new","release","release","replace","replace_with","set_impl","take","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","with"],"q":[[0,"critical_section"]],"d":["Critical section token.","Methods required for a critical section implementation.","A mutex based on critical sections.","Raw, transparent “restore state”.","Opaque “restore state”.","Acquire a critical section in the current thread.","Acquire the critical section.","Borrows the data for the duration of the critical section.","","","","","","","Borrow the data and call RefCell::borrow","Borrow the data and call RefCell::borrow_mut","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Gets a mutable reference to the contained value when the …","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Unwraps the contained value, consuming the mutex.","Create an invalid, dummy RestoreState.","Creates a new mutex.","Creates a critical section token.","Release the critical section.","Release the critical section.","Borrow the data and call RefCell::replace","Borrow the data and call RefCell::replace_with","Set the critical section implementation.","Borrow the data and call RefCell::take","","","","","","","","","","Execute closure f in a critical section."],"i":[0,0,0,0,0,0,15,3,3,4,1,3,4,1,3,3,4,1,3,4,1,3,4,1,3,3,4,1,3,1,3,4,0,15,3,3,0,3,3,4,1,3,4,1,3,4,1,0],"f":[0,0,0,0,0,[[],1],[[],2],[[3,4]],[[]],[[]],[[]],[[]],[[]],[[]],[[[3,[5]],4],6],[[[3,[5]],4],7],[4,4],[1,1],[[[3,[8]],9],10],[[4,9],10],[[1,9],10],[[]],[[]],[[]],[3],[[]],[[]],[[]],[3],[[],1],[[],3],[[],4],[1],[2],[[[3,[5]],4]],[[[3,[5]],4,11]],0,[[[3,[[5,[12]]]],4],12],[[],13],[[],13],[[],13],[[],13],[[],13],[[],13],[[],14],[[],14],[[],14],[11]],"c":[],"p":[[3,"RestoreState"],[6,"RawRestoreState"],[3,"Mutex"],[3,"CriticalSection"],[3,"RefCell"],[3,"Ref"],[3,"RefMut"],[8,"Debug"],[3,"Formatter"],[6,"Result"],[8,"FnOnce"],[8,"Default"],[4,"Result"],[3,"TypeId"],[8,"Impl"]]},\ +"hash32":{"doc":"32-bit hashing machinery","t":"IDDIIQDLLLLLLKLLLLLLKLLLLLLKLLLLLLLLLLLLLLKLL","n":["BuildHasher","BuildHasherDefault","FnvHasher","Hash","Hasher","Hasher","Murmur3Hasher","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","build_hasher","build_hasher","clone","default","default","default","eq","finish","finish","finish","fmt","from","from","from","hash","hash_slice","into","into","into","new","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","write","write","write"],"q":[[0,"hash32"]],"d":["See core::hash::BuildHasher for details","See core::hash::BuildHasherDefault for details","32-bit Fowler-Noll-Vo hasher","See core::hash::Hash for details","See core::hash::Hasher for details","See core::hash::BuildHasher::Hasher","32-bit MurmurHash3 hasher","","","","","","","See core::hash::BuildHasher.build_hasher","","","","","","","See core::hash::Hasher.finish","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Feeds this value into the given Hasher.","Feeds a slice of this type into the given Hasher.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","const constructor","","","","","","","","","","See core::hash::Hasher.write","",""],"i":[0,0,0,0,0,15,0,4,5,3,4,5,3,15,3,3,4,5,3,3,2,4,5,3,4,5,3,16,16,4,5,3,3,4,5,3,4,5,3,4,5,3,2,4,5],"f":[0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[3,[[0,[1,2]]]]]],[[[3,[[0,[1,2]]]]],[[3,[[0,[1,2]]]]]],[[],4],[[],5],[[],[[3,[[0,[1,2]]]]]],[[[3,[[0,[1,2]]]],[3,[[0,[1,2]]]]],6],[[],7],[4,7],[5,7],[[[3,[[0,[1,2]]]],8],9],[[]],[[]],[[]],[2],[[[11,[10]],2]],[[]],[[]],[[]],[[],3],[[],12],[[],12],[[],12],[[],12],[[],12],[[],12],[[],13],[[],13],[[],13],[[[11,[14]]]],[[4,[11,[14]]]],[[5,[11,[14]]]]],"c":[],"p":[[8,"Default"],[8,"Hasher"],[3,"BuildHasherDefault"],[3,"FnvHasher"],[3,"Murmur3Hasher"],[15,"bool"],[15,"u32"],[3,"Formatter"],[6,"Result"],[8,"Sized"],[15,"slice"],[4,"Result"],[3,"TypeId"],[15,"u8"],[8,"BuildHasher"],[8,"Hash"]]},\ +"heapless":{"doc":"static friendly data structures that don’t require …","t":"CCDEGGDDDDNDDCDNDDLLLLLLLLLLLLLLLLLLALLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLALLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLDIEEDLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLDDIDDDDDDDILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL","n":["BinaryHeap","Bucket","Deque","Entry","FnvIndexMap","FnvIndexSet","HistoryBuffer","IndexMap","IndexSet","LinearMap","Occupied","OccupiedEntry","OldestOrdered","Pos","String","Vacant","VacantEntry","Vec","as_mut","as_mut","as_mut_ptr","as_mut_slices","as_mut_str","as_mut_vec","as_ptr","as_ref","as_ref","as_ref","as_ref","as_ref","as_slice","as_slice","as_slices","as_str","back","back_mut","binary_heap","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","capacity","capacity","capacity","capacity","capacity","capacity","capacity","clear","clear","clear","clear","clear","clear","clear","clear_with","clone","clone","clone","clone","clone","clone","clone","cmp","cmp","contains","contains_key","contains_key","default","default","default","default","default","default","default","deref","deref","deref","deref_mut","deref_mut","difference","drop","drop","drop","drop","ends_with","entry","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","eq","extend","extend","extend","extend","extend","extend","extend","extend","extend","extend_from_slice","extend_from_slice","first","first","first_mut","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from","from_iter","from_iter","from_iter","from_iter","from_iter","from_iter","from_iter","from_slice","from_str","front","front_mut","get","get","get","get_mut","get_mut","get_mut","hash","hash","hash","hash","index","index","index_mut","index_mut","insert","insert","insert","insert","insert","insert","intersection","into","into","into","into","into","into","into","into","into","into","into","into_array","into_bytes","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_iter","into_key","into_mut","is_disjoint","is_empty","is_empty","is_empty","is_empty","is_empty","is_full","is_full","is_subset","is_superset","iter","iter","iter","iter","iter_mut","iter_mut","iter_mut","key","key","keys","keys","last","last","last_mut","len","len","len","len","len","ne","ne","ne","new","new","new","new","new","new","new","new_with","next","oldest_ordered","partial_cmp","partial_cmp","pop","pop","pop_back","pop_back_unchecked","pop_front","pop_front_unchecked","pop_unchecked","push","push","push_back","push_back_unchecked","push_front","push_front_unchecked","push_str","push_unchecked","recent","remove","remove","remove","remove","remove","remove_entry","resize","resize_default","retain","retain_mut","set_len","sorted_linked_list","starts_with","swap_remove","swap_remove","swap_remove_unchecked","symmetric_difference","truncate","truncate","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","union","values","values","values_mut","values_mut","write","write_char","write_str","write_str","BinaryHeap","Kind","Max","Min","PeekMut","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","capacity","clear","clone","default","deref","deref_mut","drop","fmt","from","from","from","from","into","into","into","into","into_iter","into_vec","is_empty","iter","iter_mut","len","new","peek","peek_mut","pop","pop","pop_unchecked","push","push_unchecked","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","FindMut","Iter","Kind","LinkedIndexU16","LinkedIndexU8","LinkedIndexUsize","Max","Min","Node","SortedLinkedList","SortedLinkedListIndex","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","cmp","cmp","cmp","deref","deref_mut","drop","drop","eq","eq","eq","find_mut","finish","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","into","into","into","into","into","into","into","into","into","into_iter","is_empty","is_full","iter","new_u16","new_u8","new_usize","next","partial_cmp","partial_cmp","partial_cmp","peek","pop","pop","pop_unchecked","push","push_unchecked","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id"],"q":[[0,"heapless"],[340,"heapless::binary_heap"],[395,"heapless::sorted_linked_list"]],"d":["","","A fixed capacity double-ended queue.","A view into an entry in the map","A heapless::IndexMap using the default FNV hasher","A heapless::IndexSet using the default FNV hasher. A list …","A “history buffer”, similar to a write-only ring …","Fixed capacity IndexMap","Fixed capacity IndexSet.","A fixed capacity map / dictionary that performs lookups …","The entry corresponding to the key K exists in the map","An occupied entry which can be manipulated","An iterator on the underlying buffer ordered from oldest …","","A fixed capacity String","The entry corresponding to the key K does not exist in the …","A view into an empty slot in the underlying map","A fixed capacity Vec","","","Returns a raw pointer to the vector’s buffer, which may …","Returns a pair of mutable slices which contain, in order, …","Converts a String into a mutable string slice.","Returns a mutable reference to the contents of this String.","Returns a raw pointer to the vector’s buffer.","","","","","","Returns the array slice backing the buffer, without …","Extracts a slice containing the entire vector.","Returns a pair of slices which contain, in order, the …","Extracts a string slice containing the entire string.","Provides a reference to the back element, or None if the …","Provides a mutable reference to the back element, or None …","A priority queue implemented with a binary heap.","","","","","","","","","","","","","","","","","","","","","","","Returns the maximum number of elements the deque can hold.","Returns the capacity of the buffer, which is the length of …","Returns the number of elements the map can hold","Returns the number of elements the set can hold","Returns the number of elements that the map can hold","Returns the maximum number of elements the String can hold","Returns the maximum number of elements the vector can hold.","Clears the deque, removing all values.","Clears the buffer, replacing every element with the …","Remove all key-value pairs in the map, while preserving …","Clears the set, removing all values.","Clears the map, removing all key-value pairs","Truncates this String, removing all contents.","Clears the vector, removing all values.","Clears the buffer, replacing every element with the given …","","","","","","","","","","Returns true if the set contains a value.","Returns true if the map contains a value for the specified …","Returns true if the map contains a value for the specified …","","","","","","","","","","","","","Visits the values representing the difference, i.e. the …","","","","","Returns true if needle is a suffix of the Vec.","Returns an entry for the corresponding key","","","","","","","","","","","","","","","","","","","","","Extends the vec from an iterator.","Clones and writes all elements in a slice to the buffer.","Clones and appends all elements in a slice to the Vec.","Get the first key-value pair","Get the first value","Get the first key-value pair, with mutable access to the …","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","","Returns the argument unchanged.","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","","","","","","Constructs a new vector with a fixed capacity of N and …","","Provides a reference to the front element, or None if the …","Provides a mutable reference to the front element, or None …","Gets a reference to the value associated with this entry","Returns a reference to the value corresponding to the key.","Returns a reference to the value corresponding to the key","Gets a mutable reference to the value associated with this …","Returns a mutable reference to the value corresponding to …","Returns a mutable reference to the value corresponding to …","","","","","","","","","Overwrites the underlying map’s value with this entry’…","Inserts this entry into to underlying map, yields a …","Inserts a key-value pair into the map.","Adds a value to the set.","Inserts a key-value pair into the map.","Inserts an element at position index within the vector, …","Visits the values representing the intersection, i.e. the …","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Returns the contents of the vector as an array of length M …","Converts a String into a byte vector.","","","","","","","","","","","","","Consumes this entry to yield to key associated with it","Consumes this entry and yields a reference to the …","Returns true if self has no elements in common with other. …","Returns whether the deque is empty.","Returns true if the map contains no elements.","Returns true if the set contains no elements.","Returns true if the map contains no elements","Returns true if the vec is empty","Returns whether the deque is full (i.e. if …","Returns true if the vec is full","Returns true if the set is a subset of another, i.e. other …","Examples","Returns an iterator over the deque.","Return an iterator over the key-value pairs of the map, in …","Return an iterator over the values of the set, in their …","An iterator visiting all key-value pairs in arbitrary …","Returns an iterator that allows modifying each value.","Return an iterator over the key-value pairs of the map, in …","An iterator visiting all key-value pairs in arbitrary …","Gets a reference to the key that this entity corresponds to","Get the key associated with this entry","Return an iterator over the keys of the map, in their order","An iterator visiting all keys in arbitrary order","Get the last key-value pair","Get the last value","Get the last key-value pair, with mutable access to the …","Returns the number of elements currently in the deque.","Returns the current fill level of the buffer.","Return the number of key-value pairs in the map.","Returns the number of elements in the set.","Returns the number of elements in this map","","","","Constructs a new, empty deque with a fixed capacity of N","Constructs a new history buffer.","Creates an empty IndexMap.","Creates an empty IndexSet","Creates an empty LinearMap","Constructs a new, empty String with a fixed capacity of N …","Constructs a new, empty vector with a fixed capacity of N","Constructs a new history buffer, where every element is …","","Returns an iterator for iterating over the buffer from …","","","Removes the last character from the string buffer and …","Removes the last element from a vector and returns it, or …","Removes the item from the back of the deque and returns …","Removes an item from the back of the deque and returns it, …","Removes the item from the front of the deque and returns …","Removes an item from the front of the deque and returns …","Removes the last element from a vector and returns it","Appends the given char to the end of this String.","Appends an item to the back of the collection","Appends an item to the back of the deque","Appends an item to the back of the deque","Appends an item to the front of the deque","Appends an item to the front of the deque","Appends a given string slice onto the end of this String.","Appends an item to the back of the collection","Returns a reference to the most recently written value.","Removes this entry from the map and yields its value","Same as swap_remove","Removes a value from the set. Returns true if the value …","Removes a key from the map, returning the value at the key …","Removes and returns the element at position index within …","Removes this entry from the map and yields its …","Resizes the Vec in-place so that len is equal to new_len.","Resizes the Vec in-place so that len is equal to new_len.","Retains only the elements specified by the predicate.","Retains only the elements specified by the predicate, …","Forces the length of the vector to new_len.","A fixed sorted priority linked list, similar to BinaryHeap …","Returns true if needle is a prefix of the Vec.","Remove the key-value pair equivalent to key and return its …","Removes an element from the vector and returns it.","Removes an element from the vector and returns it.","Visits the values representing the symmetric difference, …","Shortens this String to the specified length.","Shortens the vector, keeping the first len elements and …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Visits the values representing the union, i.e. all the …","Return an iterator over the values of the map, in their …","An iterator visiting all values in arbitrary order","Return an iterator over mutable references to the the …","An iterator visiting all values mutably in arbitrary order","Writes an element to the buffer, overwriting the oldest …","","","","A priority queue implemented with a binary heap.","The binary heap kind: min-heap or max-heap","Max-heap","Min-heap","Structure wrapping a mutable reference to the greatest …","","","","","","","","","Returns the capacity of the binary heap.","Drops all items from the binary heap.","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Returns the underlying Vec<T,N>. Order is arbitrary and …","Checks if the binary heap is empty.","Returns an iterator visiting all values in the underlying …","Returns a mutable iterator visiting all values in the …","Returns the length of the binary heap.","Creates an empty BinaryHeap as a $K-heap.","Returns the top (greatest if max-heap, smallest if …","Returns a mutable reference to the greatest item in the …","Removes the top (greatest if max-heap, smallest if …","Removes the peeked value from the heap and returns it.","Removes the top (greatest if max-heap, smallest if …","Pushes an item onto the binary heap.","Pushes an item onto the binary heap without first checking …","","","","","","","","","","","","","Comes from SortedLinkedList::find_mut.","Iterator for the linked list.","The linked list kind: min-list or max-list","Index for the SortedLinkedList with specific backing …","Index for the SortedLinkedList with specific backing …","Index for the SortedLinkedList with specific backing …","Marker for Max sorted SortedLinkedList.","Marker for Min sorted SortedLinkedList.","A node in the SortedLinkedList.","The linked list.","Trait for defining an index for the linked list, never …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Find an element in the list that can be changed and …","This will resort the element into the correct position in …","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Checks if the linked list is empty.","Checks if the linked list is full.","Get an iterator over the sorted list.","Create a new linked list.","Create a new linked list.","Create a new linked list.","","","","","Peek at the first element.","Pops the first element in the list.","This will pop the element from the list.","Pop an element from the list without checking so the list …","Pushes an element to the linked list and sorts it into …","Pushes a value onto the list without checking if the list …","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"i":[0,0,0,0,0,0,0,0,0,0,26,0,0,0,0,26,0,0,1,1,1,3,4,4,1,7,4,4,1,1,7,1,3,4,3,3,0,3,7,26,40,44,13,14,15,4,1,18,3,7,26,40,44,13,14,15,4,1,18,3,7,13,14,15,4,1,3,7,13,14,15,4,1,7,3,13,14,15,4,1,18,4,1,14,13,15,3,7,13,14,15,4,1,7,4,1,4,1,14,3,7,15,1,1,13,13,14,15,4,4,4,1,1,1,1,1,1,7,7,13,13,14,14,1,1,1,7,1,13,14,13,3,7,13,14,15,4,4,1,3,7,26,40,44,13,14,15,4,4,4,4,4,4,4,4,4,4,1,18,13,14,15,4,4,4,1,1,4,3,3,40,13,15,40,13,15,4,4,1,1,13,15,13,15,40,44,13,14,15,1,14,3,7,26,40,44,13,14,15,4,1,18,1,4,3,3,3,13,13,13,14,15,1,1,1,18,44,40,14,3,13,14,15,1,3,1,14,14,3,13,14,15,3,13,15,40,44,13,15,13,14,13,3,7,13,14,15,4,4,4,3,7,13,14,15,4,1,7,18,7,4,1,4,1,3,3,3,3,1,4,1,3,3,3,3,4,1,7,40,13,14,15,1,40,1,1,1,1,1,0,1,13,1,1,14,4,1,3,7,26,40,44,13,14,15,4,1,1,18,3,7,26,40,44,13,14,15,4,1,18,3,7,26,40,44,13,14,15,4,1,18,14,13,15,13,15,7,4,4,1,0,0,0,0,0,65,66,53,54,65,66,53,54,53,53,53,53,54,54,54,53,65,66,53,54,65,66,53,54,53,53,53,53,53,53,53,53,53,53,54,53,53,53,65,66,53,54,65,66,53,54,65,66,53,54,0,0,0,0,0,0,0,0,0,0,0,67,68,69,63,64,62,57,58,59,67,68,69,63,64,62,57,58,59,57,58,59,57,58,59,62,62,63,62,57,58,59,63,62,63,57,58,59,67,68,69,63,64,62,57,58,59,67,68,69,63,64,62,57,58,59,64,63,63,63,63,63,63,64,57,58,59,63,63,62,63,63,63,67,68,69,63,64,62,57,58,59,67,68,69,63,64,62,57,58,59,67,68,69,63,64,62,57,58,59],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1,1],[1,2],[1],[3],[4,5],[4,[[1,[6]]]],[1],[7,2],[4,[[2,[6]]]],[4,5],[1,1],[1,2],[7,2],[1,2],[3],[4,5],[3,8],[3,8],0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[3,9],[7,9],[[[13,[[0,[10,11]],12]]],9],[[[14,[[0,[10,11]],12]]],9],[[[15,[10]]],9],[4,9],[1,9],[3],[7],[[[13,[[0,[10,11]],12]]]],[[[14,[[0,[10,11]],12]]]],[[[15,[10]]]],[4],[1],[[[7,[[0,[16,17]]]],[0,[16,17]]]],[[[3,[17]]],[[3,[17]]]],[[[13,[[0,[10,11,17]],17,17]]],[[13,[[0,[10,11,17]],17,17]]]],[[[14,[[0,[10,11,17]],17]]],[[14,[[0,[10,11,17]],17]]]],[[[15,[[0,[10,17]],17]]],[[15,[[0,[10,17]],17]]]],[4,4],[[[1,[17]]],[[1,[17]]]],[[[18,[17]]],[[18,[17]]]],[[4,4],19],[[[1,[20]],[1,[20]]],19],[[[14,[[22,[[0,[21,10,11]]]],[0,[10,11]],12]],[0,[21,10,11]]],23],[[[13,[[22,[[0,[21,10,11]]]],[0,[10,11]],12]],[0,[21,10,11]]],23],[[[15,[10]],10],23],[[],3],[[],7],[[],[[13,[[0,[10,11]],[0,[12,24]]]]]],[[],[[14,[[0,[10,11]],[0,[12,24]]]]]],[[],[[15,[10]]]],[[],4],[[],1],[7,2],[4,5],[1,2],[4,5],[1,2],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],[[0,[[0,[10,11]],12]]]],[3],[7],[15],[1],[[[1,[25]],[2,[25]]],23],[[[13,[[0,[10,11]],12]],[0,[10,11]]],[[26,[[0,[10,11]]]]]],[[[13,[[0,[10,11]],10,12]],[13,[[0,[10,11]],10,12]]],23],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],23],[[[15,[10,25]],[15,[10,25]]],23],[[4,4],23],[[4,5],23],[[4,5],23],[[[1,[25]],1],23],[[[1,[25]],27],23],[[[1,[25]],2],23],[[[1,[25]],2],23],[[[1,[25]],2],23],[[[1,[25]],27],23],[[[7,[17]],28]],[[7,28]],[[[13,[[0,[10,11,16]],16,12]],28]],[[[13,[[0,[10,11]],12]],28]],[[[14,[[0,[10,11]],12]],28]],[[[14,[[0,[10,11,16]],12]],28]],[[1,28]],[[[1,[16]],28]],[[1,28]],[[[7,[17]],[2,[17]]]],[[[1,[17]],[2,[17]]],29],[[[13,[[0,[10,11]],12]]],8],[[[14,[[0,[10,11]],12]]],[[8,[[0,[10,11]]]]]],[[[13,[[0,[10,11]],12]]],8],[[[3,[30]],31],32],[[[7,[30]],31],32],[[[13,[[0,[10,11,30]],30,12]],31],32],[[[14,[[0,[10,11,30]],12]],31],32],[[[15,[[0,[10,30]],30]],31],32],[[4,31],32],[[4,31],32],[[[1,[30]],31],32],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[33,4],[34,4],[5,4],[6,4],[[]],[35,4],[36,4],[37,4],[38,4],[39,4],[[]],[[]],[28,[[13,[[0,[10,11]],[0,[12,24]]]]]],[28,[[14,[[0,[10,11]],[0,[12,24]]]]]],[28,[[15,[10]]]],[28,4],[28,4],[28,4],[28,1],[[[2,[17]]],[[29,[[1,[17]]]]]],[5,[[29,[4]]]],[3,8],[3,8],[[[40,[[0,[10,11]]]]]],[[[13,[[22,[[0,[21,11,10]]]],[0,[10,11]],12]],[0,[21,11,10]]],8],[[[15,[[22,[[0,[10,21]]]],10]],[0,[10,21]]],8],[[[40,[[0,[10,11]]]]]],[[[13,[[22,[[0,[21,11,10]]]],[0,[10,11]],12]],[0,[21,11,10]]],8],[[[15,[[22,[[0,[10,21]]]],10]],[0,[10,21]]],8],[[4,41]],[[4,42]],[[[1,[43]],41]],[[[1,[11]],42]],[[[13,[[0,[10,11,[22,[[0,[21,10,11]]]]]],12]],[0,[21,10,11]]]],[[[15,[[0,[[22,[[0,[10,21]]]],10]]]],[0,[10,21]]]],[[[13,[[0,[10,11,[22,[[0,[21,10,11]]]]]],12]],[0,[21,10,11]]]],[[[15,[[0,[[22,[[0,[10,21]]]],10]]]],[0,[10,21]]]],[[[40,[[0,[10,11]]]]]],[[[44,[[0,[10,11]]]]],29],[[[13,[[0,[10,11]],12]],[0,[10,11]]],[[29,[8]]]],[[[14,[[0,[10,11]],12]],[0,[10,11]]],[[29,[23,[0,[10,11]]]]]],[[[15,[10]],10],[[29,[8]]]],[[1,9],29],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],[[0,[[0,[10,11]],12]]]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[1,[[29,[27,1]]]],[4,[[1,[6]]]],[3],[3],[3],[[[13,[[0,[10,11]],12]]]],[[[13,[[0,[10,11]],12]]]],[[[13,[[0,[10,11]],12]]]],[[[14,[[0,[10,11]],12]]]],[[[15,[10]]]],[1],[1],[1],[[]],[[[44,[[0,[10,11]]]]],[[0,[10,11]]]],[[[40,[[0,[10,11]]]]]],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],23],[3,23],[[[13,[[0,[10,11]],12]]],23],[[[14,[[0,[10,11]],12]]],23],[[[15,[10]]],23],[1,23],[3,23],[1,23],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],23],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],23],0,[[[13,[[0,[10,11]],12]]],[[0,[[0,[10,11]]]]]],[[[14,[[0,[10,11]],12]]],[[0,[[0,[10,11]]]]]],[[[15,[10]]],[[0,[10]]]],0,[[[13,[[0,[10,11]],12]]],[[0,[[0,[10,11]]]]]],[[[15,[10]]],[[0,[10]]]],[[[40,[[0,[10,11]]]]],[[0,[10,11]]]],[[[44,[[0,[10,11]]]]],[[0,[10,11]]]],[[[13,[[0,[10,11]],12]]],45],[[[15,[10]]],45],[[[13,[[0,[10,11]],12]]],8],[[[14,[[0,[10,11]],12]]],[[8,[[0,[10,11]]]]]],[[[13,[[0,[10,11]],12]]],8],[3,9],[7,9],[[[13,[[0,[10,11]],12]]],9],[[[14,[[0,[10,11]],12]]],9],[[[15,[10]]],9],[[4,4],23],[[4,5],23],[[4,5],23],[[],3],[[],7],[[],[[13,[46]]]],[[],[[14,[46]]]],[[],15],[[],4],[[],1],[[[0,[16,17]]],[[7,[[0,[16,17]]]]]],[18,8],[7,18],[[4,4],[[8,[19]]]],[[[1,[47]],[1,[47]]],[[8,[19]]]],[4,[[8,[48]]]],[1,8],[3,8],[3],[3,8],[3],[1],[[4,48],29],[1,29],[3,29],[3],[3,29],[3],[[4,5],29],[1],[7,8],[[[40,[[0,[10,11]]]]]],[[[13,[[22,[[0,[21,11,10]]]],[0,[10,11]],12]],[0,[21,11,10]]],8],[[[14,[[22,[[0,[21,10,11]]]],[0,[10,11]],12]],[0,[21,10,11]]],23],[[[15,[[22,[[0,[10,21]]]],10]],[0,[10,21]]],8],[[1,9]],[[[40,[[0,[10,11]]]]]],[[[1,[17]],9,17],29],[[[1,[[0,[17,24]]]],9],29],[[1,49]],[[1,49]],[[1,9]],0,[[[1,[25]],[2,[25]]],23],[[[13,[[22,[[0,[21,11,10]]]],[0,[10,11]],12]],[0,[21,11,10]]],8],[[1,9]],[[1,9]],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],45],[[4,9]],[[1,9]],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[[2,[17]]],[[29,[[1,[17]]]]]],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[[14,[[0,[10,11]],12]],[14,[[0,[10,11]],12]]],45],[[[13,[[0,[10,11]],12]]],45],[[[15,[10]]],45],[[[13,[[0,[10,11]],12]]],45],[[[15,[10]]],45],[7],[[4,48],[[29,[51]]]],[[4,5],[[29,[51]]]],[[[1,[6]],5],32],0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[53,[20,52]]],9],[[[53,[20,52]]]],[[[53,[[0,[20,17]],52]]],[[53,[[0,[20,17]],52]]]],[[],[[53,[20,52]]]],[[[54,[20,52]]],20],[[[54,[20,52]]],20],[[[54,[20,52]]]],[[[53,[[0,[20,30]],52]],31],32],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[53,[20,52]]]],[[[53,[20,52]]],[[1,[20]]]],[[[53,[20,52]]],23],[[[53,[20,52]]],[[55,[20]]]],[[[53,[20,52]]],[[56,[20]]]],[[[53,[20,52]]],9],[[],53],[[[53,[20,52]]],[[8,[20]]]],[[[53,[20,52]]],[[8,[[54,[20,52]]]]]],[[[53,[20,52]]],[[8,[20]]]],[[[54,[20,52]]],20],[[[53,[20,52]]],20],[[[53,[20,52]],20],[[29,[20]]]],[[[53,[20,52]],20]],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],50],[[],50],[[],50],[[],50],0,0,0,0,0,0,0,0,0,0,0,[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[57,57],[58,58],[59,59],[[57,57],19],[[58,58],19],[[59,59],19],[[[62,[20,60,61]]]],[[[62,[20,60,61]]]],[[[63,[60]]]],[[[62,[20,60,61]]]],[[57,57],23],[[58,58],23],[[59,59],23],[[[63,[20,60,61]],49],[[8,[[62,[20,60,61]]]]]],[[[62,[20,60,61]]]],[[[63,[[0,[20,30]],60,61]],31],32],[[57,31],32],[[58,31],32],[[59,31],32],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[[63,[20,60,61]]],23],[[[63,[20,60,61]]],23],[[[63,[20,60,61]]],[[64,[20,60,61]]]],[[],[[63,[58]]]],[[],[[63,[57]]]],[[],[[63,[59]]]],[[[64,[20,60,61]]],8],[[57,57],[[8,[19]]]],[[58,58],[[8,[19]]]],[[59,59],[[8,[19]]]],[[[63,[20,60,61]]],[[8,[20]]]],[[[63,[20,60,61]]],[[29,[20]]]],[[[62,[20,60,61]]],20],[[[63,[20,60,61]]],20],[[[63,[20,60,61]],20],[[29,[20]]]],[[[63,[20,60,61]],20]],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],29],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50],[[],50]],"c":[],"p":[[3,"Vec"],[15,"slice"],[3,"Deque"],[3,"String"],[15,"str"],[15,"u8"],[3,"HistoryBuffer"],[4,"Option"],[15,"usize"],[8,"Eq"],[8,"Hash"],[8,"BuildHasher"],[3,"IndexMap"],[3,"IndexSet"],[3,"LinearMap"],[8,"Copy"],[8,"Clone"],[3,"OldestOrdered"],[4,"Ordering"],[8,"Ord"],[8,"Sized"],[8,"Borrow"],[15,"bool"],[8,"Default"],[8,"PartialEq"],[4,"Entry"],[15,"array"],[8,"IntoIterator"],[4,"Result"],[8,"Debug"],[3,"Formatter"],[6,"Result"],[15,"u32"],[15,"u64"],[15,"i16"],[15,"u16"],[15,"i32"],[15,"i8"],[15,"i64"],[3,"OccupiedEntry"],[8,"Hasher"],[8,"Hasher"],[8,"Hash"],[3,"VacantEntry"],[8,"Iterator"],[3,"BuildHasherDefault"],[8,"PartialOrd"],[15,"char"],[8,"FnMut"],[3,"TypeId"],[3,"Error"],[8,"Kind"],[3,"BinaryHeap"],[3,"PeekMut"],[3,"Iter"],[3,"IterMut"],[3,"LinkedIndexU8"],[3,"LinkedIndexU16"],[3,"LinkedIndexUsize"],[8,"SortedLinkedListIndex"],[8,"Kind"],[3,"FindMut"],[3,"SortedLinkedList"],[3,"Iter"],[4,"Min"],[4,"Max"],[3,"Min"],[3,"Max"],[3,"Node"]]},\ +"panic_halt":{"doc":"Set the panicking behavior to halt","t":"","n":[],"q":[],"d":[],"i":[],"f":[],"c":[],"p":[]},\ +"stable_deref_trait":{"doc":"This module defines an unsafe marker trait, StableDeref, …","t":"II","n":["CloneStableDeref","StableDeref"],"q":[[0,"stable_deref_trait"]],"d":["An unsafe marker trait for types where clones deref to the …","An unsafe marker trait for types that deref to a stable …"],"i":[0,0],"f":[0,0],"c":[],"p":[]}\ }'); if (typeof window !== 'undefined' && window.initSearch) {window.initSearch(searchIndex)}; if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; diff --git a/docs/doc/src-files.js b/docs/doc/src-files.js index 9f340fc..3334584 100644 --- a/docs/doc/src-files.js +++ b/docs/doc/src-files.js @@ -1,5 +1,11 @@ var srcIndex = JSON.parse('{\ "arduboy_rust":["",[["hardware",[],["buttons.rs","led.rs","mod.rs"]],["library",[],["arduboy2.rs","arduboy_tone.rs","arduboy_tone_pitch.rs","arduino.rs","c.rs","eeprom.rs","mod.rs","progmem.rs","sprites.rs"]]],["lib.rs","prelude.rs","print.rs"]],\ -"panic_halt":["",[],["lib.rs"]]\ +"atomic_polyfill":["",[],["lib.rs"]],\ +"byteorder":["",[],["lib.rs"]],\ +"critical_section":["",[],["lib.rs","mutex.rs"]],\ +"hash32":["",[],["fnv.rs","lib.rs","murmur3.rs"]],\ +"heapless":["",[],["binary_heap.rs","deque.rs","histbuf.rs","indexmap.rs","indexset.rs","lib.rs","linear_map.rs","sealed.rs","sorted_linked_list.rs","string.rs","vec.rs"]],\ +"panic_halt":["",[],["lib.rs"]],\ +"stable_deref_trait":["",[],["lib.rs"]]\ }'); createSrcSidebar(); diff --git a/docs/doc/src/arduboy_rust/lib.rs.html b/docs/doc/src/arduboy_rust/lib.rs.html index dc742d4..fd53806 100644 --- a/docs/doc/src/arduboy_rust/lib.rs.html +++ b/docs/doc/src/arduboy_rust/lib.rs.html @@ -34,6 +34,8 @@ 34 35 36 +37 +38
#![cfg(target_arch = "avr")]
 #![no_std]
 #![feature(c_size_t)]
@@ -66,6 +68,8 @@
 mod library;
 pub mod prelude;
 mod print;
+#[doc(inline)]
+pub extern crate heapless;
 pub use crate::library::arduboy2::{self, Arduboy2, Color, FONT_SIZE, HEIGHT, WIDTH};
 pub use crate::library::arduboy_tone::{self, ArduboyTones};
 pub use crate::library::eeprom::{EEPROM, EEPROMBYTE};
diff --git a/docs/doc/src/arduboy_rust/library/progmem.rs.html b/docs/doc/src/arduboy_rust/library/progmem.rs.html
index cfe8278..0b31665 100644
--- a/docs/doc/src/arduboy_rust/library/progmem.rs.html
+++ b/docs/doc/src/arduboy_rust/library/progmem.rs.html
@@ -91,6 +91,47 @@
 91
 92
 93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
 
#![allow(unused_imports)]
 /// Create a space for Progmem variable
 /// ## Example
@@ -109,6 +150,11 @@
 /// progmem!(
 ///     static image: [u8; _] = [8, 8, 0x81, 0x00, 0x12, 0x40, 0x04, 0x11, 0x00, 0x04];
 /// );
+///
+/// // for a Vector
+/// progmem!(
+///     static mut walls: Vec<Player, 100> = Vec::new();
+/// );
 /// ```
 #[macro_export]
 macro_rules! progmem {
@@ -124,6 +170,42 @@
 			$($rest)*
 		}
     };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident mut $name:ident: [$ty:ty; _] = $value:expr;
+        $($rest:tt)*
+    ) => {
+        $( #[$attr] )*
+        #[link_section = ".progmem.data"]
+        $v $id mut $name: [$ty; $value.len()] = $value;
+        $crate::progmem!{
+			$($rest)*
+		}
+    };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident $name:ident: $ty:ty = $value:expr;
+        $($rest:tt)*
+    ) => {
+        $( #[$attr] )*
+        #[link_section = ".progmem.data"]
+        $v $id $name: $ty = $value;
+        $crate::progmem!{
+			$($rest)*
+		}
+    };
+    (
+        $( #[$attr:meta] )*
+        $v:vis $id:ident mut $name:ident: $ty:ty = $value:expr;
+        $($rest:tt)*
+    ) => {
+        $( #[$attr] )*
+        #[link_section = ".progmem.data"]
+        $v $id mut $name: $ty = $value;
+        $crate::progmem!{
+			$($rest)*
+		}
+    };
     () => ()
 }
 
diff --git a/docs/doc/src/arduboy_rust/prelude.rs.html b/docs/doc/src/arduboy_rust/prelude.rs.html
index b2c6887..39d3fcc 100644
--- a/docs/doc/src/arduboy_rust/prelude.rs.html
+++ b/docs/doc/src/arduboy_rust/prelude.rs.html
@@ -29,6 +29,7 @@
 29
 30
 31
+32
 
//! This is the important one to use this library effective in your project
 //!
 //! Import the module:
@@ -39,6 +40,7 @@
 pub use crate::hardware::buttons::{self, *};
 #[doc(inline)]
 pub use crate::hardware::led::{self, *};
+pub use crate::heapless::{LinearMap, String, Vec};
 pub use crate::library::arduboy2::{self, *};
 pub use crate::library::arduboy_tone::{self, ArduboyTones};
 pub use crate::library::arduino::*;
diff --git a/docs/doc/src/atomic_polyfill/lib.rs.html b/docs/doc/src/atomic_polyfill/lib.rs.html
new file mode 100644
index 0000000..d691d1c
--- /dev/null
+++ b/docs/doc/src/atomic_polyfill/lib.rs.html
@@ -0,0 +1,19 @@
+lib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+
#![no_std]
+
+#[cfg(reexport_core)]
+pub use core::sync::atomic::*;
+
+#[cfg(not(reexport_core))]
+mod polyfill;
+#[cfg(not(reexport_core))]
+pub use polyfill::*;
+
\ No newline at end of file diff --git a/docs/doc/src/byteorder/lib.rs.html b/docs/doc/src/byteorder/lib.rs.html new file mode 100644 index 0000000..e6f7d57 --- /dev/null +++ b/docs/doc/src/byteorder/lib.rs.html @@ -0,0 +1,8105 @@ +lib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+742
+743
+744
+745
+746
+747
+748
+749
+750
+751
+752
+753
+754
+755
+756
+757
+758
+759
+760
+761
+762
+763
+764
+765
+766
+767
+768
+769
+770
+771
+772
+773
+774
+775
+776
+777
+778
+779
+780
+781
+782
+783
+784
+785
+786
+787
+788
+789
+790
+791
+792
+793
+794
+795
+796
+797
+798
+799
+800
+801
+802
+803
+804
+805
+806
+807
+808
+809
+810
+811
+812
+813
+814
+815
+816
+817
+818
+819
+820
+821
+822
+823
+824
+825
+826
+827
+828
+829
+830
+831
+832
+833
+834
+835
+836
+837
+838
+839
+840
+841
+842
+843
+844
+845
+846
+847
+848
+849
+850
+851
+852
+853
+854
+855
+856
+857
+858
+859
+860
+861
+862
+863
+864
+865
+866
+867
+868
+869
+870
+871
+872
+873
+874
+875
+876
+877
+878
+879
+880
+881
+882
+883
+884
+885
+886
+887
+888
+889
+890
+891
+892
+893
+894
+895
+896
+897
+898
+899
+900
+901
+902
+903
+904
+905
+906
+907
+908
+909
+910
+911
+912
+913
+914
+915
+916
+917
+918
+919
+920
+921
+922
+923
+924
+925
+926
+927
+928
+929
+930
+931
+932
+933
+934
+935
+936
+937
+938
+939
+940
+941
+942
+943
+944
+945
+946
+947
+948
+949
+950
+951
+952
+953
+954
+955
+956
+957
+958
+959
+960
+961
+962
+963
+964
+965
+966
+967
+968
+969
+970
+971
+972
+973
+974
+975
+976
+977
+978
+979
+980
+981
+982
+983
+984
+985
+986
+987
+988
+989
+990
+991
+992
+993
+994
+995
+996
+997
+998
+999
+1000
+1001
+1002
+1003
+1004
+1005
+1006
+1007
+1008
+1009
+1010
+1011
+1012
+1013
+1014
+1015
+1016
+1017
+1018
+1019
+1020
+1021
+1022
+1023
+1024
+1025
+1026
+1027
+1028
+1029
+1030
+1031
+1032
+1033
+1034
+1035
+1036
+1037
+1038
+1039
+1040
+1041
+1042
+1043
+1044
+1045
+1046
+1047
+1048
+1049
+1050
+1051
+1052
+1053
+1054
+1055
+1056
+1057
+1058
+1059
+1060
+1061
+1062
+1063
+1064
+1065
+1066
+1067
+1068
+1069
+1070
+1071
+1072
+1073
+1074
+1075
+1076
+1077
+1078
+1079
+1080
+1081
+1082
+1083
+1084
+1085
+1086
+1087
+1088
+1089
+1090
+1091
+1092
+1093
+1094
+1095
+1096
+1097
+1098
+1099
+1100
+1101
+1102
+1103
+1104
+1105
+1106
+1107
+1108
+1109
+1110
+1111
+1112
+1113
+1114
+1115
+1116
+1117
+1118
+1119
+1120
+1121
+1122
+1123
+1124
+1125
+1126
+1127
+1128
+1129
+1130
+1131
+1132
+1133
+1134
+1135
+1136
+1137
+1138
+1139
+1140
+1141
+1142
+1143
+1144
+1145
+1146
+1147
+1148
+1149
+1150
+1151
+1152
+1153
+1154
+1155
+1156
+1157
+1158
+1159
+1160
+1161
+1162
+1163
+1164
+1165
+1166
+1167
+1168
+1169
+1170
+1171
+1172
+1173
+1174
+1175
+1176
+1177
+1178
+1179
+1180
+1181
+1182
+1183
+1184
+1185
+1186
+1187
+1188
+1189
+1190
+1191
+1192
+1193
+1194
+1195
+1196
+1197
+1198
+1199
+1200
+1201
+1202
+1203
+1204
+1205
+1206
+1207
+1208
+1209
+1210
+1211
+1212
+1213
+1214
+1215
+1216
+1217
+1218
+1219
+1220
+1221
+1222
+1223
+1224
+1225
+1226
+1227
+1228
+1229
+1230
+1231
+1232
+1233
+1234
+1235
+1236
+1237
+1238
+1239
+1240
+1241
+1242
+1243
+1244
+1245
+1246
+1247
+1248
+1249
+1250
+1251
+1252
+1253
+1254
+1255
+1256
+1257
+1258
+1259
+1260
+1261
+1262
+1263
+1264
+1265
+1266
+1267
+1268
+1269
+1270
+1271
+1272
+1273
+1274
+1275
+1276
+1277
+1278
+1279
+1280
+1281
+1282
+1283
+1284
+1285
+1286
+1287
+1288
+1289
+1290
+1291
+1292
+1293
+1294
+1295
+1296
+1297
+1298
+1299
+1300
+1301
+1302
+1303
+1304
+1305
+1306
+1307
+1308
+1309
+1310
+1311
+1312
+1313
+1314
+1315
+1316
+1317
+1318
+1319
+1320
+1321
+1322
+1323
+1324
+1325
+1326
+1327
+1328
+1329
+1330
+1331
+1332
+1333
+1334
+1335
+1336
+1337
+1338
+1339
+1340
+1341
+1342
+1343
+1344
+1345
+1346
+1347
+1348
+1349
+1350
+1351
+1352
+1353
+1354
+1355
+1356
+1357
+1358
+1359
+1360
+1361
+1362
+1363
+1364
+1365
+1366
+1367
+1368
+1369
+1370
+1371
+1372
+1373
+1374
+1375
+1376
+1377
+1378
+1379
+1380
+1381
+1382
+1383
+1384
+1385
+1386
+1387
+1388
+1389
+1390
+1391
+1392
+1393
+1394
+1395
+1396
+1397
+1398
+1399
+1400
+1401
+1402
+1403
+1404
+1405
+1406
+1407
+1408
+1409
+1410
+1411
+1412
+1413
+1414
+1415
+1416
+1417
+1418
+1419
+1420
+1421
+1422
+1423
+1424
+1425
+1426
+1427
+1428
+1429
+1430
+1431
+1432
+1433
+1434
+1435
+1436
+1437
+1438
+1439
+1440
+1441
+1442
+1443
+1444
+1445
+1446
+1447
+1448
+1449
+1450
+1451
+1452
+1453
+1454
+1455
+1456
+1457
+1458
+1459
+1460
+1461
+1462
+1463
+1464
+1465
+1466
+1467
+1468
+1469
+1470
+1471
+1472
+1473
+1474
+1475
+1476
+1477
+1478
+1479
+1480
+1481
+1482
+1483
+1484
+1485
+1486
+1487
+1488
+1489
+1490
+1491
+1492
+1493
+1494
+1495
+1496
+1497
+1498
+1499
+1500
+1501
+1502
+1503
+1504
+1505
+1506
+1507
+1508
+1509
+1510
+1511
+1512
+1513
+1514
+1515
+1516
+1517
+1518
+1519
+1520
+1521
+1522
+1523
+1524
+1525
+1526
+1527
+1528
+1529
+1530
+1531
+1532
+1533
+1534
+1535
+1536
+1537
+1538
+1539
+1540
+1541
+1542
+1543
+1544
+1545
+1546
+1547
+1548
+1549
+1550
+1551
+1552
+1553
+1554
+1555
+1556
+1557
+1558
+1559
+1560
+1561
+1562
+1563
+1564
+1565
+1566
+1567
+1568
+1569
+1570
+1571
+1572
+1573
+1574
+1575
+1576
+1577
+1578
+1579
+1580
+1581
+1582
+1583
+1584
+1585
+1586
+1587
+1588
+1589
+1590
+1591
+1592
+1593
+1594
+1595
+1596
+1597
+1598
+1599
+1600
+1601
+1602
+1603
+1604
+1605
+1606
+1607
+1608
+1609
+1610
+1611
+1612
+1613
+1614
+1615
+1616
+1617
+1618
+1619
+1620
+1621
+1622
+1623
+1624
+1625
+1626
+1627
+1628
+1629
+1630
+1631
+1632
+1633
+1634
+1635
+1636
+1637
+1638
+1639
+1640
+1641
+1642
+1643
+1644
+1645
+1646
+1647
+1648
+1649
+1650
+1651
+1652
+1653
+1654
+1655
+1656
+1657
+1658
+1659
+1660
+1661
+1662
+1663
+1664
+1665
+1666
+1667
+1668
+1669
+1670
+1671
+1672
+1673
+1674
+1675
+1676
+1677
+1678
+1679
+1680
+1681
+1682
+1683
+1684
+1685
+1686
+1687
+1688
+1689
+1690
+1691
+1692
+1693
+1694
+1695
+1696
+1697
+1698
+1699
+1700
+1701
+1702
+1703
+1704
+1705
+1706
+1707
+1708
+1709
+1710
+1711
+1712
+1713
+1714
+1715
+1716
+1717
+1718
+1719
+1720
+1721
+1722
+1723
+1724
+1725
+1726
+1727
+1728
+1729
+1730
+1731
+1732
+1733
+1734
+1735
+1736
+1737
+1738
+1739
+1740
+1741
+1742
+1743
+1744
+1745
+1746
+1747
+1748
+1749
+1750
+1751
+1752
+1753
+1754
+1755
+1756
+1757
+1758
+1759
+1760
+1761
+1762
+1763
+1764
+1765
+1766
+1767
+1768
+1769
+1770
+1771
+1772
+1773
+1774
+1775
+1776
+1777
+1778
+1779
+1780
+1781
+1782
+1783
+1784
+1785
+1786
+1787
+1788
+1789
+1790
+1791
+1792
+1793
+1794
+1795
+1796
+1797
+1798
+1799
+1800
+1801
+1802
+1803
+1804
+1805
+1806
+1807
+1808
+1809
+1810
+1811
+1812
+1813
+1814
+1815
+1816
+1817
+1818
+1819
+1820
+1821
+1822
+1823
+1824
+1825
+1826
+1827
+1828
+1829
+1830
+1831
+1832
+1833
+1834
+1835
+1836
+1837
+1838
+1839
+1840
+1841
+1842
+1843
+1844
+1845
+1846
+1847
+1848
+1849
+1850
+1851
+1852
+1853
+1854
+1855
+1856
+1857
+1858
+1859
+1860
+1861
+1862
+1863
+1864
+1865
+1866
+1867
+1868
+1869
+1870
+1871
+1872
+1873
+1874
+1875
+1876
+1877
+1878
+1879
+1880
+1881
+1882
+1883
+1884
+1885
+1886
+1887
+1888
+1889
+1890
+1891
+1892
+1893
+1894
+1895
+1896
+1897
+1898
+1899
+1900
+1901
+1902
+1903
+1904
+1905
+1906
+1907
+1908
+1909
+1910
+1911
+1912
+1913
+1914
+1915
+1916
+1917
+1918
+1919
+1920
+1921
+1922
+1923
+1924
+1925
+1926
+1927
+1928
+1929
+1930
+1931
+1932
+1933
+1934
+1935
+1936
+1937
+1938
+1939
+1940
+1941
+1942
+1943
+1944
+1945
+1946
+1947
+1948
+1949
+1950
+1951
+1952
+1953
+1954
+1955
+1956
+1957
+1958
+1959
+1960
+1961
+1962
+1963
+1964
+1965
+1966
+1967
+1968
+1969
+1970
+1971
+1972
+1973
+1974
+1975
+1976
+1977
+1978
+1979
+1980
+1981
+1982
+1983
+1984
+1985
+1986
+1987
+1988
+1989
+1990
+1991
+1992
+1993
+1994
+1995
+1996
+1997
+1998
+1999
+2000
+2001
+2002
+2003
+2004
+2005
+2006
+2007
+2008
+2009
+2010
+2011
+2012
+2013
+2014
+2015
+2016
+2017
+2018
+2019
+2020
+2021
+2022
+2023
+2024
+2025
+2026
+2027
+2028
+2029
+2030
+2031
+2032
+2033
+2034
+2035
+2036
+2037
+2038
+2039
+2040
+2041
+2042
+2043
+2044
+2045
+2046
+2047
+2048
+2049
+2050
+2051
+2052
+2053
+2054
+2055
+2056
+2057
+2058
+2059
+2060
+2061
+2062
+2063
+2064
+2065
+2066
+2067
+2068
+2069
+2070
+2071
+2072
+2073
+2074
+2075
+2076
+2077
+2078
+2079
+2080
+2081
+2082
+2083
+2084
+2085
+2086
+2087
+2088
+2089
+2090
+2091
+2092
+2093
+2094
+2095
+2096
+2097
+2098
+2099
+2100
+2101
+2102
+2103
+2104
+2105
+2106
+2107
+2108
+2109
+2110
+2111
+2112
+2113
+2114
+2115
+2116
+2117
+2118
+2119
+2120
+2121
+2122
+2123
+2124
+2125
+2126
+2127
+2128
+2129
+2130
+2131
+2132
+2133
+2134
+2135
+2136
+2137
+2138
+2139
+2140
+2141
+2142
+2143
+2144
+2145
+2146
+2147
+2148
+2149
+2150
+2151
+2152
+2153
+2154
+2155
+2156
+2157
+2158
+2159
+2160
+2161
+2162
+2163
+2164
+2165
+2166
+2167
+2168
+2169
+2170
+2171
+2172
+2173
+2174
+2175
+2176
+2177
+2178
+2179
+2180
+2181
+2182
+2183
+2184
+2185
+2186
+2187
+2188
+2189
+2190
+2191
+2192
+2193
+2194
+2195
+2196
+2197
+2198
+2199
+2200
+2201
+2202
+2203
+2204
+2205
+2206
+2207
+2208
+2209
+2210
+2211
+2212
+2213
+2214
+2215
+2216
+2217
+2218
+2219
+2220
+2221
+2222
+2223
+2224
+2225
+2226
+2227
+2228
+2229
+2230
+2231
+2232
+2233
+2234
+2235
+2236
+2237
+2238
+2239
+2240
+2241
+2242
+2243
+2244
+2245
+2246
+2247
+2248
+2249
+2250
+2251
+2252
+2253
+2254
+2255
+2256
+2257
+2258
+2259
+2260
+2261
+2262
+2263
+2264
+2265
+2266
+2267
+2268
+2269
+2270
+2271
+2272
+2273
+2274
+2275
+2276
+2277
+2278
+2279
+2280
+2281
+2282
+2283
+2284
+2285
+2286
+2287
+2288
+2289
+2290
+2291
+2292
+2293
+2294
+2295
+2296
+2297
+2298
+2299
+2300
+2301
+2302
+2303
+2304
+2305
+2306
+2307
+2308
+2309
+2310
+2311
+2312
+2313
+2314
+2315
+2316
+2317
+2318
+2319
+2320
+2321
+2322
+2323
+2324
+2325
+2326
+2327
+2328
+2329
+2330
+2331
+2332
+2333
+2334
+2335
+2336
+2337
+2338
+2339
+2340
+2341
+2342
+2343
+2344
+2345
+2346
+2347
+2348
+2349
+2350
+2351
+2352
+2353
+2354
+2355
+2356
+2357
+2358
+2359
+2360
+2361
+2362
+2363
+2364
+2365
+2366
+2367
+2368
+2369
+2370
+2371
+2372
+2373
+2374
+2375
+2376
+2377
+2378
+2379
+2380
+2381
+2382
+2383
+2384
+2385
+2386
+2387
+2388
+2389
+2390
+2391
+2392
+2393
+2394
+2395
+2396
+2397
+2398
+2399
+2400
+2401
+2402
+2403
+2404
+2405
+2406
+2407
+2408
+2409
+2410
+2411
+2412
+2413
+2414
+2415
+2416
+2417
+2418
+2419
+2420
+2421
+2422
+2423
+2424
+2425
+2426
+2427
+2428
+2429
+2430
+2431
+2432
+2433
+2434
+2435
+2436
+2437
+2438
+2439
+2440
+2441
+2442
+2443
+2444
+2445
+2446
+2447
+2448
+2449
+2450
+2451
+2452
+2453
+2454
+2455
+2456
+2457
+2458
+2459
+2460
+2461
+2462
+2463
+2464
+2465
+2466
+2467
+2468
+2469
+2470
+2471
+2472
+2473
+2474
+2475
+2476
+2477
+2478
+2479
+2480
+2481
+2482
+2483
+2484
+2485
+2486
+2487
+2488
+2489
+2490
+2491
+2492
+2493
+2494
+2495
+2496
+2497
+2498
+2499
+2500
+2501
+2502
+2503
+2504
+2505
+2506
+2507
+2508
+2509
+2510
+2511
+2512
+2513
+2514
+2515
+2516
+2517
+2518
+2519
+2520
+2521
+2522
+2523
+2524
+2525
+2526
+2527
+2528
+2529
+2530
+2531
+2532
+2533
+2534
+2535
+2536
+2537
+2538
+2539
+2540
+2541
+2542
+2543
+2544
+2545
+2546
+2547
+2548
+2549
+2550
+2551
+2552
+2553
+2554
+2555
+2556
+2557
+2558
+2559
+2560
+2561
+2562
+2563
+2564
+2565
+2566
+2567
+2568
+2569
+2570
+2571
+2572
+2573
+2574
+2575
+2576
+2577
+2578
+2579
+2580
+2581
+2582
+2583
+2584
+2585
+2586
+2587
+2588
+2589
+2590
+2591
+2592
+2593
+2594
+2595
+2596
+2597
+2598
+2599
+2600
+2601
+2602
+2603
+2604
+2605
+2606
+2607
+2608
+2609
+2610
+2611
+2612
+2613
+2614
+2615
+2616
+2617
+2618
+2619
+2620
+2621
+2622
+2623
+2624
+2625
+2626
+2627
+2628
+2629
+2630
+2631
+2632
+2633
+2634
+2635
+2636
+2637
+2638
+2639
+2640
+2641
+2642
+2643
+2644
+2645
+2646
+2647
+2648
+2649
+2650
+2651
+2652
+2653
+2654
+2655
+2656
+2657
+2658
+2659
+2660
+2661
+2662
+2663
+2664
+2665
+2666
+2667
+2668
+2669
+2670
+2671
+2672
+2673
+2674
+2675
+2676
+2677
+2678
+2679
+2680
+2681
+2682
+2683
+2684
+2685
+2686
+2687
+2688
+2689
+2690
+2691
+2692
+2693
+2694
+2695
+2696
+2697
+2698
+2699
+2700
+2701
+2702
+2703
+2704
+2705
+2706
+2707
+2708
+2709
+2710
+2711
+2712
+2713
+2714
+2715
+2716
+2717
+2718
+2719
+2720
+2721
+2722
+2723
+2724
+2725
+2726
+2727
+2728
+2729
+2730
+2731
+2732
+2733
+2734
+2735
+2736
+2737
+2738
+2739
+2740
+2741
+2742
+2743
+2744
+2745
+2746
+2747
+2748
+2749
+2750
+2751
+2752
+2753
+2754
+2755
+2756
+2757
+2758
+2759
+2760
+2761
+2762
+2763
+2764
+2765
+2766
+2767
+2768
+2769
+2770
+2771
+2772
+2773
+2774
+2775
+2776
+2777
+2778
+2779
+2780
+2781
+2782
+2783
+2784
+2785
+2786
+2787
+2788
+2789
+2790
+2791
+2792
+2793
+2794
+2795
+2796
+2797
+2798
+2799
+2800
+2801
+2802
+2803
+2804
+2805
+2806
+2807
+2808
+2809
+2810
+2811
+2812
+2813
+2814
+2815
+2816
+2817
+2818
+2819
+2820
+2821
+2822
+2823
+2824
+2825
+2826
+2827
+2828
+2829
+2830
+2831
+2832
+2833
+2834
+2835
+2836
+2837
+2838
+2839
+2840
+2841
+2842
+2843
+2844
+2845
+2846
+2847
+2848
+2849
+2850
+2851
+2852
+2853
+2854
+2855
+2856
+2857
+2858
+2859
+2860
+2861
+2862
+2863
+2864
+2865
+2866
+2867
+2868
+2869
+2870
+2871
+2872
+2873
+2874
+2875
+2876
+2877
+2878
+2879
+2880
+2881
+2882
+2883
+2884
+2885
+2886
+2887
+2888
+2889
+2890
+2891
+2892
+2893
+2894
+2895
+2896
+2897
+2898
+2899
+2900
+2901
+2902
+2903
+2904
+2905
+2906
+2907
+2908
+2909
+2910
+2911
+2912
+2913
+2914
+2915
+2916
+2917
+2918
+2919
+2920
+2921
+2922
+2923
+2924
+2925
+2926
+2927
+2928
+2929
+2930
+2931
+2932
+2933
+2934
+2935
+2936
+2937
+2938
+2939
+2940
+2941
+2942
+2943
+2944
+2945
+2946
+2947
+2948
+2949
+2950
+2951
+2952
+2953
+2954
+2955
+2956
+2957
+2958
+2959
+2960
+2961
+2962
+2963
+2964
+2965
+2966
+2967
+2968
+2969
+2970
+2971
+2972
+2973
+2974
+2975
+2976
+2977
+2978
+2979
+2980
+2981
+2982
+2983
+2984
+2985
+2986
+2987
+2988
+2989
+2990
+2991
+2992
+2993
+2994
+2995
+2996
+2997
+2998
+2999
+3000
+3001
+3002
+3003
+3004
+3005
+3006
+3007
+3008
+3009
+3010
+3011
+3012
+3013
+3014
+3015
+3016
+3017
+3018
+3019
+3020
+3021
+3022
+3023
+3024
+3025
+3026
+3027
+3028
+3029
+3030
+3031
+3032
+3033
+3034
+3035
+3036
+3037
+3038
+3039
+3040
+3041
+3042
+3043
+3044
+3045
+3046
+3047
+3048
+3049
+3050
+3051
+3052
+3053
+3054
+3055
+3056
+3057
+3058
+3059
+3060
+3061
+3062
+3063
+3064
+3065
+3066
+3067
+3068
+3069
+3070
+3071
+3072
+3073
+3074
+3075
+3076
+3077
+3078
+3079
+3080
+3081
+3082
+3083
+3084
+3085
+3086
+3087
+3088
+3089
+3090
+3091
+3092
+3093
+3094
+3095
+3096
+3097
+3098
+3099
+3100
+3101
+3102
+3103
+3104
+3105
+3106
+3107
+3108
+3109
+3110
+3111
+3112
+3113
+3114
+3115
+3116
+3117
+3118
+3119
+3120
+3121
+3122
+3123
+3124
+3125
+3126
+3127
+3128
+3129
+3130
+3131
+3132
+3133
+3134
+3135
+3136
+3137
+3138
+3139
+3140
+3141
+3142
+3143
+3144
+3145
+3146
+3147
+3148
+3149
+3150
+3151
+3152
+3153
+3154
+3155
+3156
+3157
+3158
+3159
+3160
+3161
+3162
+3163
+3164
+3165
+3166
+3167
+3168
+3169
+3170
+3171
+3172
+3173
+3174
+3175
+3176
+3177
+3178
+3179
+3180
+3181
+3182
+3183
+3184
+3185
+3186
+3187
+3188
+3189
+3190
+3191
+3192
+3193
+3194
+3195
+3196
+3197
+3198
+3199
+3200
+3201
+3202
+3203
+3204
+3205
+3206
+3207
+3208
+3209
+3210
+3211
+3212
+3213
+3214
+3215
+3216
+3217
+3218
+3219
+3220
+3221
+3222
+3223
+3224
+3225
+3226
+3227
+3228
+3229
+3230
+3231
+3232
+3233
+3234
+3235
+3236
+3237
+3238
+3239
+3240
+3241
+3242
+3243
+3244
+3245
+3246
+3247
+3248
+3249
+3250
+3251
+3252
+3253
+3254
+3255
+3256
+3257
+3258
+3259
+3260
+3261
+3262
+3263
+3264
+3265
+3266
+3267
+3268
+3269
+3270
+3271
+3272
+3273
+3274
+3275
+3276
+3277
+3278
+3279
+3280
+3281
+3282
+3283
+3284
+3285
+3286
+3287
+3288
+3289
+3290
+3291
+3292
+3293
+3294
+3295
+3296
+3297
+3298
+3299
+3300
+3301
+3302
+3303
+3304
+3305
+3306
+3307
+3308
+3309
+3310
+3311
+3312
+3313
+3314
+3315
+3316
+3317
+3318
+3319
+3320
+3321
+3322
+3323
+3324
+3325
+3326
+3327
+3328
+3329
+3330
+3331
+3332
+3333
+3334
+3335
+3336
+3337
+3338
+3339
+3340
+3341
+3342
+3343
+3344
+3345
+3346
+3347
+3348
+3349
+3350
+3351
+3352
+3353
+3354
+3355
+3356
+3357
+3358
+3359
+3360
+3361
+3362
+3363
+3364
+3365
+3366
+3367
+3368
+3369
+3370
+3371
+3372
+3373
+3374
+3375
+3376
+3377
+3378
+3379
+3380
+3381
+3382
+3383
+3384
+3385
+3386
+3387
+3388
+3389
+3390
+3391
+3392
+3393
+3394
+3395
+3396
+3397
+3398
+3399
+3400
+3401
+3402
+3403
+3404
+3405
+3406
+3407
+3408
+3409
+3410
+3411
+3412
+3413
+3414
+3415
+3416
+3417
+3418
+3419
+3420
+3421
+3422
+3423
+3424
+3425
+3426
+3427
+3428
+3429
+3430
+3431
+3432
+3433
+3434
+3435
+3436
+3437
+3438
+3439
+3440
+3441
+3442
+3443
+3444
+3445
+3446
+3447
+3448
+3449
+3450
+3451
+3452
+3453
+3454
+3455
+3456
+3457
+3458
+3459
+3460
+3461
+3462
+3463
+3464
+3465
+3466
+3467
+3468
+3469
+3470
+3471
+3472
+3473
+3474
+3475
+3476
+3477
+3478
+3479
+3480
+3481
+3482
+3483
+3484
+3485
+3486
+3487
+3488
+3489
+3490
+3491
+3492
+3493
+3494
+3495
+3496
+3497
+3498
+3499
+3500
+3501
+3502
+3503
+3504
+3505
+3506
+3507
+3508
+3509
+3510
+3511
+3512
+3513
+3514
+3515
+3516
+3517
+3518
+3519
+3520
+3521
+3522
+3523
+3524
+3525
+3526
+3527
+3528
+3529
+3530
+3531
+3532
+3533
+3534
+3535
+3536
+3537
+3538
+3539
+3540
+3541
+3542
+3543
+3544
+3545
+3546
+3547
+3548
+3549
+3550
+3551
+3552
+3553
+3554
+3555
+3556
+3557
+3558
+3559
+3560
+3561
+3562
+3563
+3564
+3565
+3566
+3567
+3568
+3569
+3570
+3571
+3572
+3573
+3574
+3575
+3576
+3577
+3578
+3579
+3580
+3581
+3582
+3583
+3584
+3585
+3586
+3587
+3588
+3589
+3590
+3591
+3592
+3593
+3594
+3595
+3596
+3597
+3598
+3599
+3600
+3601
+3602
+3603
+3604
+3605
+3606
+3607
+3608
+3609
+3610
+3611
+3612
+3613
+3614
+3615
+3616
+3617
+3618
+3619
+3620
+3621
+3622
+3623
+3624
+3625
+3626
+3627
+3628
+3629
+3630
+3631
+3632
+3633
+3634
+3635
+3636
+3637
+3638
+3639
+3640
+3641
+3642
+3643
+3644
+3645
+3646
+3647
+3648
+3649
+3650
+3651
+3652
+3653
+3654
+3655
+3656
+3657
+3658
+3659
+3660
+3661
+3662
+3663
+3664
+3665
+3666
+3667
+3668
+3669
+3670
+3671
+3672
+3673
+3674
+3675
+3676
+3677
+3678
+3679
+3680
+3681
+3682
+3683
+3684
+3685
+3686
+3687
+3688
+3689
+3690
+3691
+3692
+3693
+3694
+3695
+3696
+3697
+3698
+3699
+3700
+3701
+3702
+3703
+3704
+3705
+3706
+3707
+3708
+3709
+3710
+3711
+3712
+3713
+3714
+3715
+3716
+3717
+3718
+3719
+3720
+3721
+3722
+3723
+3724
+3725
+3726
+3727
+3728
+3729
+3730
+3731
+3732
+3733
+3734
+3735
+3736
+3737
+3738
+3739
+3740
+3741
+3742
+3743
+3744
+3745
+3746
+3747
+3748
+3749
+3750
+3751
+3752
+3753
+3754
+3755
+3756
+3757
+3758
+3759
+3760
+3761
+3762
+3763
+3764
+3765
+3766
+3767
+3768
+3769
+3770
+3771
+3772
+3773
+3774
+3775
+3776
+3777
+3778
+3779
+3780
+3781
+3782
+3783
+3784
+3785
+3786
+3787
+3788
+3789
+3790
+3791
+3792
+3793
+3794
+3795
+3796
+3797
+3798
+3799
+3800
+3801
+3802
+3803
+3804
+3805
+3806
+3807
+3808
+3809
+3810
+3811
+3812
+3813
+3814
+3815
+3816
+3817
+3818
+3819
+3820
+3821
+3822
+3823
+3824
+3825
+3826
+3827
+3828
+3829
+3830
+3831
+3832
+3833
+3834
+3835
+3836
+3837
+3838
+3839
+3840
+3841
+3842
+3843
+3844
+3845
+3846
+3847
+3848
+3849
+3850
+3851
+3852
+3853
+3854
+3855
+3856
+3857
+3858
+3859
+3860
+3861
+3862
+3863
+3864
+3865
+3866
+3867
+3868
+3869
+3870
+3871
+3872
+3873
+3874
+3875
+3876
+3877
+3878
+3879
+3880
+3881
+3882
+3883
+3884
+3885
+3886
+3887
+3888
+3889
+3890
+3891
+3892
+3893
+3894
+3895
+3896
+3897
+3898
+3899
+3900
+3901
+3902
+3903
+3904
+3905
+3906
+3907
+3908
+3909
+3910
+3911
+3912
+3913
+3914
+3915
+3916
+3917
+3918
+3919
+3920
+3921
+3922
+3923
+3924
+3925
+3926
+3927
+3928
+3929
+3930
+3931
+3932
+3933
+3934
+3935
+3936
+3937
+3938
+3939
+3940
+3941
+3942
+3943
+3944
+3945
+3946
+3947
+3948
+3949
+3950
+3951
+3952
+3953
+3954
+3955
+3956
+3957
+3958
+3959
+3960
+3961
+3962
+3963
+3964
+3965
+3966
+3967
+3968
+3969
+3970
+3971
+3972
+3973
+3974
+3975
+3976
+3977
+3978
+3979
+3980
+3981
+3982
+3983
+3984
+3985
+3986
+3987
+3988
+3989
+3990
+3991
+3992
+3993
+3994
+3995
+3996
+3997
+3998
+3999
+4000
+4001
+4002
+4003
+4004
+4005
+4006
+4007
+4008
+4009
+4010
+4011
+4012
+4013
+4014
+4015
+4016
+4017
+4018
+4019
+4020
+4021
+4022
+4023
+4024
+4025
+4026
+4027
+4028
+4029
+4030
+4031
+4032
+4033
+4034
+4035
+4036
+4037
+4038
+4039
+4040
+4041
+4042
+4043
+4044
+4045
+4046
+4047
+4048
+4049
+4050
+4051
+4052
+
/*!
+This crate provides convenience methods for encoding and decoding numbers in
+either [big-endian or little-endian order].
+
+The organization of the crate is pretty simple. A trait, [`ByteOrder`], specifies
+byte conversion methods for each type of number in Rust (sans numbers that have
+a platform dependent size like `usize` and `isize`). Two types, [`BigEndian`]
+and [`LittleEndian`] implement these methods. Finally, [`ReadBytesExt`] and
+[`WriteBytesExt`] provide convenience methods available to all types that
+implement [`Read`] and [`Write`].
+
+An alias, [`NetworkEndian`], for [`BigEndian`] is provided to help improve
+code clarity.
+
+An additional alias, [`NativeEndian`], is provided for the endianness of the
+local platform. This is convenient when serializing data for use and
+conversions are not desired.
+
+# Examples
+
+Read unsigned 16 bit big-endian integers from a [`Read`] type:
+
+```rust
+use std::io::Cursor;
+use byteorder::{BigEndian, ReadBytesExt};
+
+let mut rdr = Cursor::new(vec![2, 5, 3, 0]);
+// Note that we use type parameters to indicate which kind of byte order
+// we want!
+assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap());
+assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap());
+```
+
+Write unsigned 16 bit little-endian integers to a [`Write`] type:
+
+```rust
+use byteorder::{LittleEndian, WriteBytesExt};
+
+let mut wtr = vec![];
+wtr.write_u16::<LittleEndian>(517).unwrap();
+wtr.write_u16::<LittleEndian>(768).unwrap();
+assert_eq!(wtr, vec![5, 2, 0, 3]);
+```
+
+# Optional Features
+
+This crate optionally provides support for 128 bit values (`i128` and `u128`)
+when built with the `i128` feature enabled.
+
+This crate can also be used without the standard library.
+
+# Alternatives
+
+Note that as of Rust 1.32, the standard numeric types provide built-in methods
+like `to_le_bytes` and `from_le_bytes`, which support some of the same use
+cases.
+
+[big-endian or little-endian order]: https://en.wikipedia.org/wiki/Endianness
+[`ByteOrder`]: trait.ByteOrder.html
+[`BigEndian`]: enum.BigEndian.html
+[`LittleEndian`]: enum.LittleEndian.html
+[`ReadBytesExt`]: trait.ReadBytesExt.html
+[`WriteBytesExt`]: trait.WriteBytesExt.html
+[`NetworkEndian`]: type.NetworkEndian.html
+[`NativeEndian`]: type.NativeEndian.html
+[`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
+[`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
+*/
+
+#![deny(missing_docs)]
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use core::{
+    convert::TryInto, fmt::Debug, hash::Hash, ptr::copy_nonoverlapping, slice,
+};
+
+#[cfg(feature = "std")]
+pub use crate::io::{ReadBytesExt, WriteBytesExt};
+
+#[cfg(feature = "std")]
+mod io;
+
+#[inline]
+fn extend_sign(val: u64, nbytes: usize) -> i64 {
+    let shift = (8 - nbytes) * 8;
+    (val << shift) as i64 >> shift
+}
+
+#[inline]
+fn extend_sign128(val: u128, nbytes: usize) -> i128 {
+    let shift = (16 - nbytes) * 8;
+    (val << shift) as i128 >> shift
+}
+
+#[inline]
+fn unextend_sign(val: i64, nbytes: usize) -> u64 {
+    let shift = (8 - nbytes) * 8;
+    (val << shift) as u64 >> shift
+}
+
+#[inline]
+fn unextend_sign128(val: i128, nbytes: usize) -> u128 {
+    let shift = (16 - nbytes) * 8;
+    (val << shift) as u128 >> shift
+}
+
+#[inline]
+fn pack_size(n: u64) -> usize {
+    if n < 1 << 8 {
+        1
+    } else if n < 1 << 16 {
+        2
+    } else if n < 1 << 24 {
+        3
+    } else if n < 1 << 32 {
+        4
+    } else if n < 1 << 40 {
+        5
+    } else if n < 1 << 48 {
+        6
+    } else if n < 1 << 56 {
+        7
+    } else {
+        8
+    }
+}
+
+#[inline]
+fn pack_size128(n: u128) -> usize {
+    if n < 1 << 8 {
+        1
+    } else if n < 1 << 16 {
+        2
+    } else if n < 1 << 24 {
+        3
+    } else if n < 1 << 32 {
+        4
+    } else if n < 1 << 40 {
+        5
+    } else if n < 1 << 48 {
+        6
+    } else if n < 1 << 56 {
+        7
+    } else if n < 1 << 64 {
+        8
+    } else if n < 1 << 72 {
+        9
+    } else if n < 1 << 80 {
+        10
+    } else if n < 1 << 88 {
+        11
+    } else if n < 1 << 96 {
+        12
+    } else if n < 1 << 104 {
+        13
+    } else if n < 1 << 112 {
+        14
+    } else if n < 1 << 120 {
+        15
+    } else {
+        16
+    }
+}
+
+mod private {
+    /// Sealed stops crates other than byteorder from implementing any traits
+    /// that use it.
+    pub trait Sealed {}
+    impl Sealed for super::LittleEndian {}
+    impl Sealed for super::BigEndian {}
+}
+
+/// `ByteOrder` describes types that can serialize integers as bytes.
+///
+/// Note that `Self` does not appear anywhere in this trait's definition!
+/// Therefore, in order to use it, you'll need to use syntax like
+/// `T::read_u16(&[0, 1])` where `T` implements `ByteOrder`.
+///
+/// This crate provides two types that implement `ByteOrder`: [`BigEndian`]
+/// and [`LittleEndian`].
+/// This trait is sealed and cannot be implemented for callers to avoid
+/// breaking backwards compatibility when adding new derived traits.
+///
+/// # Examples
+///
+/// Write and read `u32` numbers in little endian order:
+///
+/// ```rust
+/// use byteorder::{ByteOrder, LittleEndian};
+///
+/// let mut buf = [0; 4];
+/// LittleEndian::write_u32(&mut buf, 1_000_000);
+/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+/// ```
+///
+/// Write and read `i16` numbers in big endian order:
+///
+/// ```rust
+/// use byteorder::{ByteOrder, BigEndian};
+///
+/// let mut buf = [0; 2];
+/// BigEndian::write_i16(&mut buf, -5_000);
+/// assert_eq!(-5_000, BigEndian::read_i16(&buf));
+/// ```
+///
+/// [`BigEndian`]: enum.BigEndian.html
+/// [`LittleEndian`]: enum.LittleEndian.html
+pub trait ByteOrder:
+    Clone
+    + Copy
+    + Debug
+    + Default
+    + Eq
+    + Hash
+    + Ord
+    + PartialEq
+    + PartialOrd
+    + private::Sealed
+{
+    /// Reads an unsigned 16 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 2`.
+    fn read_u16(buf: &[u8]) -> u16;
+
+    /// Reads an unsigned 24 bit integer from `buf`, stored in u32.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 3`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 24 bit `u32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_u24(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf));
+    /// ```
+    fn read_u24(buf: &[u8]) -> u32 {
+        Self::read_uint(buf, 3) as u32
+    }
+
+    /// Reads an unsigned 32 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 4`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 4];
+    /// LittleEndian::write_u32(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+    /// ```
+    fn read_u32(buf: &[u8]) -> u32;
+
+    /// Reads an unsigned 48 bit integer from `buf`, stored in u64.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 6`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 48 bit `u64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 6];
+    /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000);
+    /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf));
+    /// ```
+    fn read_u48(buf: &[u8]) -> u64 {
+        Self::read_uint(buf, 6) as u64
+    }
+
+    /// Reads an unsigned 64 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 8`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 8];
+    /// LittleEndian::write_u64(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf));
+    /// ```
+    fn read_u64(buf: &[u8]) -> u64;
+
+    /// Reads an unsigned 128 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 16`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 16];
+    /// LittleEndian::write_u128(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf));
+    /// ```
+    fn read_u128(buf: &[u8]) -> u128;
+
+    /// Reads an unsigned n-bytes integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `nbytes < 1` or `nbytes > 8` or
+    /// `buf.len() < nbytes`
+    ///
+    /// # Examples
+    ///
+    /// Write and read an n-byte number in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_uint(&mut buf, 1_000_000, 3);
+    /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3));
+    /// ```
+    fn read_uint(buf: &[u8], nbytes: usize) -> u64;
+
+    /// Reads an unsigned n-bytes integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `nbytes < 1` or `nbytes > 16` or
+    /// `buf.len() < nbytes`
+    ///
+    /// # Examples
+    ///
+    /// Write and read an n-byte number in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3);
+    /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3));
+    /// ```
+    fn read_uint128(buf: &[u8], nbytes: usize) -> u128;
+
+    /// Writes an unsigned 16 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 2`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 2];
+    /// LittleEndian::write_u16(&mut buf, 1_000);
+    /// assert_eq!(1_000, LittleEndian::read_u16(&buf));
+    /// ```
+    fn write_u16(buf: &mut [u8], n: u16);
+
+    /// Writes an unsigned 24 bit integer `n` to `buf`, stored in u32.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 3`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 24 bit `u32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_u24(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf));
+    /// ```
+    fn write_u24(buf: &mut [u8], n: u32) {
+        Self::write_uint(buf, n as u64, 3)
+    }
+
+    /// Writes an unsigned 32 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 4`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 4];
+    /// LittleEndian::write_u32(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+    /// ```
+    fn write_u32(buf: &mut [u8], n: u32);
+
+    /// Writes an unsigned 48 bit integer `n` to `buf`, stored in u64.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 6`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 48 bit `u64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 6];
+    /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000);
+    /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf));
+    /// ```
+    fn write_u48(buf: &mut [u8], n: u64) {
+        Self::write_uint(buf, n as u64, 6)
+    }
+
+    /// Writes an unsigned 64 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 8`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 8];
+    /// LittleEndian::write_u64(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf));
+    /// ```
+    fn write_u64(buf: &mut [u8], n: u64);
+
+    /// Writes an unsigned 128 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 16`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 16];
+    /// LittleEndian::write_u128(&mut buf, 1_000_000);
+    /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf));
+    /// ```
+    fn write_u128(buf: &mut [u8], n: u128);
+
+    /// Writes an unsigned integer `n` to `buf` using only `nbytes`.
+    ///
+    /// # Panics
+    ///
+    /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then
+    /// this method panics.
+    ///
+    /// # Examples
+    ///
+    /// Write and read an n-byte number in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_uint(&mut buf, 1_000_000, 3);
+    /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3));
+    /// ```
+    fn write_uint(buf: &mut [u8], n: u64, nbytes: usize);
+
+    /// Writes an unsigned integer `n` to `buf` using only `nbytes`.
+    ///
+    /// # Panics
+    ///
+    /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then
+    /// this method panics.
+    ///
+    /// # Examples
+    ///
+    /// Write and read an n-byte number in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3);
+    /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3));
+    /// ```
+    fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize);
+
+    /// Reads a signed 16 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 2`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 2];
+    /// LittleEndian::write_i16(&mut buf, -1_000);
+    /// assert_eq!(-1_000, LittleEndian::read_i16(&buf));
+    /// ```
+    #[inline]
+    fn read_i16(buf: &[u8]) -> i16 {
+        Self::read_u16(buf) as i16
+    }
+
+    /// Reads a signed 24 bit integer from `buf`, stored in i32.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 3`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 24 bit `i32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_i24(&mut buf, -1_000_000);
+    /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf));
+    /// ```
+    #[inline]
+    fn read_i24(buf: &[u8]) -> i32 {
+        Self::read_int(buf, 3) as i32
+    }
+
+    /// Reads a signed 32 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 4`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 4];
+    /// LittleEndian::write_i32(&mut buf, -1_000_000);
+    /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf));
+    /// ```
+    #[inline]
+    fn read_i32(buf: &[u8]) -> i32 {
+        Self::read_u32(buf) as i32
+    }
+
+    /// Reads a signed 48 bit integer from `buf`, stored in i64.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 6`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 48 bit `i64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 6];
+    /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000);
+    /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf));
+    /// ```
+    #[inline]
+    fn read_i48(buf: &[u8]) -> i64 {
+        Self::read_int(buf, 6) as i64
+    }
+
+    /// Reads a signed 64 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 8`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 8];
+    /// LittleEndian::write_i64(&mut buf, -1_000_000_000);
+    /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf));
+    /// ```
+    #[inline]
+    fn read_i64(buf: &[u8]) -> i64 {
+        Self::read_u64(buf) as i64
+    }
+
+    /// Reads a signed 128 bit integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 16`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 16];
+    /// LittleEndian::write_i128(&mut buf, -1_000_000_000);
+    /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf));
+    /// ```
+    #[inline]
+    fn read_i128(buf: &[u8]) -> i128 {
+        Self::read_u128(buf) as i128
+    }
+
+    /// Reads a signed n-bytes integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `nbytes < 1` or `nbytes > 8` or
+    /// `buf.len() < nbytes`
+    ///
+    /// # Examples
+    ///
+    /// Write and read n-length signed numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_int(&mut buf, -1_000, 3);
+    /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3));
+    /// ```
+    #[inline]
+    fn read_int(buf: &[u8], nbytes: usize) -> i64 {
+        extend_sign(Self::read_uint(buf, nbytes), nbytes)
+    }
+
+    /// Reads a signed n-bytes integer from `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `nbytes < 1` or `nbytes > 16` or
+    /// `buf.len() < nbytes`
+    ///
+    /// # Examples
+    ///
+    /// Write and read n-length signed numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_int128(&mut buf, -1_000, 3);
+    /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3));
+    /// ```
+    #[inline]
+    fn read_int128(buf: &[u8], nbytes: usize) -> i128 {
+        extend_sign128(Self::read_uint128(buf, nbytes), nbytes)
+    }
+
+    /// Reads a IEEE754 single-precision (4 bytes) floating point number.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 4`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let e = 2.71828;
+    /// let mut buf = [0; 4];
+    /// LittleEndian::write_f32(&mut buf, e);
+    /// assert_eq!(e, LittleEndian::read_f32(&buf));
+    /// ```
+    #[inline]
+    fn read_f32(buf: &[u8]) -> f32 {
+        f32::from_bits(Self::read_u32(buf))
+    }
+
+    /// Reads a IEEE754 double-precision (8 bytes) floating point number.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 8`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let phi = 1.6180339887;
+    /// let mut buf = [0; 8];
+    /// LittleEndian::write_f64(&mut buf, phi);
+    /// assert_eq!(phi, LittleEndian::read_f64(&buf));
+    /// ```
+    #[inline]
+    fn read_f64(buf: &[u8]) -> f64 {
+        f64::from_bits(Self::read_u64(buf))
+    }
+
+    /// Writes a signed 16 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 2`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 2];
+    /// LittleEndian::write_i16(&mut buf, -1_000);
+    /// assert_eq!(-1_000, LittleEndian::read_i16(&buf));
+    /// ```
+    #[inline]
+    fn write_i16(buf: &mut [u8], n: i16) {
+        Self::write_u16(buf, n as u16)
+    }
+
+    /// Writes a signed 24 bit integer `n` to `buf`, stored in i32.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 3`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 24 bit `i32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_i24(&mut buf, -1_000_000);
+    /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf));
+    /// ```
+    #[inline]
+    fn write_i24(buf: &mut [u8], n: i32) {
+        Self::write_int(buf, n as i64, 3)
+    }
+
+    /// Writes a signed 32 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 4`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 4];
+    /// LittleEndian::write_i32(&mut buf, -1_000_000);
+    /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf));
+    /// ```
+    #[inline]
+    fn write_i32(buf: &mut [u8], n: i32) {
+        Self::write_u32(buf, n as u32)
+    }
+
+    /// Writes a signed 48 bit integer `n` to `buf`, stored in i64.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 6`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read 48 bit `i64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 6];
+    /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000);
+    /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf));
+    /// ```
+    #[inline]
+    fn write_i48(buf: &mut [u8], n: i64) {
+        Self::write_int(buf, n as i64, 6)
+    }
+
+    /// Writes a signed 64 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 8`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 8];
+    /// LittleEndian::write_i64(&mut buf, -1_000_000_000);
+    /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf));
+    /// ```
+    #[inline]
+    fn write_i64(buf: &mut [u8], n: i64) {
+        Self::write_u64(buf, n as u64)
+    }
+
+    /// Writes a signed 128 bit integer `n` to `buf`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 16`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read n-byte `i128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 16];
+    /// LittleEndian::write_i128(&mut buf, -1_000_000_000);
+    /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf));
+    /// ```
+    #[inline]
+    fn write_i128(buf: &mut [u8], n: i128) {
+        Self::write_u128(buf, n as u128)
+    }
+
+    /// Writes a signed integer `n` to `buf` using only `nbytes`.
+    ///
+    /// # Panics
+    ///
+    /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then
+    /// this method panics.
+    ///
+    /// # Examples
+    ///
+    /// Write and read an n-byte number in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_int(&mut buf, -1_000, 3);
+    /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3));
+    /// ```
+    #[inline]
+    fn write_int(buf: &mut [u8], n: i64, nbytes: usize) {
+        Self::write_uint(buf, unextend_sign(n, nbytes), nbytes)
+    }
+
+    /// Writes a signed integer `n` to `buf` using only `nbytes`.
+    ///
+    /// # Panics
+    ///
+    /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then
+    /// this method panics.
+    ///
+    /// # Examples
+    ///
+    /// Write and read n-length signed numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut buf = [0; 3];
+    /// LittleEndian::write_int128(&mut buf, -1_000, 3);
+    /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3));
+    /// ```
+    #[inline]
+    fn write_int128(buf: &mut [u8], n: i128, nbytes: usize) {
+        Self::write_uint128(buf, unextend_sign128(n, nbytes), nbytes)
+    }
+
+    /// Writes a IEEE754 single-precision (4 bytes) floating point number.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 4`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let e = 2.71828;
+    /// let mut buf = [0; 4];
+    /// LittleEndian::write_f32(&mut buf, e);
+    /// assert_eq!(e, LittleEndian::read_f32(&buf));
+    /// ```
+    #[inline]
+    fn write_f32(buf: &mut [u8], n: f32) {
+        Self::write_u32(buf, n.to_bits())
+    }
+
+    /// Writes a IEEE754 double-precision (8 bytes) floating point number.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() < 8`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let phi = 1.6180339887;
+    /// let mut buf = [0; 8];
+    /// LittleEndian::write_f64(&mut buf, phi);
+    /// assert_eq!(phi, LittleEndian::read_f64(&buf));
+    /// ```
+    #[inline]
+    fn write_f64(buf: &mut [u8], n: f64) {
+        Self::write_u64(buf, n.to_bits())
+    }
+
+    /// Reads unsigned 16 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 2*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 8];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u16_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u16_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn read_u16_into(src: &[u8], dst: &mut [u16]);
+
+    /// Reads unsigned 32 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 4*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u32_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn read_u32_into(src: &[u8], dst: &mut [u32]);
+
+    /// Reads unsigned 64 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 8*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u64_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn read_u64_into(src: &[u8], dst: &mut [u64]);
+
+    /// Reads unsigned 128 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 16*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 64];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u128_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u128_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn read_u128_into(src: &[u8], dst: &mut [u128]);
+
+    /// Reads signed 16 bit integers from `src` to `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() != 2*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 8];
+    /// let numbers_given = [1, 2, 0x0f, 0xee];
+    /// LittleEndian::write_i16_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i16_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    fn read_i16_into(src: &[u8], dst: &mut [i16]) {
+        let dst = unsafe {
+            slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u16, dst.len())
+        };
+        Self::read_u16_into(src, dst)
+    }
+
+    /// Reads signed 32 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 4*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_i32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i32_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    fn read_i32_into(src: &[u8], dst: &mut [i32]) {
+        let dst = unsafe {
+            slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len())
+        };
+        Self::read_u32_into(src, dst);
+    }
+
+    /// Reads signed 64 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 8*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_i64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i64_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    fn read_i64_into(src: &[u8], dst: &mut [i64]) {
+        let dst = unsafe {
+            slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len())
+        };
+        Self::read_u64_into(src, dst);
+    }
+
+    /// Reads signed 128 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 16*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 64];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_i128_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i128_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    fn read_i128_into(src: &[u8], dst: &mut [i128]) {
+        let dst = unsafe {
+            slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u128, dst.len())
+        };
+        Self::read_u128_into(src, dst);
+    }
+
+    /// Reads IEEE754 single-precision (4 bytes) floating point numbers from
+    /// `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 4*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19];
+    /// LittleEndian::write_f32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0.0; 4];
+    /// LittleEndian::read_f32_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    fn read_f32_into(src: &[u8], dst: &mut [f32]) {
+        let dst = unsafe {
+            slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len())
+        };
+        Self::read_u32_into(src, dst);
+    }
+
+    /// **DEPRECATED**.
+    ///
+    /// This method is deprecated. Use `read_f32_into` instead.
+    /// Reads IEEE754 single-precision (4 bytes) floating point numbers from
+    /// `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 4*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19];
+    /// LittleEndian::write_f32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0.0; 4];
+    /// LittleEndian::read_f32_into_unchecked(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    #[deprecated(since = "1.3.0", note = "please use `read_f32_into` instead")]
+    fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32]) {
+        Self::read_f32_into(src, dst);
+    }
+
+    /// Reads IEEE754 single-precision (4 bytes) floating point numbers from
+    /// `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 8*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91];
+    /// LittleEndian::write_f64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0.0; 4];
+    /// LittleEndian::read_f64_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    fn read_f64_into(src: &[u8], dst: &mut [f64]) {
+        let dst = unsafe {
+            slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len())
+        };
+        Self::read_u64_into(src, dst);
+    }
+
+    /// **DEPRECATED**.
+    ///
+    /// This method is deprecated. Use `read_f64_into` instead.
+    ///
+    /// Reads IEEE754 single-precision (4 bytes) floating point numbers from
+    /// `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 8*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91];
+    /// LittleEndian::write_f64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0.0; 4];
+    /// LittleEndian::read_f64_into_unchecked(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    #[inline]
+    #[deprecated(since = "1.3.0", note = "please use `read_f64_into` instead")]
+    fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64]) {
+        Self::read_f64_into(src, dst);
+    }
+
+    /// Writes unsigned 16 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 2*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 8];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u16_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u16_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_u16_into(src: &[u16], dst: &mut [u8]);
+
+    /// Writes unsigned 32 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 4*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u32_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_u32_into(src: &[u32], dst: &mut [u8]);
+
+    /// Writes unsigned 64 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 8*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u64_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_u64_into(src: &[u64], dst: &mut [u8]);
+
+    /// Writes unsigned 128 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 16*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `u128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 64];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_u128_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_u128_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_u128_into(src: &[u128], dst: &mut [u8]);
+
+    /// Writes signed 8 bit integers from `src` into `dst`.
+    ///
+    /// Note that since each `i8` is a single byte, no byte order conversions
+    /// are used. This method is included because it provides a safe, simple
+    /// way for the caller to write from a `&[i8]` buffer. (Without this
+    /// method, the caller would have to either use `unsafe` code or convert
+    /// each byte to `u8` individually.)
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() != src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i8` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
+    ///
+    /// let mut bytes = [0; 4];
+    /// let numbers_given = [1, 2, 0xf, 0xe];
+    /// LittleEndian::write_i8_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// bytes.as_ref().read_i8_into(&mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_i8_into(src: &[i8], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u8, src.len())
+        };
+        dst.copy_from_slice(src);
+    }
+
+    /// Writes signed 16 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `buf.len() != 2*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i16` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 8];
+    /// let numbers_given = [1, 2, 0x0f, 0xee];
+    /// LittleEndian::write_i16_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i16_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_i16_into(src: &[i16], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u16, src.len())
+        };
+        Self::write_u16_into(src, dst);
+    }
+
+    /// Writes signed 32 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 4*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_i32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i32_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_i32_into(src: &[i32], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u32, src.len())
+        };
+        Self::write_u32_into(src, dst);
+    }
+
+    /// Writes signed 64 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 8*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_i64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i64_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_i64_into(src: &[i64], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u64, src.len())
+        };
+        Self::write_u64_into(src, dst);
+    }
+
+    /// Writes signed 128 bit integers from `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `dst.len() != 16*src.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `i128` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 64];
+    /// let numbers_given = [1, 2, 0xf00f, 0xffee];
+    /// LittleEndian::write_i128_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0; 4];
+    /// LittleEndian::read_i128_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_i128_into(src: &[i128], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u128, src.len())
+        };
+        Self::write_u128_into(src, dst);
+    }
+
+    /// Writes IEEE754 single-precision (4 bytes) floating point numbers from
+    /// `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 4*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f32` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 16];
+    /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19];
+    /// LittleEndian::write_f32_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0.0; 4];
+    /// LittleEndian::read_f32_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_f32_into(src: &[f32], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u32, src.len())
+        };
+        Self::write_u32_into(src, dst);
+    }
+
+    /// Writes IEEE754 double-precision (8 bytes) floating point numbers from
+    /// `src` into `dst`.
+    ///
+    /// # Panics
+    ///
+    /// Panics when `src.len() != 8*dst.len()`.
+    ///
+    /// # Examples
+    ///
+    /// Write and read `f64` numbers in little endian order:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, LittleEndian};
+    ///
+    /// let mut bytes = [0; 32];
+    /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91];
+    /// LittleEndian::write_f64_into(&numbers_given, &mut bytes);
+    ///
+    /// let mut numbers_got = [0.0; 4];
+    /// LittleEndian::read_f64_into(&bytes, &mut numbers_got);
+    /// assert_eq!(numbers_given, numbers_got);
+    /// ```
+    fn write_f64_into(src: &[f64], dst: &mut [u8]) {
+        let src = unsafe {
+            slice::from_raw_parts(src.as_ptr() as *const u64, src.len())
+        };
+        Self::write_u64_into(src, dst);
+    }
+
+    /// Converts the given slice of unsigned 16 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_u16(&mut numbers);
+    /// assert_eq!(numbers, [5u16.to_be(), 65000u16.to_be()]);
+    /// ```
+    fn from_slice_u16(numbers: &mut [u16]);
+
+    /// Converts the given slice of unsigned 32 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_u32(&mut numbers);
+    /// assert_eq!(numbers, [5u32.to_be(), 65000u32.to_be()]);
+    /// ```
+    fn from_slice_u32(numbers: &mut [u32]);
+
+    /// Converts the given slice of unsigned 64 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_u64(&mut numbers);
+    /// assert_eq!(numbers, [5u64.to_be(), 65000u64.to_be()]);
+    /// ```
+    fn from_slice_u64(numbers: &mut [u64]);
+
+    /// Converts the given slice of unsigned 128 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_u128(&mut numbers);
+    /// assert_eq!(numbers, [5u128.to_be(), 65000u128.to_be()]);
+    /// ```
+    fn from_slice_u128(numbers: &mut [u128]);
+
+    /// Converts the given slice of signed 16 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 6500];
+    /// BigEndian::from_slice_i16(&mut numbers);
+    /// assert_eq!(numbers, [5i16.to_be(), 6500i16.to_be()]);
+    /// ```
+    #[inline]
+    fn from_slice_i16(src: &mut [i16]) {
+        let src = unsafe {
+            slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u16, src.len())
+        };
+        Self::from_slice_u16(src);
+    }
+
+    /// Converts the given slice of signed 32 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_i32(&mut numbers);
+    /// assert_eq!(numbers, [5i32.to_be(), 65000i32.to_be()]);
+    /// ```
+    #[inline]
+    fn from_slice_i32(src: &mut [i32]) {
+        let src = unsafe {
+            slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u32, src.len())
+        };
+        Self::from_slice_u32(src);
+    }
+
+    /// Converts the given slice of signed 64 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_i64(&mut numbers);
+    /// assert_eq!(numbers, [5i64.to_be(), 65000i64.to_be()]);
+    /// ```
+    #[inline]
+    fn from_slice_i64(src: &mut [i64]) {
+        let src = unsafe {
+            slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u64, src.len())
+        };
+        Self::from_slice_u64(src);
+    }
+
+    /// Converts the given slice of signed 128 bit integers to a particular
+    /// endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    ///
+    /// # Examples
+    ///
+    /// Convert the host platform's endianness to big-endian:
+    ///
+    /// ```rust
+    /// use byteorder::{ByteOrder, BigEndian};
+    ///
+    /// let mut numbers = [5, 65000];
+    /// BigEndian::from_slice_i128(&mut numbers);
+    /// assert_eq!(numbers, [5i128.to_be(), 65000i128.to_be()]);
+    /// ```
+    #[inline]
+    fn from_slice_i128(src: &mut [i128]) {
+        let src = unsafe {
+            slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u128, src.len())
+        };
+        Self::from_slice_u128(src);
+    }
+
+    /// Converts the given slice of IEEE754 single-precision (4 bytes) floating
+    /// point numbers to a particular endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    fn from_slice_f32(numbers: &mut [f32]);
+
+    /// Converts the given slice of IEEE754 double-precision (8 bytes) floating
+    /// point numbers to a particular endianness.
+    ///
+    /// If the endianness matches the endianness of the host platform, then
+    /// this is a no-op.
+    fn from_slice_f64(numbers: &mut [f64]);
+}
+
+/// Defines big-endian serialization.
+///
+/// Note that this type has no value constructor. It is used purely at the
+/// type level.
+///
+/// # Examples
+///
+/// Write and read `u32` numbers in big endian order:
+///
+/// ```rust
+/// use byteorder::{ByteOrder, BigEndian};
+///
+/// let mut buf = [0; 4];
+/// BigEndian::write_u32(&mut buf, 1_000_000);
+/// assert_eq!(1_000_000, BigEndian::read_u32(&buf));
+/// ```
+#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
+pub enum BigEndian {}
+
+impl Default for BigEndian {
+    fn default() -> BigEndian {
+        panic!("BigEndian default")
+    }
+}
+
+/// A type alias for [`BigEndian`].
+///
+/// [`BigEndian`]: enum.BigEndian.html
+pub type BE = BigEndian;
+
+/// Defines little-endian serialization.
+///
+/// Note that this type has no value constructor. It is used purely at the
+/// type level.
+///
+/// # Examples
+///
+/// Write and read `u32` numbers in little endian order:
+///
+/// ```rust
+/// use byteorder::{ByteOrder, LittleEndian};
+///
+/// let mut buf = [0; 4];
+/// LittleEndian::write_u32(&mut buf, 1_000_000);
+/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf));
+/// ```
+#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
+pub enum LittleEndian {}
+
+impl Default for LittleEndian {
+    fn default() -> LittleEndian {
+        panic!("LittleEndian default")
+    }
+}
+
+/// A type alias for [`LittleEndian`].
+///
+/// [`LittleEndian`]: enum.LittleEndian.html
+pub type LE = LittleEndian;
+
+/// Defines network byte order serialization.
+///
+/// Network byte order is defined by [RFC 1700][1] to be big-endian, and is
+/// referred to in several protocol specifications.  This type is an alias of
+/// [`BigEndian`].
+///
+/// [1]: https://tools.ietf.org/html/rfc1700
+///
+/// Note that this type has no value constructor. It is used purely at the
+/// type level.
+///
+/// # Examples
+///
+/// Write and read `i16` numbers in big endian order:
+///
+/// ```rust
+/// use byteorder::{ByteOrder, NetworkEndian, BigEndian};
+///
+/// let mut buf = [0; 2];
+/// BigEndian::write_i16(&mut buf, -5_000);
+/// assert_eq!(-5_000, NetworkEndian::read_i16(&buf));
+/// ```
+///
+/// [`BigEndian`]: enum.BigEndian.html
+pub type NetworkEndian = BigEndian;
+
+/// Defines system native-endian serialization.
+///
+/// Note that this type has no value constructor. It is used purely at the
+/// type level.
+///
+/// On this platform, this is an alias for [`LittleEndian`].
+///
+/// [`LittleEndian`]: enum.LittleEndian.html
+#[cfg(target_endian = "little")]
+pub type NativeEndian = LittleEndian;
+
+/// Defines system native-endian serialization.
+///
+/// Note that this type has no value constructor. It is used purely at the
+/// type level.
+///
+/// On this platform, this is an alias for [`BigEndian`].
+///
+/// [`BigEndian`]: enum.BigEndian.html
+#[cfg(target_endian = "big")]
+pub type NativeEndian = BigEndian;
+
+/// Copies $size bytes from a number $n to a &mut [u8] $dst. $ty represents the
+/// numeric type of $n and $which must be either to_be or to_le, depending on
+/// which endianness one wants to use when writing to $dst.
+///
+/// This macro is only safe to call when $ty is a numeric type and $size ==
+/// size_of::<$ty>() and where $dst is a &mut [u8].
+macro_rules! unsafe_write_num_bytes {
+    ($ty:ty, $size:expr, $n:expr, $dst:expr, $which:ident) => {{
+        assert!($size <= $dst.len());
+        unsafe {
+            // N.B. https://github.com/rust-lang/rust/issues/22776
+            let bytes = *(&$n.$which() as *const _ as *const [u8; $size]);
+            copy_nonoverlapping((&bytes).as_ptr(), $dst.as_mut_ptr(), $size);
+        }
+    }};
+}
+
+/// Copies a &[u8] $src into a &mut [<numeric>] $dst for the endianness given
+/// by $which (must be either to_be or to_le).
+///
+/// This macro is only safe to call when $src and $dst are &[u8] and &mut [u8],
+/// respectively. The macro will panic if $src.len() != $size * $dst.len(),
+/// where $size represents the size of the integers encoded in $src.
+macro_rules! unsafe_read_slice {
+    ($src:expr, $dst:expr, $size:expr, $which:ident) => {{
+        assert_eq!($src.len(), $size * $dst.len());
+
+        unsafe {
+            copy_nonoverlapping(
+                $src.as_ptr(),
+                $dst.as_mut_ptr() as *mut u8,
+                $src.len(),
+            );
+        }
+        for v in $dst.iter_mut() {
+            *v = v.$which();
+        }
+    }};
+}
+
+/// Copies a &[$ty] $src into a &mut [u8] $dst, where $ty must be a numeric
+/// type. This panics if size_of::<$ty>() * $src.len() != $dst.len().
+///
+/// This macro is only safe to call when $src is a slice of numeric types and
+/// $dst is a &mut [u8] and where $ty represents the type of the integers in
+/// $src.
+macro_rules! unsafe_write_slice_native {
+    ($src:expr, $dst:expr, $ty:ty) => {{
+        let size = core::mem::size_of::<$ty>();
+        assert_eq!(size * $src.len(), $dst.len());
+
+        unsafe {
+            copy_nonoverlapping(
+                $src.as_ptr() as *const u8,
+                $dst.as_mut_ptr(),
+                $dst.len(),
+            );
+        }
+    }};
+}
+
+macro_rules! write_slice {
+    ($src:expr, $dst:expr, $ty:ty, $size:expr, $write:expr) => {{
+        assert!($size == ::core::mem::size_of::<$ty>());
+        assert_eq!($size * $src.len(), $dst.len());
+
+        for (&n, chunk) in $src.iter().zip($dst.chunks_mut($size)) {
+            $write(chunk, n);
+        }
+    }};
+}
+
+impl ByteOrder for BigEndian {
+    #[inline]
+    fn read_u16(buf: &[u8]) -> u16 {
+        u16::from_be_bytes(buf[..2].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_u32(buf: &[u8]) -> u32 {
+        u32::from_be_bytes(buf[..4].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_u64(buf: &[u8]) -> u64 {
+        u64::from_be_bytes(buf[..8].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_u128(buf: &[u8]) -> u128 {
+        u128::from_be_bytes(buf[..16].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_uint(buf: &[u8], nbytes: usize) -> u64 {
+        assert!(1 <= nbytes && nbytes <= 8 && nbytes <= buf.len());
+        let mut out = 0u64;
+        let ptr_out = &mut out as *mut u64 as *mut u8;
+        unsafe {
+            copy_nonoverlapping(
+                buf.as_ptr(),
+                ptr_out.offset((8 - nbytes) as isize),
+                nbytes,
+            );
+        }
+        out.to_be()
+    }
+
+    #[inline]
+    fn read_uint128(buf: &[u8], nbytes: usize) -> u128 {
+        assert!(1 <= nbytes && nbytes <= 16 && nbytes <= buf.len());
+        let mut out: u128 = 0;
+        let ptr_out = &mut out as *mut u128 as *mut u8;
+        unsafe {
+            copy_nonoverlapping(
+                buf.as_ptr(),
+                ptr_out.offset((16 - nbytes) as isize),
+                nbytes,
+            );
+        }
+        out.to_be()
+    }
+
+    #[inline]
+    fn write_u16(buf: &mut [u8], n: u16) {
+        unsafe_write_num_bytes!(u16, 2, n, buf, to_be);
+    }
+
+    #[inline]
+    fn write_u32(buf: &mut [u8], n: u32) {
+        unsafe_write_num_bytes!(u32, 4, n, buf, to_be);
+    }
+
+    #[inline]
+    fn write_u64(buf: &mut [u8], n: u64) {
+        unsafe_write_num_bytes!(u64, 8, n, buf, to_be);
+    }
+
+    #[inline]
+    fn write_u128(buf: &mut [u8], n: u128) {
+        unsafe_write_num_bytes!(u128, 16, n, buf, to_be);
+    }
+
+    #[inline]
+    fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) {
+        assert!(pack_size(n) <= nbytes && nbytes <= 8);
+        assert!(nbytes <= buf.len());
+        unsafe {
+            let bytes = *(&n.to_be() as *const u64 as *const [u8; 8]);
+            copy_nonoverlapping(
+                bytes.as_ptr().offset((8 - nbytes) as isize),
+                buf.as_mut_ptr(),
+                nbytes,
+            );
+        }
+    }
+
+    #[inline]
+    fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) {
+        assert!(pack_size128(n) <= nbytes && nbytes <= 16);
+        assert!(nbytes <= buf.len());
+        unsafe {
+            let bytes = *(&n.to_be() as *const u128 as *const [u8; 16]);
+            copy_nonoverlapping(
+                bytes.as_ptr().offset((16 - nbytes) as isize),
+                buf.as_mut_ptr(),
+                nbytes,
+            );
+        }
+    }
+
+    #[inline]
+    fn read_u16_into(src: &[u8], dst: &mut [u16]) {
+        unsafe_read_slice!(src, dst, 2, to_be);
+    }
+
+    #[inline]
+    fn read_u32_into(src: &[u8], dst: &mut [u32]) {
+        unsafe_read_slice!(src, dst, 4, to_be);
+    }
+
+    #[inline]
+    fn read_u64_into(src: &[u8], dst: &mut [u64]) {
+        unsafe_read_slice!(src, dst, 8, to_be);
+    }
+
+    #[inline]
+    fn read_u128_into(src: &[u8], dst: &mut [u128]) {
+        unsafe_read_slice!(src, dst, 16, to_be);
+    }
+
+    #[inline]
+    fn write_u16_into(src: &[u16], dst: &mut [u8]) {
+        if cfg!(target_endian = "big") {
+            unsafe_write_slice_native!(src, dst, u16);
+        } else {
+            write_slice!(src, dst, u16, 2, Self::write_u16);
+        }
+    }
+
+    #[inline]
+    fn write_u32_into(src: &[u32], dst: &mut [u8]) {
+        if cfg!(target_endian = "big") {
+            unsafe_write_slice_native!(src, dst, u32);
+        } else {
+            write_slice!(src, dst, u32, 4, Self::write_u32);
+        }
+    }
+
+    #[inline]
+    fn write_u64_into(src: &[u64], dst: &mut [u8]) {
+        if cfg!(target_endian = "big") {
+            unsafe_write_slice_native!(src, dst, u64);
+        } else {
+            write_slice!(src, dst, u64, 8, Self::write_u64);
+        }
+    }
+
+    #[inline]
+    fn write_u128_into(src: &[u128], dst: &mut [u8]) {
+        if cfg!(target_endian = "big") {
+            unsafe_write_slice_native!(src, dst, u128);
+        } else {
+            write_slice!(src, dst, u128, 16, Self::write_u128);
+        }
+    }
+
+    #[inline]
+    fn from_slice_u16(numbers: &mut [u16]) {
+        if cfg!(target_endian = "little") {
+            for n in numbers {
+                *n = n.to_be();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_u32(numbers: &mut [u32]) {
+        if cfg!(target_endian = "little") {
+            for n in numbers {
+                *n = n.to_be();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_u64(numbers: &mut [u64]) {
+        if cfg!(target_endian = "little") {
+            for n in numbers {
+                *n = n.to_be();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_u128(numbers: &mut [u128]) {
+        if cfg!(target_endian = "little") {
+            for n in numbers {
+                *n = n.to_be();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_f32(numbers: &mut [f32]) {
+        if cfg!(target_endian = "little") {
+            for n in numbers {
+                unsafe {
+                    let int = *(n as *const f32 as *const u32);
+                    *n = *(&int.to_be() as *const u32 as *const f32);
+                }
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_f64(numbers: &mut [f64]) {
+        if cfg!(target_endian = "little") {
+            for n in numbers {
+                unsafe {
+                    let int = *(n as *const f64 as *const u64);
+                    *n = *(&int.to_be() as *const u64 as *const f64);
+                }
+            }
+        }
+    }
+}
+
+impl ByteOrder for LittleEndian {
+    #[inline]
+    fn read_u16(buf: &[u8]) -> u16 {
+        u16::from_le_bytes(buf[..2].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_u32(buf: &[u8]) -> u32 {
+        u32::from_le_bytes(buf[..4].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_u64(buf: &[u8]) -> u64 {
+        u64::from_le_bytes(buf[..8].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_u128(buf: &[u8]) -> u128 {
+        u128::from_le_bytes(buf[..16].try_into().unwrap())
+    }
+
+    #[inline]
+    fn read_uint(buf: &[u8], nbytes: usize) -> u64 {
+        assert!(1 <= nbytes && nbytes <= 8 && nbytes <= buf.len());
+        let mut out = 0u64;
+        let ptr_out = &mut out as *mut u64 as *mut u8;
+        unsafe {
+            copy_nonoverlapping(buf.as_ptr(), ptr_out, nbytes);
+        }
+        out.to_le()
+    }
+
+    #[inline]
+    fn read_uint128(buf: &[u8], nbytes: usize) -> u128 {
+        assert!(1 <= nbytes && nbytes <= 16 && nbytes <= buf.len());
+        let mut out: u128 = 0;
+        let ptr_out = &mut out as *mut u128 as *mut u8;
+        unsafe {
+            copy_nonoverlapping(buf.as_ptr(), ptr_out, nbytes);
+        }
+        out.to_le()
+    }
+
+    #[inline]
+    fn write_u16(buf: &mut [u8], n: u16) {
+        unsafe_write_num_bytes!(u16, 2, n, buf, to_le);
+    }
+
+    #[inline]
+    fn write_u32(buf: &mut [u8], n: u32) {
+        unsafe_write_num_bytes!(u32, 4, n, buf, to_le);
+    }
+
+    #[inline]
+    fn write_u64(buf: &mut [u8], n: u64) {
+        unsafe_write_num_bytes!(u64, 8, n, buf, to_le);
+    }
+
+    #[inline]
+    fn write_u128(buf: &mut [u8], n: u128) {
+        unsafe_write_num_bytes!(u128, 16, n, buf, to_le);
+    }
+
+    #[inline]
+    fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) {
+        assert!(pack_size(n as u64) <= nbytes && nbytes <= 8);
+        assert!(nbytes <= buf.len());
+        unsafe {
+            let bytes = *(&n.to_le() as *const u64 as *const [u8; 8]);
+            copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes);
+        }
+    }
+
+    #[inline]
+    fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) {
+        assert!(pack_size128(n as u128) <= nbytes && nbytes <= 16);
+        assert!(nbytes <= buf.len());
+        unsafe {
+            let bytes = *(&n.to_le() as *const u128 as *const [u8; 16]);
+            copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes);
+        }
+    }
+
+    #[inline]
+    fn read_u16_into(src: &[u8], dst: &mut [u16]) {
+        unsafe_read_slice!(src, dst, 2, to_le);
+    }
+
+    #[inline]
+    fn read_u32_into(src: &[u8], dst: &mut [u32]) {
+        unsafe_read_slice!(src, dst, 4, to_le);
+    }
+
+    #[inline]
+    fn read_u64_into(src: &[u8], dst: &mut [u64]) {
+        unsafe_read_slice!(src, dst, 8, to_le);
+    }
+
+    #[inline]
+    fn read_u128_into(src: &[u8], dst: &mut [u128]) {
+        unsafe_read_slice!(src, dst, 16, to_le);
+    }
+
+    #[inline]
+    fn write_u16_into(src: &[u16], dst: &mut [u8]) {
+        if cfg!(target_endian = "little") {
+            unsafe_write_slice_native!(src, dst, u16);
+        } else {
+            write_slice!(src, dst, u16, 2, Self::write_u16);
+        }
+    }
+
+    #[inline]
+    fn write_u32_into(src: &[u32], dst: &mut [u8]) {
+        if cfg!(target_endian = "little") {
+            unsafe_write_slice_native!(src, dst, u32);
+        } else {
+            write_slice!(src, dst, u32, 4, Self::write_u32);
+        }
+    }
+
+    #[inline]
+    fn write_u64_into(src: &[u64], dst: &mut [u8]) {
+        if cfg!(target_endian = "little") {
+            unsafe_write_slice_native!(src, dst, u64);
+        } else {
+            write_slice!(src, dst, u64, 8, Self::write_u64);
+        }
+    }
+
+    #[inline]
+    fn write_u128_into(src: &[u128], dst: &mut [u8]) {
+        if cfg!(target_endian = "little") {
+            unsafe_write_slice_native!(src, dst, u128);
+        } else {
+            write_slice!(src, dst, u128, 16, Self::write_u128);
+        }
+    }
+
+    #[inline]
+    fn from_slice_u16(numbers: &mut [u16]) {
+        if cfg!(target_endian = "big") {
+            for n in numbers {
+                *n = n.to_le();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_u32(numbers: &mut [u32]) {
+        if cfg!(target_endian = "big") {
+            for n in numbers {
+                *n = n.to_le();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_u64(numbers: &mut [u64]) {
+        if cfg!(target_endian = "big") {
+            for n in numbers {
+                *n = n.to_le();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_u128(numbers: &mut [u128]) {
+        if cfg!(target_endian = "big") {
+            for n in numbers {
+                *n = n.to_le();
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_f32(numbers: &mut [f32]) {
+        if cfg!(target_endian = "big") {
+            for n in numbers {
+                unsafe {
+                    let int = *(n as *const f32 as *const u32);
+                    *n = *(&int.to_le() as *const u32 as *const f32);
+                }
+            }
+        }
+    }
+
+    #[inline]
+    fn from_slice_f64(numbers: &mut [f64]) {
+        if cfg!(target_endian = "big") {
+            for n in numbers {
+                unsafe {
+                    let int = *(n as *const f64 as *const u64);
+                    *n = *(&int.to_le() as *const u64 as *const f64);
+                }
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen, Testable};
+    use rand::{thread_rng, Rng};
+
+    pub const U24_MAX: u32 = 16_777_215;
+    pub const I24_MAX: i32 = 8_388_607;
+    pub const U48_MAX: u64 = 281_474_976_710_655;
+    pub const I48_MAX: i64 = 140_737_488_355_327;
+
+    pub const U64_MAX: u64 = ::core::u64::MAX;
+    pub const I64_MAX: u64 = ::core::i64::MAX as u64;
+
+    macro_rules! calc_max {
+        ($max:expr, $bytes:expr) => {
+            calc_max!($max, $bytes, 8)
+        };
+        ($max:expr, $bytes:expr, $maxbytes:expr) => {
+            ($max - 1) >> (8 * ($maxbytes - $bytes))
+        };
+    }
+
+    #[derive(Clone, Debug)]
+    pub struct Wi128<T>(pub T);
+
+    impl<T: Clone> Wi128<T> {
+        pub fn clone(&self) -> T {
+            self.0.clone()
+        }
+    }
+
+    impl<T: PartialEq> PartialEq<T> for Wi128<T> {
+        fn eq(&self, other: &T) -> bool {
+            self.0.eq(other)
+        }
+    }
+
+    impl Arbitrary for Wi128<u128> {
+        fn arbitrary<G: Gen>(gen: &mut G) -> Wi128<u128> {
+            let max = calc_max!(::core::u128::MAX, gen.size(), 16);
+            let output = (gen.gen::<u64>() as u128)
+                | ((gen.gen::<u64>() as u128) << 64);
+            Wi128(output & (max - 1))
+        }
+    }
+
+    impl Arbitrary for Wi128<i128> {
+        fn arbitrary<G: Gen>(gen: &mut G) -> Wi128<i128> {
+            let max = calc_max!(::core::i128::MAX, gen.size(), 16);
+            let output = (gen.gen::<i64>() as i128)
+                | ((gen.gen::<i64>() as i128) << 64);
+            Wi128(output & (max - 1))
+        }
+    }
+
+    pub fn qc_sized<A: Testable>(f: A, size: u64) {
+        QuickCheck::new()
+            .gen(StdGen::new(thread_rng(), size as usize))
+            .tests(1_00)
+            .max_tests(10_000)
+            .quickcheck(f);
+    }
+
+    macro_rules! qc_byte_order {
+        ($name:ident, $ty_int:ty, $max:expr,
+         $bytes:expr, $read:ident, $write:ident) => {
+            mod $name {
+                #[allow(unused_imports)]
+                use super::{qc_sized, Wi128};
+                use crate::{
+                    BigEndian, ByteOrder, LittleEndian, NativeEndian,
+                };
+
+                #[test]
+                fn big_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut buf = [0; 16];
+                        BigEndian::$write(&mut buf, n.clone(), $bytes);
+                        n == BigEndian::$read(&buf[..$bytes], $bytes)
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max);
+                }
+
+                #[test]
+                fn little_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut buf = [0; 16];
+                        LittleEndian::$write(&mut buf, n.clone(), $bytes);
+                        n == LittleEndian::$read(&buf[..$bytes], $bytes)
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max);
+                }
+
+                #[test]
+                fn native_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut buf = [0; 16];
+                        NativeEndian::$write(&mut buf, n.clone(), $bytes);
+                        n == NativeEndian::$read(&buf[..$bytes], $bytes)
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max);
+                }
+            }
+        };
+        ($name:ident, $ty_int:ty, $max:expr,
+         $read:ident, $write:ident) => {
+            mod $name {
+                #[allow(unused_imports)]
+                use super::{qc_sized, Wi128};
+                use crate::{
+                    BigEndian, ByteOrder, LittleEndian, NativeEndian,
+                };
+                use core::mem::size_of;
+
+                #[test]
+                fn big_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let bytes = size_of::<$ty_int>();
+                        let mut buf = [0; 16];
+                        BigEndian::$write(&mut buf[16 - bytes..], n.clone());
+                        n == BigEndian::$read(&buf[16 - bytes..])
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max - 1);
+                }
+
+                #[test]
+                fn little_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let bytes = size_of::<$ty_int>();
+                        let mut buf = [0; 16];
+                        LittleEndian::$write(&mut buf[..bytes], n.clone());
+                        n == LittleEndian::$read(&buf[..bytes])
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max - 1);
+                }
+
+                #[test]
+                fn native_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let bytes = size_of::<$ty_int>();
+                        let mut buf = [0; 16];
+                        NativeEndian::$write(&mut buf[..bytes], n.clone());
+                        n == NativeEndian::$read(&buf[..bytes])
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max - 1);
+                }
+            }
+        };
+    }
+
+    qc_byte_order!(
+        prop_u16,
+        u16,
+        ::core::u16::MAX as u64,
+        read_u16,
+        write_u16
+    );
+    qc_byte_order!(
+        prop_i16,
+        i16,
+        ::core::i16::MAX as u64,
+        read_i16,
+        write_i16
+    );
+    qc_byte_order!(
+        prop_u24,
+        u32,
+        crate::test::U24_MAX as u64,
+        read_u24,
+        write_u24
+    );
+    qc_byte_order!(
+        prop_i24,
+        i32,
+        crate::test::I24_MAX as u64,
+        read_i24,
+        write_i24
+    );
+    qc_byte_order!(
+        prop_u32,
+        u32,
+        ::core::u32::MAX as u64,
+        read_u32,
+        write_u32
+    );
+    qc_byte_order!(
+        prop_i32,
+        i32,
+        ::core::i32::MAX as u64,
+        read_i32,
+        write_i32
+    );
+    qc_byte_order!(
+        prop_u48,
+        u64,
+        crate::test::U48_MAX as u64,
+        read_u48,
+        write_u48
+    );
+    qc_byte_order!(
+        prop_i48,
+        i64,
+        crate::test::I48_MAX as u64,
+        read_i48,
+        write_i48
+    );
+    qc_byte_order!(
+        prop_u64,
+        u64,
+        ::core::u64::MAX as u64,
+        read_u64,
+        write_u64
+    );
+    qc_byte_order!(
+        prop_i64,
+        i64,
+        ::core::i64::MAX as u64,
+        read_i64,
+        write_i64
+    );
+    qc_byte_order!(
+        prop_f32,
+        f32,
+        ::core::u64::MAX as u64,
+        read_f32,
+        write_f32
+    );
+    qc_byte_order!(
+        prop_f64,
+        f64,
+        ::core::i64::MAX as u64,
+        read_f64,
+        write_f64
+    );
+
+    qc_byte_order!(prop_u128, Wi128<u128>, 16 + 1, read_u128, write_u128);
+    qc_byte_order!(prop_i128, Wi128<i128>, 16 + 1, read_i128, write_i128);
+
+    qc_byte_order!(
+        prop_uint_1,
+        u64,
+        calc_max!(super::U64_MAX, 1),
+        1,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_2,
+        u64,
+        calc_max!(super::U64_MAX, 2),
+        2,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_3,
+        u64,
+        calc_max!(super::U64_MAX, 3),
+        3,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_4,
+        u64,
+        calc_max!(super::U64_MAX, 4),
+        4,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_5,
+        u64,
+        calc_max!(super::U64_MAX, 5),
+        5,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_6,
+        u64,
+        calc_max!(super::U64_MAX, 6),
+        6,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_7,
+        u64,
+        calc_max!(super::U64_MAX, 7),
+        7,
+        read_uint,
+        write_uint
+    );
+    qc_byte_order!(
+        prop_uint_8,
+        u64,
+        calc_max!(super::U64_MAX, 8),
+        8,
+        read_uint,
+        write_uint
+    );
+
+    qc_byte_order!(
+        prop_uint128_1,
+        Wi128<u128>,
+        1,
+        1,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_2,
+        Wi128<u128>,
+        2,
+        2,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_3,
+        Wi128<u128>,
+        3,
+        3,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_4,
+        Wi128<u128>,
+        4,
+        4,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_5,
+        Wi128<u128>,
+        5,
+        5,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_6,
+        Wi128<u128>,
+        6,
+        6,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_7,
+        Wi128<u128>,
+        7,
+        7,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_8,
+        Wi128<u128>,
+        8,
+        8,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_9,
+        Wi128<u128>,
+        9,
+        9,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_10,
+        Wi128<u128>,
+        10,
+        10,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_11,
+        Wi128<u128>,
+        11,
+        11,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_12,
+        Wi128<u128>,
+        12,
+        12,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_13,
+        Wi128<u128>,
+        13,
+        13,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_14,
+        Wi128<u128>,
+        14,
+        14,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_15,
+        Wi128<u128>,
+        15,
+        15,
+        read_uint128,
+        write_uint128
+    );
+    qc_byte_order!(
+        prop_uint128_16,
+        Wi128<u128>,
+        16,
+        16,
+        read_uint128,
+        write_uint128
+    );
+
+    qc_byte_order!(
+        prop_int_1,
+        i64,
+        calc_max!(super::I64_MAX, 1),
+        1,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_2,
+        i64,
+        calc_max!(super::I64_MAX, 2),
+        2,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_3,
+        i64,
+        calc_max!(super::I64_MAX, 3),
+        3,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_4,
+        i64,
+        calc_max!(super::I64_MAX, 4),
+        4,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_5,
+        i64,
+        calc_max!(super::I64_MAX, 5),
+        5,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_6,
+        i64,
+        calc_max!(super::I64_MAX, 6),
+        6,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_7,
+        i64,
+        calc_max!(super::I64_MAX, 7),
+        7,
+        read_int,
+        write_int
+    );
+    qc_byte_order!(
+        prop_int_8,
+        i64,
+        calc_max!(super::I64_MAX, 8),
+        8,
+        read_int,
+        write_int
+    );
+
+    qc_byte_order!(
+        prop_int128_1,
+        Wi128<i128>,
+        1,
+        1,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_2,
+        Wi128<i128>,
+        2,
+        2,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_3,
+        Wi128<i128>,
+        3,
+        3,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_4,
+        Wi128<i128>,
+        4,
+        4,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_5,
+        Wi128<i128>,
+        5,
+        5,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_6,
+        Wi128<i128>,
+        6,
+        6,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_7,
+        Wi128<i128>,
+        7,
+        7,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_8,
+        Wi128<i128>,
+        8,
+        8,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_9,
+        Wi128<i128>,
+        9,
+        9,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_10,
+        Wi128<i128>,
+        10,
+        10,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_11,
+        Wi128<i128>,
+        11,
+        11,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_12,
+        Wi128<i128>,
+        12,
+        12,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_13,
+        Wi128<i128>,
+        13,
+        13,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_14,
+        Wi128<i128>,
+        14,
+        14,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_15,
+        Wi128<i128>,
+        15,
+        15,
+        read_int128,
+        write_int128
+    );
+    qc_byte_order!(
+        prop_int128_16,
+        Wi128<i128>,
+        16,
+        16,
+        read_int128,
+        write_int128
+    );
+
+    // Test that all of the byte conversion functions panic when given a
+    // buffer that is too small.
+    //
+    // These tests are critical to ensure safety, otherwise we might end up
+    // with a buffer overflow.
+    macro_rules! too_small {
+        ($name:ident, $maximally_small:expr, $zero:expr,
+         $read:ident, $write:ident) => {
+            mod $name {
+                use crate::{
+                    BigEndian, ByteOrder, LittleEndian, NativeEndian,
+                };
+
+                #[test]
+                #[should_panic]
+                fn read_big_endian() {
+                    let buf = [0; $maximally_small];
+                    BigEndian::$read(&buf);
+                }
+
+                #[test]
+                #[should_panic]
+                fn read_little_endian() {
+                    let buf = [0; $maximally_small];
+                    LittleEndian::$read(&buf);
+                }
+
+                #[test]
+                #[should_panic]
+                fn read_native_endian() {
+                    let buf = [0; $maximally_small];
+                    NativeEndian::$read(&buf);
+                }
+
+                #[test]
+                #[should_panic]
+                fn write_big_endian() {
+                    let mut buf = [0; $maximally_small];
+                    BigEndian::$write(&mut buf, $zero);
+                }
+
+                #[test]
+                #[should_panic]
+                fn write_little_endian() {
+                    let mut buf = [0; $maximally_small];
+                    LittleEndian::$write(&mut buf, $zero);
+                }
+
+                #[test]
+                #[should_panic]
+                fn write_native_endian() {
+                    let mut buf = [0; $maximally_small];
+                    NativeEndian::$write(&mut buf, $zero);
+                }
+            }
+        };
+        ($name:ident, $maximally_small:expr, $read:ident) => {
+            mod $name {
+                use crate::{
+                    BigEndian, ByteOrder, LittleEndian, NativeEndian,
+                };
+
+                #[test]
+                #[should_panic]
+                fn read_big_endian() {
+                    let buf = [0; $maximally_small];
+                    BigEndian::$read(&buf, $maximally_small + 1);
+                }
+
+                #[test]
+                #[should_panic]
+                fn read_little_endian() {
+                    let buf = [0; $maximally_small];
+                    LittleEndian::$read(&buf, $maximally_small + 1);
+                }
+
+                #[test]
+                #[should_panic]
+                fn read_native_endian() {
+                    let buf = [0; $maximally_small];
+                    NativeEndian::$read(&buf, $maximally_small + 1);
+                }
+            }
+        };
+    }
+
+    too_small!(small_u16, 1, 0, read_u16, write_u16);
+    too_small!(small_i16, 1, 0, read_i16, write_i16);
+    too_small!(small_u32, 3, 0, read_u32, write_u32);
+    too_small!(small_i32, 3, 0, read_i32, write_i32);
+    too_small!(small_u64, 7, 0, read_u64, write_u64);
+    too_small!(small_i64, 7, 0, read_i64, write_i64);
+    too_small!(small_f32, 3, 0.0, read_f32, write_f32);
+    too_small!(small_f64, 7, 0.0, read_f64, write_f64);
+    too_small!(small_u128, 15, 0, read_u128, write_u128);
+    too_small!(small_i128, 15, 0, read_i128, write_i128);
+
+    too_small!(small_uint_1, 1, read_uint);
+    too_small!(small_uint_2, 2, read_uint);
+    too_small!(small_uint_3, 3, read_uint);
+    too_small!(small_uint_4, 4, read_uint);
+    too_small!(small_uint_5, 5, read_uint);
+    too_small!(small_uint_6, 6, read_uint);
+    too_small!(small_uint_7, 7, read_uint);
+
+    too_small!(small_uint128_1, 1, read_uint128);
+    too_small!(small_uint128_2, 2, read_uint128);
+    too_small!(small_uint128_3, 3, read_uint128);
+    too_small!(small_uint128_4, 4, read_uint128);
+    too_small!(small_uint128_5, 5, read_uint128);
+    too_small!(small_uint128_6, 6, read_uint128);
+    too_small!(small_uint128_7, 7, read_uint128);
+    too_small!(small_uint128_8, 8, read_uint128);
+    too_small!(small_uint128_9, 9, read_uint128);
+    too_small!(small_uint128_10, 10, read_uint128);
+    too_small!(small_uint128_11, 11, read_uint128);
+    too_small!(small_uint128_12, 12, read_uint128);
+    too_small!(small_uint128_13, 13, read_uint128);
+    too_small!(small_uint128_14, 14, read_uint128);
+    too_small!(small_uint128_15, 15, read_uint128);
+
+    too_small!(small_int_1, 1, read_int);
+    too_small!(small_int_2, 2, read_int);
+    too_small!(small_int_3, 3, read_int);
+    too_small!(small_int_4, 4, read_int);
+    too_small!(small_int_5, 5, read_int);
+    too_small!(small_int_6, 6, read_int);
+    too_small!(small_int_7, 7, read_int);
+
+    too_small!(small_int128_1, 1, read_int128);
+    too_small!(small_int128_2, 2, read_int128);
+    too_small!(small_int128_3, 3, read_int128);
+    too_small!(small_int128_4, 4, read_int128);
+    too_small!(small_int128_5, 5, read_int128);
+    too_small!(small_int128_6, 6, read_int128);
+    too_small!(small_int128_7, 7, read_int128);
+    too_small!(small_int128_8, 8, read_int128);
+    too_small!(small_int128_9, 9, read_int128);
+    too_small!(small_int128_10, 10, read_int128);
+    too_small!(small_int128_11, 11, read_int128);
+    too_small!(small_int128_12, 12, read_int128);
+    too_small!(small_int128_13, 13, read_int128);
+    too_small!(small_int128_14, 14, read_int128);
+    too_small!(small_int128_15, 15, read_int128);
+
+    // Test that reading/writing slices enforces the correct lengths.
+    macro_rules! slice_lengths {
+        ($name:ident, $read:ident, $write:ident,
+         $num_bytes:expr, $numbers:expr) => {
+            mod $name {
+                use crate::{
+                    BigEndian, ByteOrder, LittleEndian, NativeEndian,
+                };
+
+                #[test]
+                #[should_panic]
+                fn read_big_endian() {
+                    let bytes = [0; $num_bytes];
+                    let mut numbers = $numbers;
+                    BigEndian::$read(&bytes, &mut numbers);
+                }
+
+                #[test]
+                #[should_panic]
+                fn read_little_endian() {
+                    let bytes = [0; $num_bytes];
+                    let mut numbers = $numbers;
+                    LittleEndian::$read(&bytes, &mut numbers);
+                }
+
+                #[test]
+                #[should_panic]
+                fn read_native_endian() {
+                    let bytes = [0; $num_bytes];
+                    let mut numbers = $numbers;
+                    NativeEndian::$read(&bytes, &mut numbers);
+                }
+
+                #[test]
+                #[should_panic]
+                fn write_big_endian() {
+                    let mut bytes = [0; $num_bytes];
+                    let numbers = $numbers;
+                    BigEndian::$write(&numbers, &mut bytes);
+                }
+
+                #[test]
+                #[should_panic]
+                fn write_little_endian() {
+                    let mut bytes = [0; $num_bytes];
+                    let numbers = $numbers;
+                    LittleEndian::$write(&numbers, &mut bytes);
+                }
+
+                #[test]
+                #[should_panic]
+                fn write_native_endian() {
+                    let mut bytes = [0; $num_bytes];
+                    let numbers = $numbers;
+                    NativeEndian::$write(&numbers, &mut bytes);
+                }
+            }
+        };
+    }
+
+    slice_lengths!(
+        slice_len_too_small_u16,
+        read_u16_into,
+        write_u16_into,
+        3,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_u16,
+        read_u16_into,
+        write_u16_into,
+        5,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_small_i16,
+        read_i16_into,
+        write_i16_into,
+        3,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_i16,
+        read_i16_into,
+        write_i16_into,
+        5,
+        [0, 0]
+    );
+
+    slice_lengths!(
+        slice_len_too_small_u32,
+        read_u32_into,
+        write_u32_into,
+        7,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_u32,
+        read_u32_into,
+        write_u32_into,
+        9,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_small_i32,
+        read_i32_into,
+        write_i32_into,
+        7,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_i32,
+        read_i32_into,
+        write_i32_into,
+        9,
+        [0, 0]
+    );
+
+    slice_lengths!(
+        slice_len_too_small_u64,
+        read_u64_into,
+        write_u64_into,
+        15,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_u64,
+        read_u64_into,
+        write_u64_into,
+        17,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_small_i64,
+        read_i64_into,
+        write_i64_into,
+        15,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_i64,
+        read_i64_into,
+        write_i64_into,
+        17,
+        [0, 0]
+    );
+
+    slice_lengths!(
+        slice_len_too_small_u128,
+        read_u128_into,
+        write_u128_into,
+        31,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_u128,
+        read_u128_into,
+        write_u128_into,
+        33,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_small_i128,
+        read_i128_into,
+        write_i128_into,
+        31,
+        [0, 0]
+    );
+    slice_lengths!(
+        slice_len_too_big_i128,
+        read_i128_into,
+        write_i128_into,
+        33,
+        [0, 0]
+    );
+
+    #[test]
+    fn uint_bigger_buffer() {
+        use crate::{ByteOrder, LittleEndian};
+        let n = LittleEndian::read_uint(&[1, 2, 3, 4, 5, 6, 7, 8], 5);
+        assert_eq!(n, 0x05_0403_0201);
+    }
+
+    #[test]
+    fn regression173_array_impl() {
+        use crate::{BigEndian, ByteOrder, LittleEndian};
+
+        let xs = [0; 100];
+
+        let x = BigEndian::read_u16(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_u32(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_u64(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_u128(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_i16(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_i32(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_i64(&xs);
+        assert_eq!(x, 0);
+        let x = BigEndian::read_i128(&xs);
+        assert_eq!(x, 0);
+
+        let x = LittleEndian::read_u16(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_u32(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_u64(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_u128(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_i16(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_i32(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_i64(&xs);
+        assert_eq!(x, 0);
+        let x = LittleEndian::read_i128(&xs);
+        assert_eq!(x, 0);
+    }
+}
+
+#[cfg(test)]
+#[cfg(feature = "std")]
+mod stdtests {
+    extern crate quickcheck;
+    extern crate rand;
+
+    use self::quickcheck::{QuickCheck, StdGen, Testable};
+    use self::rand::thread_rng;
+
+    fn qc_unsized<A: Testable>(f: A) {
+        QuickCheck::new()
+            .gen(StdGen::new(thread_rng(), 16))
+            .tests(1_00)
+            .max_tests(10_000)
+            .quickcheck(f);
+    }
+
+    macro_rules! calc_max {
+        ($max:expr, $bytes:expr) => {
+            ($max - 1) >> (8 * (8 - $bytes))
+        };
+    }
+
+    macro_rules! qc_bytes_ext {
+        ($name:ident, $ty_int:ty, $max:expr,
+         $bytes:expr, $read:ident, $write:ident) => {
+            mod $name {
+                #[allow(unused_imports)]
+                use crate::test::{qc_sized, Wi128};
+                use crate::{
+                    BigEndian, LittleEndian, NativeEndian, ReadBytesExt,
+                    WriteBytesExt,
+                };
+                use std::io::Cursor;
+
+                #[test]
+                fn big_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut wtr = vec![];
+                        wtr.$write::<BigEndian>(n.clone()).unwrap();
+                        let offset = wtr.len() - $bytes;
+                        let mut rdr = Cursor::new(&mut wtr[offset..]);
+                        n == rdr.$read::<BigEndian>($bytes).unwrap()
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max);
+                }
+
+                #[test]
+                fn little_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut wtr = vec![];
+                        wtr.$write::<LittleEndian>(n.clone()).unwrap();
+                        let mut rdr = Cursor::new(wtr);
+                        n == rdr.$read::<LittleEndian>($bytes).unwrap()
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max);
+                }
+
+                #[test]
+                fn native_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut wtr = vec![];
+                        wtr.$write::<NativeEndian>(n.clone()).unwrap();
+                        let offset = if cfg!(target_endian = "big") {
+                            wtr.len() - $bytes
+                        } else {
+                            0
+                        };
+                        let mut rdr = Cursor::new(&mut wtr[offset..]);
+                        n == rdr.$read::<NativeEndian>($bytes).unwrap()
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max);
+                }
+            }
+        };
+        ($name:ident, $ty_int:ty, $max:expr, $read:ident, $write:ident) => {
+            mod $name {
+                #[allow(unused_imports)]
+                use crate::test::{qc_sized, Wi128};
+                use crate::{
+                    BigEndian, LittleEndian, NativeEndian, ReadBytesExt,
+                    WriteBytesExt,
+                };
+                use std::io::Cursor;
+
+                #[test]
+                fn big_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut wtr = vec![];
+                        wtr.$write::<BigEndian>(n.clone()).unwrap();
+                        let mut rdr = Cursor::new(wtr);
+                        n == rdr.$read::<BigEndian>().unwrap()
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max - 1);
+                }
+
+                #[test]
+                fn little_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut wtr = vec![];
+                        wtr.$write::<LittleEndian>(n.clone()).unwrap();
+                        let mut rdr = Cursor::new(wtr);
+                        n == rdr.$read::<LittleEndian>().unwrap()
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max - 1);
+                }
+
+                #[test]
+                fn native_endian() {
+                    fn prop(n: $ty_int) -> bool {
+                        let mut wtr = vec![];
+                        wtr.$write::<NativeEndian>(n.clone()).unwrap();
+                        let mut rdr = Cursor::new(wtr);
+                        n == rdr.$read::<NativeEndian>().unwrap()
+                    }
+                    qc_sized(prop as fn($ty_int) -> bool, $max - 1);
+                }
+            }
+        };
+    }
+
+    qc_bytes_ext!(
+        prop_ext_u16,
+        u16,
+        ::std::u16::MAX as u64,
+        read_u16,
+        write_u16
+    );
+    qc_bytes_ext!(
+        prop_ext_i16,
+        i16,
+        ::std::i16::MAX as u64,
+        read_i16,
+        write_i16
+    );
+    qc_bytes_ext!(
+        prop_ext_u32,
+        u32,
+        ::std::u32::MAX as u64,
+        read_u32,
+        write_u32
+    );
+    qc_bytes_ext!(
+        prop_ext_i32,
+        i32,
+        ::std::i32::MAX as u64,
+        read_i32,
+        write_i32
+    );
+    qc_bytes_ext!(
+        prop_ext_u64,
+        u64,
+        ::std::u64::MAX as u64,
+        read_u64,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_i64,
+        i64,
+        ::std::i64::MAX as u64,
+        read_i64,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_f32,
+        f32,
+        ::std::u64::MAX as u64,
+        read_f32,
+        write_f32
+    );
+    qc_bytes_ext!(
+        prop_ext_f64,
+        f64,
+        ::std::i64::MAX as u64,
+        read_f64,
+        write_f64
+    );
+
+    qc_bytes_ext!(prop_ext_u128, Wi128<u128>, 16 + 1, read_u128, write_u128);
+    qc_bytes_ext!(prop_ext_i128, Wi128<i128>, 16 + 1, read_i128, write_i128);
+
+    qc_bytes_ext!(
+        prop_ext_uint_1,
+        u64,
+        calc_max!(crate::test::U64_MAX, 1),
+        1,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_2,
+        u64,
+        calc_max!(crate::test::U64_MAX, 2),
+        2,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_3,
+        u64,
+        calc_max!(crate::test::U64_MAX, 3),
+        3,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_4,
+        u64,
+        calc_max!(crate::test::U64_MAX, 4),
+        4,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_5,
+        u64,
+        calc_max!(crate::test::U64_MAX, 5),
+        5,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_6,
+        u64,
+        calc_max!(crate::test::U64_MAX, 6),
+        6,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_7,
+        u64,
+        calc_max!(crate::test::U64_MAX, 7),
+        7,
+        read_uint,
+        write_u64
+    );
+    qc_bytes_ext!(
+        prop_ext_uint_8,
+        u64,
+        calc_max!(crate::test::U64_MAX, 8),
+        8,
+        read_uint,
+        write_u64
+    );
+
+    qc_bytes_ext!(
+        prop_ext_uint128_1,
+        Wi128<u128>,
+        1,
+        1,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_2,
+        Wi128<u128>,
+        2,
+        2,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_3,
+        Wi128<u128>,
+        3,
+        3,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_4,
+        Wi128<u128>,
+        4,
+        4,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_5,
+        Wi128<u128>,
+        5,
+        5,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_6,
+        Wi128<u128>,
+        6,
+        6,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_7,
+        Wi128<u128>,
+        7,
+        7,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_8,
+        Wi128<u128>,
+        8,
+        8,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_9,
+        Wi128<u128>,
+        9,
+        9,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_10,
+        Wi128<u128>,
+        10,
+        10,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_11,
+        Wi128<u128>,
+        11,
+        11,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_12,
+        Wi128<u128>,
+        12,
+        12,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_13,
+        Wi128<u128>,
+        13,
+        13,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_14,
+        Wi128<u128>,
+        14,
+        14,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_15,
+        Wi128<u128>,
+        15,
+        15,
+        read_uint128,
+        write_u128
+    );
+    qc_bytes_ext!(
+        prop_ext_uint128_16,
+        Wi128<u128>,
+        16,
+        16,
+        read_uint128,
+        write_u128
+    );
+
+    qc_bytes_ext!(
+        prop_ext_int_1,
+        i64,
+        calc_max!(crate::test::I64_MAX, 1),
+        1,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_2,
+        i64,
+        calc_max!(crate::test::I64_MAX, 2),
+        2,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_3,
+        i64,
+        calc_max!(crate::test::I64_MAX, 3),
+        3,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_4,
+        i64,
+        calc_max!(crate::test::I64_MAX, 4),
+        4,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_5,
+        i64,
+        calc_max!(crate::test::I64_MAX, 5),
+        5,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_6,
+        i64,
+        calc_max!(crate::test::I64_MAX, 6),
+        6,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_7,
+        i64,
+        calc_max!(crate::test::I64_MAX, 1),
+        7,
+        read_int,
+        write_i64
+    );
+    qc_bytes_ext!(
+        prop_ext_int_8,
+        i64,
+        calc_max!(crate::test::I64_MAX, 8),
+        8,
+        read_int,
+        write_i64
+    );
+
+    qc_bytes_ext!(
+        prop_ext_int128_1,
+        Wi128<i128>,
+        1,
+        1,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_2,
+        Wi128<i128>,
+        2,
+        2,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_3,
+        Wi128<i128>,
+        3,
+        3,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_4,
+        Wi128<i128>,
+        4,
+        4,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_5,
+        Wi128<i128>,
+        5,
+        5,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_6,
+        Wi128<i128>,
+        6,
+        6,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_7,
+        Wi128<i128>,
+        7,
+        7,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_8,
+        Wi128<i128>,
+        8,
+        8,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_9,
+        Wi128<i128>,
+        9,
+        9,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_10,
+        Wi128<i128>,
+        10,
+        10,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_11,
+        Wi128<i128>,
+        11,
+        11,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_12,
+        Wi128<i128>,
+        12,
+        12,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_13,
+        Wi128<i128>,
+        13,
+        13,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_14,
+        Wi128<i128>,
+        14,
+        14,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_15,
+        Wi128<i128>,
+        15,
+        15,
+        read_int128,
+        write_i128
+    );
+    qc_bytes_ext!(
+        prop_ext_int128_16,
+        Wi128<i128>,
+        16,
+        16,
+        read_int128,
+        write_i128
+    );
+
+    // Test slice serialization/deserialization.
+    macro_rules! qc_slice {
+        ($name:ident, $ty_int:ty, $read:ident, $write:ident, $zero:expr) => {
+            mod $name {
+                use super::qc_unsized;
+                #[allow(unused_imports)]
+                use crate::test::Wi128;
+                use crate::{
+                    BigEndian, ByteOrder, LittleEndian, NativeEndian,
+                };
+                use core::mem::size_of;
+
+                #[test]
+                fn big_endian() {
+                    #[allow(unused_unsafe)]
+                    fn prop(numbers: Vec<$ty_int>) -> bool {
+                        let numbers: Vec<_> =
+                            numbers.into_iter().map(|x| x.clone()).collect();
+                        let num_bytes = size_of::<$ty_int>() * numbers.len();
+                        let mut bytes = vec![0; num_bytes];
+
+                        BigEndian::$write(&numbers, &mut bytes);
+
+                        let mut got = vec![$zero; numbers.len()];
+                        unsafe {
+                            BigEndian::$read(&bytes, &mut got);
+                        }
+
+                        numbers == got
+                    }
+                    qc_unsized(prop as fn(_) -> bool);
+                }
+
+                #[test]
+                fn little_endian() {
+                    #[allow(unused_unsafe)]
+                    fn prop(numbers: Vec<$ty_int>) -> bool {
+                        let numbers: Vec<_> =
+                            numbers.into_iter().map(|x| x.clone()).collect();
+                        let num_bytes = size_of::<$ty_int>() * numbers.len();
+                        let mut bytes = vec![0; num_bytes];
+
+                        LittleEndian::$write(&numbers, &mut bytes);
+
+                        let mut got = vec![$zero; numbers.len()];
+                        unsafe {
+                            LittleEndian::$read(&bytes, &mut got);
+                        }
+
+                        numbers == got
+                    }
+                    qc_unsized(prop as fn(_) -> bool);
+                }
+
+                #[test]
+                fn native_endian() {
+                    #[allow(unused_unsafe)]
+                    fn prop(numbers: Vec<$ty_int>) -> bool {
+                        let numbers: Vec<_> =
+                            numbers.into_iter().map(|x| x.clone()).collect();
+                        let num_bytes = size_of::<$ty_int>() * numbers.len();
+                        let mut bytes = vec![0; num_bytes];
+
+                        NativeEndian::$write(&numbers, &mut bytes);
+
+                        let mut got = vec![$zero; numbers.len()];
+                        unsafe {
+                            NativeEndian::$read(&bytes, &mut got);
+                        }
+
+                        numbers == got
+                    }
+                    qc_unsized(prop as fn(_) -> bool);
+                }
+            }
+        };
+    }
+
+    qc_slice!(prop_slice_u16, u16, read_u16_into, write_u16_into, 0);
+    qc_slice!(prop_slice_i16, i16, read_i16_into, write_i16_into, 0);
+    qc_slice!(prop_slice_u32, u32, read_u32_into, write_u32_into, 0);
+    qc_slice!(prop_slice_i32, i32, read_i32_into, write_i32_into, 0);
+    qc_slice!(prop_slice_u64, u64, read_u64_into, write_u64_into, 0);
+    qc_slice!(prop_slice_i64, i64, read_i64_into, write_i64_into, 0);
+    qc_slice!(
+        prop_slice_u128,
+        Wi128<u128>,
+        read_u128_into,
+        write_u128_into,
+        0
+    );
+    qc_slice!(
+        prop_slice_i128,
+        Wi128<i128>,
+        read_i128_into,
+        write_i128_into,
+        0
+    );
+
+    qc_slice!(prop_slice_f32, f32, read_f32_into, write_f32_into, 0.0);
+    qc_slice!(prop_slice_f64, f64, read_f64_into, write_f64_into, 0.0);
+}
+
\ No newline at end of file diff --git a/docs/doc/src/critical_section/lib.rs.html b/docs/doc/src/critical_section/lib.rs.html new file mode 100644 index 0000000..8026720 --- /dev/null +++ b/docs/doc/src/critical_section/lib.rs.html @@ -0,0 +1,579 @@ +lib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+
#![cfg_attr(not(feature = "std"), no_std)]
+#![doc = include_str!("../README.md")]
+
+mod mutex;
+#[cfg(feature = "std")]
+mod std;
+
+use core::marker::PhantomData;
+
+pub use self::mutex::Mutex;
+
+/// Critical section token.
+///
+/// An instance of this type indicates that the current thread is executing code within a critical
+/// section.
+#[derive(Clone, Copy, Debug)]
+pub struct CriticalSection<'cs> {
+    _private: PhantomData<&'cs ()>,
+}
+
+impl<'cs> CriticalSection<'cs> {
+    /// Creates a critical section token.
+    ///
+    /// This method is meant to be used to create safe abstractions rather than being directly used
+    /// in applications.
+    ///
+    /// # Safety
+    ///
+    /// This must only be called when the current thread is in a critical section. The caller must
+    /// ensure that the returned instance will not live beyond the end of the critical section.
+    ///
+    /// The caller must use adequate fences to prevent the compiler from moving the
+    /// instructions inside the critical section to the outside of it. Sequentially consistent fences are
+    /// suggested immediately after entry and immediately before exit from the critical section.
+    ///
+    /// Note that the lifetime `'cs` of the returned instance is unconstrained. User code must not
+    /// be able to influence the lifetime picked for this type, since that might cause it to be
+    /// inferred to `'static`.
+    #[inline(always)]
+    pub unsafe fn new() -> Self {
+        CriticalSection {
+            _private: PhantomData,
+        }
+    }
+}
+
+#[cfg(any(
+    all(feature = "restore-state-none", feature = "restore-state-bool"),
+    all(feature = "restore-state-none", feature = "restore-state-u8"),
+    all(feature = "restore-state-none", feature = "restore-state-u16"),
+    all(feature = "restore-state-none", feature = "restore-state-u32"),
+    all(feature = "restore-state-none", feature = "restore-state-u64"),
+    all(feature = "restore-state-bool", feature = "restore-state-u8"),
+    all(feature = "restore-state-bool", feature = "restore-state-u16"),
+    all(feature = "restore-state-bool", feature = "restore-state-u32"),
+    all(feature = "restore-state-bool", feature = "restore-state-u64"),
+    all(feature = "restore-state-u8", feature = "restore-state-u16"),
+    all(feature = "restore-state-u8", feature = "restore-state-u32"),
+    all(feature = "restore-state-u8", feature = "restore-state-u64"),
+    all(feature = "restore-state-u16", feature = "restore-state-u32"),
+    all(feature = "restore-state-u16", feature = "restore-state-u64"),
+    all(feature = "restore-state-u32", feature = "restore-state-u64"),
+))]
+compile_error!("You must set at most one of these Cargo features: restore-state-none, restore-state-bool, restore-state-u8, restore-state-u16, restore-state-u32, restore-state-u64");
+
+#[cfg(not(any(
+    feature = "restore-state-bool",
+    feature = "restore-state-u8",
+    feature = "restore-state-u16",
+    feature = "restore-state-u32",
+    feature = "restore-state-u64"
+)))]
+type RawRestoreStateInner = ();
+
+#[cfg(feature = "restore-state-bool")]
+type RawRestoreStateInner = bool;
+
+#[cfg(feature = "restore-state-u8")]
+type RawRestoreStateInner = u8;
+
+#[cfg(feature = "restore-state-u16")]
+type RawRestoreStateInner = u16;
+
+#[cfg(feature = "restore-state-u32")]
+type RawRestoreStateInner = u32;
+
+#[cfg(feature = "restore-state-u64")]
+type RawRestoreStateInner = u64;
+
+// We have RawRestoreStateInner and RawRestoreState so that we don't have to copypaste the docs 5 times.
+// In the docs this shows as `pub type RawRestoreState = u8` or whatever the selected type is, because
+// the "inner" type alias is private.
+
+/// Raw, transparent "restore state".
+///
+/// This type changes based on which Cargo feature is selected, out of
+/// - `restore-state-none` (default, makes the type be `()`)
+/// - `restore-state-bool`
+/// - `restore-state-u8`
+/// - `restore-state-u16`
+/// - `restore-state-u32`
+/// - `restore-state-u64`
+///
+/// See [`RestoreState`].
+///
+/// User code uses [`RestoreState`] opaquely, critical section implementations
+/// use [`RawRestoreState`] so that they can use the inner value.
+pub type RawRestoreState = RawRestoreStateInner;
+
+/// Opaque "restore state".
+///
+/// Implementations use this to "carry over" information between acquiring and releasing
+/// a critical section. For example, when nesting two critical sections of an
+/// implementation that disables interrupts globally, acquiring the inner one won't disable
+/// the interrupts since they're already disabled. The impl would use the restore state to "tell"
+/// the corresponding release that it does *not* have to reenable interrupts yet, only the
+/// outer release should do so.
+///
+/// User code uses [`RestoreState`] opaquely, critical section implementations
+/// use [`RawRestoreState`] so that they can use the inner value.
+#[derive(Clone, Copy, Debug)]
+pub struct RestoreState(RawRestoreState);
+
+impl RestoreState {
+    /// Create an invalid, dummy  `RestoreState`.
+    ///
+    /// This can be useful to avoid `Option` when storing a `RestoreState` in a
+    /// struct field, or a `static`.
+    ///
+    /// Note that due to the safety contract of [`acquire`]/[`release`], you must not pass
+    /// a `RestoreState` obtained from this method to [`release`].
+    pub const fn invalid() -> Self {
+        #[cfg(not(any(
+            feature = "restore-state-bool",
+            feature = "restore-state-u8",
+            feature = "restore-state-u16",
+            feature = "restore-state-u32",
+            feature = "restore-state-u64"
+        )))]
+        return Self(());
+
+        #[cfg(feature = "restore-state-bool")]
+        return Self(false);
+
+        #[cfg(feature = "restore-state-u8")]
+        return Self(0);
+
+        #[cfg(feature = "restore-state-u16")]
+        return Self(0);
+
+        #[cfg(feature = "restore-state-u32")]
+        return Self(0);
+
+        #[cfg(feature = "restore-state-u64")]
+        return Self(0);
+    }
+}
+
+/// Acquire a critical section in the current thread.
+///
+/// This function is extremely low level. Strongly prefer using [`with`] instead.
+///
+/// Nesting critical sections is allowed. The inner critical sections
+/// are mostly no-ops since they're already protected by the outer one.
+///
+/// # Safety
+///
+/// - Each `acquire` call must be paired with exactly one `release` call in the same thread.
+/// - `acquire` returns a "restore state" that you must pass to the corresponding `release` call.
+/// - `acquire`/`release` pairs must be "properly nested", ie it's not OK to do `a=acquire(); b=acquire(); release(a); release(b);`.
+/// - It is UB to call `release` if the critical section is not acquired in the current thread.
+/// - It is UB to call `release` with a "restore state" that does not come from the corresponding `acquire` call.
+/// - It must provide ordering guarantees at least equivalent to a [`core::sync::atomic::Ordering::Acquire`]
+///   on a memory location shared by all critical sections, on which the `release` call will do a
+///   [`core::sync::atomic::Ordering::Release`] operation.
+#[inline(always)]
+pub unsafe fn acquire() -> RestoreState {
+    extern "Rust" {
+        fn _critical_section_1_0_acquire() -> RawRestoreState;
+    }
+
+    #[allow(clippy::unit_arg)]
+    RestoreState(_critical_section_1_0_acquire())
+}
+
+/// Release the critical section.
+///
+/// This function is extremely low level. Strongly prefer using [`with`] instead.
+///
+/// # Safety
+///
+/// See [`acquire`] for the safety contract description.
+#[inline(always)]
+pub unsafe fn release(restore_state: RestoreState) {
+    extern "Rust" {
+        fn _critical_section_1_0_release(restore_state: RawRestoreState);
+    }
+
+    #[allow(clippy::unit_arg)]
+    _critical_section_1_0_release(restore_state.0)
+}
+
+/// Execute closure `f` in a critical section.
+///
+/// Nesting critical sections is allowed. The inner critical sections
+/// are mostly no-ops since they're already protected by the outer one.
+///
+/// # Panics
+///
+/// This function panics if the given closure `f` panics. In this case
+/// the critical section is released before unwinding.
+#[inline]
+pub fn with<R>(f: impl FnOnce(CriticalSection) -> R) -> R {
+    // Helper for making sure `release` is called even if `f` panics.
+    struct Guard {
+        state: RestoreState,
+    }
+
+    impl Drop for Guard {
+        #[inline(always)]
+        fn drop(&mut self) {
+            unsafe { release(self.state) }
+        }
+    }
+
+    let state = unsafe { acquire() };
+    let _guard = Guard { state };
+
+    unsafe { f(CriticalSection::new()) }
+}
+
+/// Methods required for a critical section implementation.
+///
+/// This trait is not intended to be used except when implementing a critical section.
+///
+/// # Safety
+///
+/// Implementations must uphold the contract specified in [`crate::acquire`] and [`crate::release`].
+pub unsafe trait Impl {
+    /// Acquire the critical section.
+    ///
+    /// # Safety
+    ///
+    /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`].
+    unsafe fn acquire() -> RawRestoreState;
+
+    /// Release the critical section.
+    ///
+    /// # Safety
+    ///
+    /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`].
+    unsafe fn release(restore_state: RawRestoreState);
+}
+
+/// Set the critical section implementation.
+///
+/// # Example
+///
+/// ```
+/// # #[cfg(not(feature = "std"))] // needed for `cargo test --features std`
+/// # mod no_std {
+/// use critical_section::RawRestoreState;
+///
+/// struct MyCriticalSection;
+/// critical_section::set_impl!(MyCriticalSection);
+///
+/// unsafe impl critical_section::Impl for MyCriticalSection {
+///     unsafe fn acquire() -> RawRestoreState {
+///         // ...
+///     }
+///
+///     unsafe fn release(restore_state: RawRestoreState) {
+///         // ...
+///     }
+/// }
+/// # }
+#[macro_export]
+macro_rules! set_impl {
+    ($t: ty) => {
+        #[no_mangle]
+        unsafe fn _critical_section_1_0_acquire() -> $crate::RawRestoreState {
+            <$t as $crate::Impl>::acquire()
+        }
+        #[no_mangle]
+        unsafe fn _critical_section_1_0_release(restore_state: $crate::RawRestoreState) {
+            <$t as $crate::Impl>::release(restore_state)
+        }
+    };
+}
+
\ No newline at end of file diff --git a/docs/doc/src/critical_section/mutex.rs.html b/docs/doc/src/critical_section/mutex.rs.html new file mode 100644 index 0000000..d17a8f7 --- /dev/null +++ b/docs/doc/src/critical_section/mutex.rs.html @@ -0,0 +1,401 @@ +mutex.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+
use super::CriticalSection;
+use core::cell::{Ref, RefCell, RefMut, UnsafeCell};
+
+/// A mutex based on critical sections.
+///
+/// # Example
+///
+/// ```no_run
+/// # use critical_section::Mutex;
+/// # use std::cell::Cell;
+///
+/// static FOO: Mutex<Cell<i32>> = Mutex::new(Cell::new(42));
+///
+/// fn main() {
+///     critical_section::with(|cs| {
+///         FOO.borrow(cs).set(43);
+///     });
+/// }
+///
+/// fn interrupt_handler() {
+///     let _x = critical_section::with(|cs| FOO.borrow(cs).get());
+/// }
+/// ```
+///
+///
+/// # Design
+///
+/// [`std::sync::Mutex`] has two purposes. It converts types that are [`Send`]
+/// but not [`Sync`] into types that are both; and it provides
+/// [interior mutability]. `critical_section::Mutex`, on the other hand, only adds
+/// `Sync`. It does *not* provide interior mutability.
+///
+/// This was a conscious design choice. It is possible to create multiple
+/// [`CriticalSection`] tokens, either by nesting critical sections or `Copy`ing
+/// an existing token. As a result, it would not be sound for [`Mutex::borrow`]
+/// to return `&mut T`, because there would be nothing to prevent calling
+/// `borrow` multiple times to create aliased `&mut T` references.
+///
+/// The solution is to include a runtime check to ensure that each resource is
+/// borrowed only once. This is what `std::sync::Mutex` does. However, this is
+/// a runtime cost that may not be required in all circumstances. For instance,
+/// `Mutex<Cell<T>>` never needs to create `&mut T` or equivalent.
+///
+/// If `&mut T` is needed, the simplest solution is to use `Mutex<RefCell<T>>`,
+/// which is the closest analogy to `std::sync::Mutex`. [`RefCell`] inserts the
+/// exact runtime check necessary to guarantee that the `&mut T` reference is
+/// unique.
+///
+/// To reduce verbosity when using `Mutex<RefCell<T>>`, we reimplement some of
+/// `RefCell`'s methods on it directly.
+///
+/// ```no_run
+/// # use critical_section::Mutex;
+/// # use std::cell::RefCell;
+///
+/// static FOO: Mutex<RefCell<i32>> = Mutex::new(RefCell::new(42));
+///
+/// fn main() {
+///     critical_section::with(|cs| {
+///         // Instead of calling this
+///         let _ = FOO.borrow(cs).take();
+///         // Call this
+///         let _ = FOO.take(cs);
+///         // `RefCell::borrow` and `RefCell::borrow_mut` are renamed to
+///         // `borrow_ref` and `borrow_ref_mut` to avoid name collisions
+///         let _: &mut i32 = &mut *FOO.borrow_ref_mut(cs);
+///     })
+/// }
+/// ```
+///
+/// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
+/// [interior mutability]: https://doc.rust-lang.org/reference/interior-mutability.html
+#[derive(Debug)]
+pub struct Mutex<T> {
+    inner: UnsafeCell<T>,
+}
+
+impl<T> Mutex<T> {
+    /// Creates a new mutex.
+    #[inline]
+    pub const fn new(value: T) -> Self {
+        Mutex {
+            inner: UnsafeCell::new(value),
+        }
+    }
+
+    /// Gets a mutable reference to the contained value when the mutex is already uniquely borrowed.
+    ///
+    /// This does not require locking or a critical section since it takes `&mut self`, which
+    /// guarantees unique ownership already. Care must be taken when using this method to
+    /// **unsafely** access `static mut` variables, appropriate fences must be used to prevent
+    /// unwanted optimizations.
+    #[inline]
+    pub fn get_mut(&mut self) -> &mut T {
+        unsafe { &mut *self.inner.get() }
+    }
+
+    /// Unwraps the contained value, consuming the mutex.
+    #[inline]
+    pub fn into_inner(self) -> T {
+        self.inner.into_inner()
+    }
+
+    /// Borrows the data for the duration of the critical section.
+    #[inline]
+    pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T {
+        unsafe { &*self.inner.get() }
+    }
+}
+
+impl<T> Mutex<RefCell<T>> {
+    /// Borrow the data and call [`RefCell::replace`]
+    ///
+    /// This is equivalent to `self.borrow(cs).replace(t)`
+    ///
+    /// # Panics
+    ///
+    /// This call could panic. See the documentation for [`RefCell::replace`]
+    /// for more details.
+    #[inline]
+    #[track_caller]
+    pub fn replace<'cs>(&'cs self, cs: CriticalSection<'cs>, t: T) -> T {
+        self.borrow(cs).replace(t)
+    }
+
+    /// Borrow the data and call [`RefCell::replace_with`]
+    ///
+    /// This is equivalent to `self.borrow(cs).replace_with(f)`
+    ///
+    /// # Panics
+    ///
+    /// This call could panic. See the documentation for
+    /// [`RefCell::replace_with`] for more details.
+    #[inline]
+    #[track_caller]
+    pub fn replace_with<'cs, F>(&'cs self, cs: CriticalSection<'cs>, f: F) -> T
+    where
+        F: FnOnce(&mut T) -> T,
+    {
+        self.borrow(cs).replace_with(f)
+    }
+
+    /// Borrow the data and call [`RefCell::borrow`]
+    ///
+    /// This is equivalent to `self.borrow(cs).borrow()`
+    ///
+    /// # Panics
+    ///
+    /// This call could panic. See the documentation for [`RefCell::borrow`]
+    /// for more details.
+    #[inline]
+    #[track_caller]
+    pub fn borrow_ref<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, T> {
+        self.borrow(cs).borrow()
+    }
+
+    /// Borrow the data and call [`RefCell::borrow_mut`]
+    ///
+    /// This is equivalent to `self.borrow(cs).borrow_mut()`
+    ///
+    /// # Panics
+    ///
+    /// This call could panic. See the documentation for [`RefCell::borrow_mut`]
+    /// for more details.
+    #[inline]
+    #[track_caller]
+    pub fn borrow_ref_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, T> {
+        self.borrow(cs).borrow_mut()
+    }
+}
+
+impl<T: Default> Mutex<RefCell<T>> {
+    /// Borrow the data and call [`RefCell::take`]
+    ///
+    /// This is equivalent to `self.borrow(cs).take()`
+    ///
+    /// # Panics
+    ///
+    /// This call could panic. See the documentation for [`RefCell::take`]
+    /// for more details.
+    #[inline]
+    #[track_caller]
+    pub fn take<'cs>(&'cs self, cs: CriticalSection<'cs>) -> T {
+        self.borrow(cs).take()
+    }
+}
+
+// NOTE A `Mutex` can be used as a channel so the protected data must be `Send`
+// to prevent sending non-Sendable stuff (e.g. access tokens) across different
+// threads.
+unsafe impl<T> Sync for Mutex<T> where T: Send {}
+
+/// ``` compile_fail
+/// fn bad(cs: critical_section::CriticalSection) -> &u32 {
+///     let x = critical_section::Mutex::new(42u32);
+///     x.borrow(cs)
+/// }
+/// ```
+#[cfg(doctest)]
+const BorrowMustNotOutliveMutexTest: () = ();
+
\ No newline at end of file diff --git a/docs/doc/src/hash32/fnv.rs.html b/docs/doc/src/hash32/fnv.rs.html new file mode 100644 index 0000000..58e7f9b --- /dev/null +++ b/docs/doc/src/hash32/fnv.rs.html @@ -0,0 +1,57 @@ +fnv.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+
const BASIS: u32 = 0x811c9dc5;
+const PRIME: u32 = 0x1000193;
+
+/// 32-bit Fowler-Noll-Vo hasher
+pub struct Hasher {
+    state: u32,
+}
+
+impl Default for Hasher {
+    fn default() -> Self {
+        Hasher { state: BASIS }
+    }
+}
+
+impl ::Hasher for Hasher {
+    #[inline]
+    fn finish(&self) -> u32 {
+        self.state
+    }
+
+    #[inline]
+    fn write(&mut self, bytes: &[u8]) {
+        for byte in bytes {
+            self.state ^= u32::from(*byte);
+            self.state = self.state.wrapping_mul(PRIME);
+        }
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/hash32/lib.rs.html b/docs/doc/src/hash32/lib.rs.html new file mode 100644 index 0000000..c4f677a --- /dev/null +++ b/docs/doc/src/hash32/lib.rs.html @@ -0,0 +1,727 @@ +lib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+
//! 32-bit hashing machinery
+//!
+//! # Why?
+//!
+//! Because 32-bit architectures are a thing (e.g. ARM Cortex-M) and you don't want your hashing
+//! function to pull in a bunch of slow 64-bit compiler intrinsics (software implementations of
+//! 64-bit operations).
+//!
+//! # Relationship to `core::hash`
+//!
+//! This crate exposes the same interfaces you'll find in [`core::hash`]: `Hash`, `Hasher`,
+//! `BuildHasher` and `BuildHasherDefault`. The main difference is that `hash32::Hasher::finish`
+//! returns a `u32` instead of `u64`, and the contract of `hash32::Hasher` forbids the implementer
+//! from performing 64-bit (or 128-bit) operations while computing the hash.
+//!
+//! [`core::hash`]: https://doc.rust-lang.org/std/hash/index.html
+//!
+//! # `#[derive(Hash32)]`
+//!
+//! The easiest way to implement `hash32::Hash` for a `struct` is to use the `#[derive(Hash32)]`.
+//!
+//! Note that you need to *explicitly* depend on both `hash32` *and* `hash32_derive`; both crates
+//! must appear in your `Cargo.toml`.
+//!
+//! ``` ignore
+//! use hash32_derive::Hash32;
+//!
+//! #[derive(Hash32)]
+//! struct Ipv4Addr([u8; 4]);
+//!
+//! # fn main() {}
+//!
+//! ```
+//! # Hashers
+//!
+//! This crate provides implementations of the following 32-bit hashing algorithms:
+//!
+//! - [Fowler-Noll-Vo](struct.FnvHasher.html)
+//! - [MurmurHash3](struct.Murmur3Hasher.html)
+//!
+//! # MSRV
+//!
+//! This crate is guaranteed to compile on latest stable Rust. It *might* compile on older
+//! versions but that may change in any new patch release.
+//!
+//! # Future
+//!
+//! In the future we'd like to deprecate this crate in favor of making `core::hash::Hasher` generic
+//! over the size of the computed hash. Below is shown the planned change (but it doesn't work due
+//! to limitations in the `associated_type_defaults` feature):
+//!
+//! ``` ignore
+//! #![feature(associated_type_defaults)]
+//!
+//! trait Hasher {
+//!     type Hash = u64; // default type for backwards compatibility
+//!
+//!     fn finish(&self) -> Self::Hash; // changed
+//!     fn write(&mut self, bytes: &[u8]);
+//! }
+//! ```
+//!
+//! With this change a single `#[derive(Hash)]` would enough to make a type hashable with 32-bit and
+//! 64-bit hashers.
+
+#![deny(missing_docs)]
+#![deny(warnings)]
+#![no_std]
+
+extern crate byteorder;
+
+use core::marker::PhantomData;
+use core::{mem, slice, fmt};
+
+pub use fnv::Hasher as FnvHasher;
+pub use murmur3::Hasher as Murmur3Hasher;
+
+mod fnv;
+mod murmur3;
+
+/// See [`core::hash::BuildHasherDefault`][0] for details
+///
+/// [0]: https://doc.rust-lang.org/core/hash/struct.BuildHasherDefault.html
+pub struct BuildHasherDefault<H>
+{
+    _marker: PhantomData<H>,
+}
+
+impl<H> Default for BuildHasherDefault<H>
+where
+    H: Default + Hasher,
+{
+    fn default() -> Self {
+        BuildHasherDefault {
+            _marker: PhantomData,
+        }
+    }
+}
+
+impl<H> Clone for BuildHasherDefault<H>
+where
+    H: Default + Hasher,
+{
+    fn clone(&self) -> Self {
+        BuildHasherDefault::default()
+    }
+}
+
+impl<H> PartialEq for BuildHasherDefault<H>
+where
+    H: Default + Hasher,
+{
+    fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
+        true
+    }
+}
+
+impl<H: Default + Hasher> Eq for BuildHasherDefault<H> {}
+
+impl<H: Default + Hasher> fmt::Debug for BuildHasherDefault<H> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.pad("BuildHasherDefault")
+    }
+}
+
+impl<H> BuildHasherDefault<H>
+{
+    /// `const` constructor
+    pub const fn new() -> Self {
+        BuildHasherDefault {
+            _marker: PhantomData,
+        }
+    }
+}
+
+impl<H> BuildHasher for BuildHasherDefault<H>
+where
+    H: Default + Hasher,
+{
+    type Hasher = H;
+
+    fn build_hasher(&self) -> Self::Hasher {
+        H::default()
+    }
+}
+
+/// See [`core::hash::BuildHasher`][0] for details
+///
+/// [0]: https://doc.rust-lang.org/core/hash/trait.BuildHasher.html
+pub trait BuildHasher {
+    /// See [`core::hash::BuildHasher::Hasher`][0]
+    ///
+    /// [0]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html#associatedtype.Hasher
+    type Hasher: Hasher;
+
+    /// See [`core::hash::BuildHasher.build_hasher`][0]
+    ///
+    /// [0]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html#tymethod.build_hasher
+    fn build_hasher(&self) -> Self::Hasher;
+}
+
+/// See [`core::hash::Hasher`][0] for details
+///
+/// [0]: https://doc.rust-lang.org/core/hash/trait.Hasher.html
+///
+/// # Contract
+///
+/// Implementers of this trait must *not* perform any 64-bit (or 128-bit) operation while computing
+/// the hash.
+pub trait Hasher {
+    /// See [`core::hash::Hasher.finish`][0]
+    ///
+    /// [0]: https://doc.rust-lang.org/std/hash/trait.Hasher.html#tymethod.finish
+    fn finish(&self) -> u32;
+
+    /// See [`core::hash::Hasher.write`][0]
+    ///
+    /// [0]: https://doc.rust-lang.org/std/hash/trait.Hasher.html#tymethod.write
+    fn write(&mut self, bytes: &[u8]);
+}
+
+/// See [`core::hash::Hash`][0] for details
+///
+/// [0]: https://doc.rust-lang.org/core/hash/trait.Hash.html
+pub trait Hash {
+    /// Feeds this value into the given `Hasher`.
+    fn hash<H>(&self, state: &mut H)
+    where
+        H: Hasher;
+
+    /// Feeds a slice of this type into the given `Hasher`.
+    fn hash_slice<H>(data: &[Self], state: &mut H)
+    where
+        H: Hasher,
+        Self: Sized,
+    {
+        for piece in data {
+            piece.hash(state);
+        }
+    }
+}
+
+macro_rules! int {
+    ($ty:ident) => {
+        impl Hash for $ty {
+            fn hash<H>(&self, state: &mut H)
+            where
+                H: Hasher,
+            {
+                unsafe { state.write(&mem::transmute::<$ty, [u8; mem::size_of::<$ty>()]>(*self)) }
+            }
+
+            fn hash_slice<H>(data: &[Self], state: &mut H)
+            where
+                H: Hasher,
+            {
+                let newlen = data.len() * mem::size_of::<$ty>();
+                let ptr = data.as_ptr() as *const u8;
+                unsafe { state.write(slice::from_raw_parts(ptr, newlen)) }
+            }
+        }
+    };
+}
+
+int!(i16);
+int!(i32);
+int!(i64);
+int!(i8);
+int!(isize);
+int!(u16);
+int!(u32);
+int!(u64);
+int!(u8);
+int!(usize);
+
+impl Hash for bool {
+    fn hash<H>(&self, state: &mut H)
+    where
+        H: Hasher,
+    {
+        (*self as u8).hash(state)
+    }
+}
+
+impl Hash for char {
+    fn hash<H>(&self, state: &mut H)
+    where
+        H: Hasher,
+    {
+        (*self as u32).hash(state)
+    }
+}
+
+impl Hash for str {
+    fn hash<H>(&self, state: &mut H)
+    where
+        H: Hasher,
+    {
+        state.write(self.as_bytes());
+        state.write(&[0xff]);
+    }
+}
+
+impl<T> Hash for [T]
+where
+    T: Hash,
+{
+    fn hash<H>(&self, state: &mut H)
+    where
+        H: Hasher,
+    {
+        self.len().hash(state);
+        T::hash_slice(self, state);
+    }
+}
+
+macro_rules! array {
+    ($($n:expr),+) => {
+        $(
+            impl<T> Hash for [T; $n]
+                where
+                T: Hash,
+            {
+                fn hash<H>(&self, state: &mut H)
+                    where
+                    H: Hasher,
+                {
+                    Hash::hash(&self[..], state)
+                }
+            }
+        )+
+    };
+}
+
+array!(
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+    26, 27, 28, 29, 30, 31, 32
+);
+
+impl<'a, T: ?Sized + Hash> Hash for &'a T {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        (**self).hash(state);
+    }
+}
+
+impl<'a, T: ?Sized + Hash> Hash for &'a mut T {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        (**self).hash(state);
+    }
+}
+
+impl Hash for () {
+    fn hash<H: Hasher>(&self, _state: &mut H) {}
+}
+
+macro_rules! tuple {
+    ( $($name:ident)+) => (
+        impl<$($name: Hash),*> Hash for ($($name,)*)
+            where
+            last_type!($($name,)+): ?Sized
+        {
+            #[allow(non_snake_case)]
+            fn hash<S: Hasher>(&self, state: &mut S) {
+                let ($(ref $name,)*) = *self;
+                $($name.hash(state);)*
+            }
+        }
+    );
+}
+
+macro_rules! last_type {
+    ($a:ident,) => { $a };
+    ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
+}
+
+tuple! { A }
+tuple! { A B }
+tuple! { A B C }
+tuple! { A B C D }
+tuple! { A B C D E }
+tuple! { A B C D E F }
+tuple! { A B C D E F G }
+tuple! { A B C D E F G H }
+tuple! { A B C D E F G H I }
+tuple! { A B C D E F G H I J }
+tuple! { A B C D E F G H I J K }
+tuple! { A B C D E F G H I J K L }
+
+#[cfg(test)]
+mod test {
+    use super::{FnvHasher, Hash, Hasher};
+    #[test]
+    fn hashes_tuples() {
+        let mut h = FnvHasher::default();
+        ().hash(&mut h);
+        (1_usize,).hash(&mut h);
+        (1_u8, 2_i8).hash(&mut h);
+        (1_u16, 2_i16, 3_u32).hash(&mut h);
+        (1_i32, 2_u64, 3_i64, true).hash(&mut h);
+        (1_isize, 'a', "abc", [1u32, 2, 3, 4], false).hash(&mut h);
+        h.finish();
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/hash32/murmur3.rs.html b/docs/doc/src/hash32/murmur3.rs.html new file mode 100644 index 0000000..dddbfbc --- /dev/null +++ b/docs/doc/src/hash32/murmur3.rs.html @@ -0,0 +1,381 @@ +murmur3.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+
use core::{mem, slice};
+
+use byteorder::{ByteOrder, LE};
+
+/// 32-bit MurmurHash3 hasher
+pub struct Hasher {
+    buf: Buffer,
+    index: Index,
+    processed: u32,
+    state: State,
+}
+
+struct State(u32);
+
+#[derive(Clone, Copy)]
+#[repr(align(4))]
+struct Buffer {
+    bytes: [u8; 4],
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum Index {
+    _0,
+    _1,
+    _2,
+    _3,
+}
+
+impl Index {
+    fn usize(&self) -> usize {
+        match *self {
+            Index::_0 => 0,
+            Index::_1 => 1,
+            Index::_2 => 2,
+            Index::_3 => 3,
+        }
+    }
+}
+
+impl From<usize> for Index {
+    fn from(x: usize) -> Self {
+        match x % 4 {
+            0 => Index::_0,
+            1 => Index::_1,
+            2 => Index::_2,
+            3 => Index::_3,
+            _ => unreachable!(),
+        }
+    }
+}
+
+impl Hasher {
+    fn push(&mut self, buf: &[u8]) {
+        let start = self.index.usize();
+        let len = buf.len();
+        // NOTE(unsafe) avoid calling `memcpy` on a 0-3 byte copy
+        // self.buf.bytes[start..start+len].copy_from(buf);
+        for i in 0..len {
+            unsafe {
+                *self.buf.bytes.get_unchecked_mut(start + i) = *buf.get_unchecked(i);
+            }
+        }
+        self.index = Index::from(start + len);
+    }
+}
+
+impl Default for Hasher {
+    #[allow(deprecated)]
+    fn default() -> Self {
+        Hasher {
+            buf: unsafe { mem::uninitialized() },
+            index: Index::_0,
+            processed: 0,
+            state: State(0),
+        }
+    }
+}
+
+impl ::Hasher for Hasher {
+    fn finish(&self) -> u32 {
+        // tail
+        let mut state = match self.index {
+            Index::_3 => {
+                let mut block = 0;
+                block ^= u32::from(self.buf.bytes[2]) << 16;
+                block ^= u32::from(self.buf.bytes[1]) << 8;
+                block ^= u32::from(self.buf.bytes[0]);
+                self.state.0 ^ pre_mix(block)
+            }
+            Index::_2 => {
+                let mut block = 0;
+                block ^= u32::from(self.buf.bytes[1]) << 8;
+                block ^= u32::from(self.buf.bytes[0]);
+                self.state.0 ^ pre_mix(block)
+            }
+            Index::_1 => {
+                let mut block = 0;
+                block ^= u32::from(self.buf.bytes[0]);
+                self.state.0 ^ pre_mix(block)
+            }
+            Index::_0 => self.state.0,
+        };
+
+        // finalization mix
+        state ^= self.processed;
+        state ^= state >> 16;
+        state = state.wrapping_mul(0x85ebca6b);
+        state ^= state >> 13;
+        state = state.wrapping_mul(0xc2b2ae35);
+        state ^= state >> 16;
+
+        state
+    }
+
+    #[inline]
+    fn write(&mut self, bytes: &[u8]) {
+        let len = bytes.len();
+        self.processed += len as u32;
+
+        let body = if self.index == Index::_0 {
+            bytes
+        } else {
+            let index = self.index.usize();
+            if len + index >= 4 {
+                // we can complete a block using the data left in the buffer
+                // NOTE(unsafe) avoid panicking branch (`slice_index_len_fail`)
+                // let (head, body) = bytes.split_at(4 - index);
+                let mid = 4 - index;
+                let head = unsafe { slice::from_raw_parts(bytes.as_ptr(), mid) };
+                let body = unsafe {
+                    slice::from_raw_parts(bytes.as_ptr().offset(mid as isize), len - mid)
+                };
+
+                // NOTE(unsafe) avoid calling `memcpy` on a 0-3 byte copy
+                // self.buf.bytes[index..].copy_from_slice(head);
+                for i in 0..4 - index {
+                    unsafe {
+                        *self.buf.bytes.get_unchecked_mut(index + i) = *head.get_unchecked(i);
+                    }
+                }
+
+                self.index = Index::_0;
+
+                self.state.process_block(&self.buf.bytes);
+
+                body
+            } else {
+                bytes
+            }
+        };
+
+        for block in body.chunks(4) {
+            if block.len() == 4 {
+                self.state
+                    .process_block(unsafe { &*(block.as_ptr() as *const _) });
+            } else {
+                self.push(block);
+            }
+        }
+
+        // XXX is this faster?
+        // for block in body.exact_chunks(4) {
+        //     self.state
+        //         .process_block(unsafe { &*(block.as_ptr() as *const _) });
+        // }
+
+        // let tail = body.split_at(body.len() / 4 * 4).1;
+
+        // self.push(tail);
+    }
+}
+
+const C1: u32 = 0xcc9e2d51;
+const C2: u32 = 0x1b873593;
+const R1: u32 = 15;
+
+impl State {
+    fn process_block(&mut self, block: &[u8; 4]) {
+        self.0 ^= pre_mix(LE::read_u32(block));
+        self.0 = self.0.rotate_left(13);
+        self.0 = 5u32.wrapping_mul(self.0).wrapping_add(0xe6546b64);
+    }
+}
+
+fn pre_mix(mut block: u32) -> u32 {
+    block = block.wrapping_mul(C1);
+    block = block.rotate_left(R1);
+    block = block.wrapping_mul(C2);
+    block
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/binary_heap.rs.html b/docs/doc/src/heapless/binary_heap.rs.html new file mode 100644 index 0000000..fb21995 --- /dev/null +++ b/docs/doc/src/heapless/binary_heap.rs.html @@ -0,0 +1,1483 @@ +binary_heap.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+
//! A priority queue implemented with a binary heap.
+//!
+//! Insertion and popping the largest element have `O(log n)` time complexity. Checking the largest
+//! / smallest element is `O(1)`.
+
+// TODO not yet implemented
+// Converting a vector to a binary heap can be done in-place, and has `O(n)` complexity. A binary
+// heap can also be converted to a sorted vector in-place, allowing it to be used for an `O(n log
+// n)` in-place heapsort.
+
+use core::{
+    cmp::Ordering,
+    fmt,
+    marker::PhantomData,
+    mem::{self, ManuallyDrop},
+    ops::{Deref, DerefMut},
+    ptr, slice,
+};
+
+use crate::vec::Vec;
+
+/// Min-heap
+pub enum Min {}
+
+/// Max-heap
+pub enum Max {}
+
+/// The binary heap kind: min-heap or max-heap
+pub trait Kind: private::Sealed {
+    #[doc(hidden)]
+    fn ordering() -> Ordering;
+}
+
+impl Kind for Min {
+    fn ordering() -> Ordering {
+        Ordering::Less
+    }
+}
+
+impl Kind for Max {
+    fn ordering() -> Ordering {
+        Ordering::Greater
+    }
+}
+
+/// Sealed traits
+mod private {
+    pub trait Sealed {}
+}
+
+impl private::Sealed for Max {}
+impl private::Sealed for Min {}
+
+/// A priority queue implemented with a binary heap.
+///
+/// This can be either a min-heap or a max-heap.
+///
+/// It is a logic error for an item to be modified in such a way that the item's ordering relative
+/// to any other item, as determined by the `Ord` trait, changes while it is in the heap. This is
+/// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
+///
+/// ```
+/// use heapless::binary_heap::{BinaryHeap, Max};
+///
+/// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+///
+/// // We can use peek to look at the next item in the heap. In this case,
+/// // there's no items in there yet so we get None.
+/// assert_eq!(heap.peek(), None);
+///
+/// // Let's add some scores...
+/// heap.push(1).unwrap();
+/// heap.push(5).unwrap();
+/// heap.push(2).unwrap();
+///
+/// // Now peek shows the most important item in the heap.
+/// assert_eq!(heap.peek(), Some(&5));
+///
+/// // We can check the length of a heap.
+/// assert_eq!(heap.len(), 3);
+///
+/// // We can iterate over the items in the heap, although they are returned in
+/// // a random order.
+/// for x in &heap {
+///     println!("{}", x);
+/// }
+///
+/// // If we instead pop these scores, they should come back in order.
+/// assert_eq!(heap.pop(), Some(5));
+/// assert_eq!(heap.pop(), Some(2));
+/// assert_eq!(heap.pop(), Some(1));
+/// assert_eq!(heap.pop(), None);
+///
+/// // We can clear the heap of any remaining items.
+/// heap.clear();
+///
+/// // The heap should now be empty.
+/// assert!(heap.is_empty())
+/// ```
+
+pub struct BinaryHeap<T, K, const N: usize> {
+    pub(crate) _kind: PhantomData<K>,
+    pub(crate) data: Vec<T, N>,
+}
+
+impl<T, K, const N: usize> BinaryHeap<T, K, N> {
+    /* Constructors */
+    /// Creates an empty BinaryHeap as a $K-heap.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// // allocate the binary heap on the stack
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// heap.push(4).unwrap();
+    ///
+    /// // allocate the binary heap in a static variable
+    /// static mut HEAP: BinaryHeap<i32, Max, 8> = BinaryHeap::new();
+    /// ```
+    pub const fn new() -> Self {
+        Self {
+            _kind: PhantomData,
+            data: Vec::new(),
+        }
+    }
+}
+
+impl<T, K, const N: usize> BinaryHeap<T, K, N>
+where
+    T: Ord,
+    K: Kind,
+{
+    /* Public API */
+    /// Returns the capacity of the binary heap.
+    pub fn capacity(&self) -> usize {
+        self.data.capacity()
+    }
+
+    /// Drops all items from the binary heap.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// heap.push(1).unwrap();
+    /// heap.push(3).unwrap();
+    ///
+    /// assert!(!heap.is_empty());
+    ///
+    /// heap.clear();
+    ///
+    /// assert!(heap.is_empty());
+    /// ```
+    pub fn clear(&mut self) {
+        self.data.clear()
+    }
+
+    /// Returns the length of the binary heap.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// heap.push(1).unwrap();
+    /// heap.push(3).unwrap();
+    ///
+    /// assert_eq!(heap.len(), 2);
+    /// ```
+    pub fn len(&self) -> usize {
+        self.data.len()
+    }
+
+    /// Checks if the binary heap is empty.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    ///
+    /// assert!(heap.is_empty());
+    ///
+    /// heap.push(3).unwrap();
+    /// heap.push(5).unwrap();
+    /// heap.push(1).unwrap();
+    ///
+    /// assert!(!heap.is_empty());
+    /// ```
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    /// Returns an iterator visiting all values in the underlying vector, in arbitrary order.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// heap.push(1).unwrap();
+    /// heap.push(2).unwrap();
+    /// heap.push(3).unwrap();
+    /// heap.push(4).unwrap();
+    ///
+    /// // Print 1, 2, 3, 4 in arbitrary order
+    /// for x in heap.iter() {
+    ///     println!("{}", x);
+    ///
+    /// }
+    /// ```
+    pub fn iter(&self) -> slice::Iter<'_, T> {
+        self.data.as_slice().iter()
+    }
+
+    /// Returns a mutable iterator visiting all values in the underlying vector, in arbitrary order.
+    ///
+    /// **WARNING** Mutating the items in the binary heap can leave the heap in an inconsistent
+    /// state.
+    pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
+        self.data.as_mut_slice().iter_mut()
+    }
+
+    /// Returns the *top* (greatest if max-heap, smallest if min-heap) item in the binary heap, or
+    /// None if it is empty.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// assert_eq!(heap.peek(), None);
+    ///
+    /// heap.push(1).unwrap();
+    /// heap.push(5).unwrap();
+    /// heap.push(2).unwrap();
+    /// assert_eq!(heap.peek(), Some(&5));
+    /// ```
+    pub fn peek(&self) -> Option<&T> {
+        self.data.as_slice().get(0)
+    }
+
+    /// Returns a mutable reference to the greatest item in the binary heap, or
+    /// `None` if it is empty.
+    ///
+    /// Note: If the `PeekMut` value is leaked, the heap may be in an
+    /// inconsistent state.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// assert!(heap.peek_mut().is_none());
+    ///
+    /// heap.push(1);
+    /// heap.push(5);
+    /// heap.push(2);
+    /// {
+    ///     let mut val = heap.peek_mut().unwrap();
+    ///     *val = 0;
+    /// }
+    ///
+    /// assert_eq!(heap.peek(), Some(&2));
+    /// ```
+    pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, K, N>> {
+        if self.is_empty() {
+            None
+        } else {
+            Some(PeekMut {
+                heap: self,
+                sift: true,
+            })
+        }
+    }
+
+    /// Removes the *top* (greatest if max-heap, smallest if min-heap) item from the binary heap and
+    /// returns it, or None if it is empty.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// heap.push(1).unwrap();
+    /// heap.push(3).unwrap();
+    ///
+    /// assert_eq!(heap.pop(), Some(3));
+    /// assert_eq!(heap.pop(), Some(1));
+    /// assert_eq!(heap.pop(), None);
+    /// ```
+    pub fn pop(&mut self) -> Option<T> {
+        if self.is_empty() {
+            None
+        } else {
+            Some(unsafe { self.pop_unchecked() })
+        }
+    }
+
+    /// Removes the *top* (greatest if max-heap, smallest if min-heap) item from the binary heap and
+    /// returns it, without checking if the binary heap is empty.
+    pub unsafe fn pop_unchecked(&mut self) -> T {
+        let mut item = self.data.pop_unchecked();
+
+        if !self.is_empty() {
+            mem::swap(&mut item, self.data.as_mut_slice().get_unchecked_mut(0));
+            self.sift_down_to_bottom(0);
+        }
+        item
+    }
+
+    /// Pushes an item onto the binary heap.
+    ///
+    /// ```
+    /// use heapless::binary_heap::{BinaryHeap, Max};
+    ///
+    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
+    /// heap.push(3).unwrap();
+    /// heap.push(5).unwrap();
+    /// heap.push(1).unwrap();
+    ///
+    /// assert_eq!(heap.len(), 3);
+    /// assert_eq!(heap.peek(), Some(&5));
+    /// ```
+    pub fn push(&mut self, item: T) -> Result<(), T> {
+        if self.data.is_full() {
+            return Err(item);
+        }
+
+        unsafe { self.push_unchecked(item) }
+        Ok(())
+    }
+
+    /// Pushes an item onto the binary heap without first checking if it's full.
+    pub unsafe fn push_unchecked(&mut self, item: T) {
+        let old_len = self.len();
+        self.data.push_unchecked(item);
+        self.sift_up(0, old_len);
+    }
+
+    /// Returns the underlying ```Vec<T,N>```. Order is arbitrary and time is O(1).
+    pub fn into_vec(self) -> Vec<T, N> {
+        self.data
+    }
+
+    /* Private API */
+    fn sift_down_to_bottom(&mut self, mut pos: usize) {
+        let end = self.len();
+        let start = pos;
+        unsafe {
+            let mut hole = Hole::new(self.data.as_mut_slice(), pos);
+            let mut child = 2 * pos + 1;
+            while child < end {
+                let right = child + 1;
+                // compare with the greater of the two children
+                if right < end && hole.get(child).cmp(hole.get(right)) != K::ordering() {
+                    child = right;
+                }
+                hole.move_to(child);
+                child = 2 * hole.pos() + 1;
+            }
+            pos = hole.pos;
+        }
+        self.sift_up(start, pos);
+    }
+
+    fn sift_up(&mut self, start: usize, pos: usize) -> usize {
+        unsafe {
+            // Take out the value at `pos` and create a hole.
+            let mut hole = Hole::new(self.data.as_mut_slice(), pos);
+
+            while hole.pos() > start {
+                let parent = (hole.pos() - 1) / 2;
+                if hole.element().cmp(hole.get(parent)) != K::ordering() {
+                    break;
+                }
+                hole.move_to(parent);
+            }
+            hole.pos()
+        }
+    }
+}
+
+/// Hole represents a hole in a slice i.e. an index without valid value
+/// (because it was moved from or duplicated).
+/// In drop, `Hole` will restore the slice by filling the hole
+/// position with the value that was originally removed.
+struct Hole<'a, T> {
+    data: &'a mut [T],
+    /// `elt` is always `Some` from new until drop.
+    elt: ManuallyDrop<T>,
+    pos: usize,
+}
+
+impl<'a, T> Hole<'a, T> {
+    /// Create a new Hole at index `pos`.
+    ///
+    /// Unsafe because pos must be within the data slice.
+    #[inline]
+    unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
+        debug_assert!(pos < data.len());
+        let elt = ptr::read(data.get_unchecked(pos));
+        Hole {
+            data,
+            elt: ManuallyDrop::new(elt),
+            pos,
+        }
+    }
+
+    #[inline]
+    fn pos(&self) -> usize {
+        self.pos
+    }
+
+    /// Returns a reference to the element removed.
+    #[inline]
+    fn element(&self) -> &T {
+        &self.elt
+    }
+
+    /// Returns a reference to the element at `index`.
+    ///
+    /// Unsafe because index must be within the data slice and not equal to pos.
+    #[inline]
+    unsafe fn get(&self, index: usize) -> &T {
+        debug_assert!(index != self.pos);
+        debug_assert!(index < self.data.len());
+        self.data.get_unchecked(index)
+    }
+
+    /// Move hole to new location
+    ///
+    /// Unsafe because index must be within the data slice and not equal to pos.
+    #[inline]
+    unsafe fn move_to(&mut self, index: usize) {
+        debug_assert!(index != self.pos);
+        debug_assert!(index < self.data.len());
+        let ptr = self.data.as_mut_ptr();
+        let index_ptr: *const _ = ptr.add(index);
+        let hole_ptr = ptr.add(self.pos);
+        ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
+        self.pos = index;
+    }
+}
+
+/// Structure wrapping a mutable reference to the greatest item on a
+/// `BinaryHeap`.
+///
+/// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See
+/// its documentation for more.
+///
+/// [`peek_mut`]: struct.BinaryHeap.html#method.peek_mut
+/// [`BinaryHeap`]: struct.BinaryHeap.html
+pub struct PeekMut<'a, T, K, const N: usize>
+where
+    T: Ord,
+    K: Kind,
+{
+    heap: &'a mut BinaryHeap<T, K, N>,
+    sift: bool,
+}
+
+impl<T, K, const N: usize> Drop for PeekMut<'_, T, K, N>
+where
+    T: Ord,
+    K: Kind,
+{
+    fn drop(&mut self) {
+        if self.sift {
+            self.heap.sift_down_to_bottom(0);
+        }
+    }
+}
+
+impl<T, K, const N: usize> Deref for PeekMut<'_, T, K, N>
+where
+    T: Ord,
+    K: Kind,
+{
+    type Target = T;
+    fn deref(&self) -> &T {
+        debug_assert!(!self.heap.is_empty());
+        // SAFE: PeekMut is only instantiated for non-empty heaps
+        unsafe { self.heap.data.as_slice().get_unchecked(0) }
+    }
+}
+
+impl<T, K, const N: usize> DerefMut for PeekMut<'_, T, K, N>
+where
+    T: Ord,
+    K: Kind,
+{
+    fn deref_mut(&mut self) -> &mut T {
+        debug_assert!(!self.heap.is_empty());
+        // SAFE: PeekMut is only instantiated for non-empty heaps
+        unsafe { self.heap.data.as_mut_slice().get_unchecked_mut(0) }
+    }
+}
+
+impl<'a, T, K, const N: usize> PeekMut<'a, T, K, N>
+where
+    T: Ord,
+    K: Kind,
+{
+    /// Removes the peeked value from the heap and returns it.
+    pub fn pop(mut this: PeekMut<'a, T, K, N>) -> T {
+        let value = this.heap.pop().unwrap();
+        this.sift = false;
+        value
+    }
+}
+
+impl<'a, T> Drop for Hole<'a, T> {
+    #[inline]
+    fn drop(&mut self) {
+        // fill the hole again
+        unsafe {
+            let pos = self.pos;
+            ptr::write(self.data.get_unchecked_mut(pos), ptr::read(&*self.elt));
+        }
+    }
+}
+
+impl<T, K, const N: usize> Default for BinaryHeap<T, K, N>
+where
+    T: Ord,
+    K: Kind,
+{
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl<T, K, const N: usize> Clone for BinaryHeap<T, K, N>
+where
+    K: Kind,
+    T: Ord + Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            _kind: self._kind,
+            data: self.data.clone(),
+        }
+    }
+}
+
+impl<T, K, const N: usize> fmt::Debug for BinaryHeap<T, K, N>
+where
+    K: Kind,
+    T: Ord + fmt::Debug,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_list().entries(self.iter()).finish()
+    }
+}
+
+impl<'a, T, K, const N: usize> IntoIterator for &'a BinaryHeap<T, K, N>
+where
+    K: Kind,
+    T: Ord,
+{
+    type Item = &'a T;
+    type IntoIter = slice::Iter<'a, T>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::vec::Vec;
+
+    use crate::binary_heap::{BinaryHeap, Max, Min};
+
+    #[test]
+    fn static_new() {
+        static mut _B: BinaryHeap<i32, Min, 16> = BinaryHeap::new();
+    }
+
+    #[test]
+    fn drop() {
+        droppable!();
+
+        {
+            let mut v: BinaryHeap<Droppable, Max, 2> = BinaryHeap::new();
+            v.push(Droppable::new()).ok().unwrap();
+            v.push(Droppable::new()).ok().unwrap();
+            v.pop().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut v: BinaryHeap<Droppable, Max, 2> = BinaryHeap::new();
+            v.push(Droppable::new()).ok().unwrap();
+            v.push(Droppable::new()).ok().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut v: BinaryHeap<Droppable, Min, 2> = BinaryHeap::new();
+            v.push(Droppable::new()).ok().unwrap();
+            v.push(Droppable::new()).ok().unwrap();
+            v.pop().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut v: BinaryHeap<Droppable, Min, 2> = BinaryHeap::new();
+            v.push(Droppable::new()).ok().unwrap();
+            v.push(Droppable::new()).ok().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+    }
+
+    #[test]
+    fn into_vec() {
+        droppable!();
+
+        let mut h: BinaryHeap<Droppable, Max, 2> = BinaryHeap::new();
+        h.push(Droppable::new()).ok().unwrap();
+        h.push(Droppable::new()).ok().unwrap();
+        h.pop().unwrap();
+
+        assert_eq!(Droppable::count(), 1);
+
+        let v = h.into_vec();
+
+        assert_eq!(Droppable::count(), 1);
+
+        core::mem::drop(v);
+
+        assert_eq!(Droppable::count(), 0);
+    }
+
+    #[test]
+    fn min() {
+        let mut heap = BinaryHeap::<_, Min, 16>::new();
+        heap.push(1).unwrap();
+        heap.push(2).unwrap();
+        heap.push(3).unwrap();
+        heap.push(17).unwrap();
+        heap.push(19).unwrap();
+        heap.push(36).unwrap();
+        heap.push(7).unwrap();
+        heap.push(25).unwrap();
+        heap.push(100).unwrap();
+
+        assert_eq!(
+            heap.iter().cloned().collect::<Vec<_>>(),
+            [1, 2, 3, 17, 19, 36, 7, 25, 100]
+        );
+
+        assert_eq!(heap.pop(), Some(1));
+
+        assert_eq!(
+            heap.iter().cloned().collect::<Vec<_>>(),
+            [2, 17, 3, 25, 19, 36, 7, 100]
+        );
+
+        assert_eq!(heap.pop(), Some(2));
+        assert_eq!(heap.pop(), Some(3));
+        assert_eq!(heap.pop(), Some(7));
+        assert_eq!(heap.pop(), Some(17));
+        assert_eq!(heap.pop(), Some(19));
+        assert_eq!(heap.pop(), Some(25));
+        assert_eq!(heap.pop(), Some(36));
+        assert_eq!(heap.pop(), Some(100));
+        assert_eq!(heap.pop(), None);
+
+        assert!(heap.peek_mut().is_none());
+
+        heap.push(1).unwrap();
+        heap.push(2).unwrap();
+        heap.push(10).unwrap();
+
+        {
+            let mut val = heap.peek_mut().unwrap();
+            *val = 7;
+        }
+
+        assert_eq!(heap.pop(), Some(2));
+        assert_eq!(heap.pop(), Some(7));
+        assert_eq!(heap.pop(), Some(10));
+        assert_eq!(heap.pop(), None);
+    }
+
+    #[test]
+    fn max() {
+        let mut heap = BinaryHeap::<_, Max, 16>::new();
+        heap.push(1).unwrap();
+        heap.push(2).unwrap();
+        heap.push(3).unwrap();
+        heap.push(17).unwrap();
+        heap.push(19).unwrap();
+        heap.push(36).unwrap();
+        heap.push(7).unwrap();
+        heap.push(25).unwrap();
+        heap.push(100).unwrap();
+
+        assert_eq!(
+            heap.iter().cloned().collect::<Vec<_>>(),
+            [100, 36, 19, 25, 3, 2, 7, 1, 17]
+        );
+
+        assert_eq!(heap.pop(), Some(100));
+
+        assert_eq!(
+            heap.iter().cloned().collect::<Vec<_>>(),
+            [36, 25, 19, 17, 3, 2, 7, 1]
+        );
+
+        assert_eq!(heap.pop(), Some(36));
+        assert_eq!(heap.pop(), Some(25));
+        assert_eq!(heap.pop(), Some(19));
+        assert_eq!(heap.pop(), Some(17));
+        assert_eq!(heap.pop(), Some(7));
+        assert_eq!(heap.pop(), Some(3));
+        assert_eq!(heap.pop(), Some(2));
+        assert_eq!(heap.pop(), Some(1));
+        assert_eq!(heap.pop(), None);
+
+        assert!(heap.peek_mut().is_none());
+
+        heap.push(1).unwrap();
+        heap.push(9).unwrap();
+        heap.push(10).unwrap();
+
+        {
+            let mut val = heap.peek_mut().unwrap();
+            *val = 7;
+        }
+
+        assert_eq!(heap.pop(), Some(9));
+        assert_eq!(heap.pop(), Some(7));
+        assert_eq!(heap.pop(), Some(1));
+        assert_eq!(heap.pop(), None);
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/deque.rs.html b/docs/doc/src/heapless/deque.rs.html new file mode 100644 index 0000000..846e3fb --- /dev/null +++ b/docs/doc/src/heapless/deque.rs.html @@ -0,0 +1,1663 @@ +deque.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+742
+743
+744
+745
+746
+747
+748
+749
+750
+751
+752
+753
+754
+755
+756
+757
+758
+759
+760
+761
+762
+763
+764
+765
+766
+767
+768
+769
+770
+771
+772
+773
+774
+775
+776
+777
+778
+779
+780
+781
+782
+783
+784
+785
+786
+787
+788
+789
+790
+791
+792
+793
+794
+795
+796
+797
+798
+799
+800
+801
+802
+803
+804
+805
+806
+807
+808
+809
+810
+811
+812
+813
+814
+815
+816
+817
+818
+819
+820
+821
+822
+823
+824
+825
+826
+827
+828
+829
+830
+831
+
use core::fmt;
+use core::iter::FusedIterator;
+use core::marker::PhantomData;
+use core::mem::MaybeUninit;
+use core::{ptr, slice};
+
+/// A fixed capacity double-ended queue.
+///
+/// # Examples
+///
+/// ```
+/// use heapless::Deque;
+///
+/// // A deque with a fixed capacity of 8 elements allocated on the stack
+/// let mut deque = Deque::<_, 8>::new();
+///
+/// // You can use it as a good old FIFO queue.
+/// deque.push_back(1);
+/// deque.push_back(2);
+/// assert_eq!(deque.len(), 2);
+///
+/// assert_eq!(deque.pop_front(), Some(1));
+/// assert_eq!(deque.pop_front(), Some(2));
+/// assert_eq!(deque.len(), 0);
+///
+/// // Deque is double-ended, you can push and pop from the front and back.
+/// deque.push_back(1);
+/// deque.push_front(2);
+/// deque.push_back(3);
+/// deque.push_front(4);
+/// assert_eq!(deque.pop_front(), Some(4));
+/// assert_eq!(deque.pop_front(), Some(2));
+/// assert_eq!(deque.pop_front(), Some(1));
+/// assert_eq!(deque.pop_front(), Some(3));
+///
+/// // You can iterate it, yielding all the elements front-to-back.
+/// for x in &deque {
+///     println!("{}", x);
+/// }
+/// ```
+pub struct Deque<T, const N: usize> {
+    buffer: [MaybeUninit<T>; N],
+
+    /// Front index. Always 0..=(N-1)
+    front: usize,
+    /// Back index. Always 0..=(N-1).
+    back: usize,
+
+    /// Used to distinguish "empty" and "full" cases when `front == back`.
+    /// May only be `true` if `front == back`, always `false` otherwise.
+    full: bool,
+}
+
+impl<T, const N: usize> Deque<T, N> {
+    const INIT: MaybeUninit<T> = MaybeUninit::uninit();
+
+    /// Constructs a new, empty deque with a fixed capacity of `N`
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Deque;
+    ///
+    /// // allocate the deque on the stack
+    /// let mut x: Deque<u8, 16> = Deque::new();
+    ///
+    /// // allocate the deque in a static variable
+    /// static mut X: Deque<u8, 16> = Deque::new();
+    /// ```
+    pub const fn new() -> Self {
+        // Const assert N > 0
+        crate::sealed::greater_than_0::<N>();
+
+        Self {
+            buffer: [Self::INIT; N],
+            front: 0,
+            back: 0,
+            full: false,
+        }
+    }
+
+    fn increment(i: usize) -> usize {
+        if i + 1 == N {
+            0
+        } else {
+            i + 1
+        }
+    }
+
+    fn decrement(i: usize) -> usize {
+        if i == 0 {
+            N - 1
+        } else {
+            i - 1
+        }
+    }
+
+    /// Returns the maximum number of elements the deque can hold.
+    pub const fn capacity(&self) -> usize {
+        N
+    }
+
+    /// Returns the number of elements currently in the deque.
+    pub const fn len(&self) -> usize {
+        if self.full {
+            N
+        } else if self.back < self.front {
+            self.back + N - self.front
+        } else {
+            self.back - self.front
+        }
+    }
+
+    /// Clears the deque, removing all values.
+    pub fn clear(&mut self) {
+        // safety: we're immediately setting a consistent empty state.
+        unsafe { self.drop_contents() }
+        self.front = 0;
+        self.back = 0;
+        self.full = false;
+    }
+
+    /// Drop all items in the `Deque`, leaving the state `back/front/full` unmodified.
+    ///
+    /// safety: leaves the `Deque` in an inconsistent state, so can cause duplicate drops.
+    unsafe fn drop_contents(&mut self) {
+        // We drop each element used in the deque by turning into a &mut[T]
+        let (a, b) = self.as_mut_slices();
+        ptr::drop_in_place(a);
+        ptr::drop_in_place(b);
+    }
+
+    /// Returns whether the deque is empty.
+    pub fn is_empty(&self) -> bool {
+        self.front == self.back && !self.full
+    }
+
+    /// Returns whether the deque is full (i.e. if `len() == capacity()`.
+    pub fn is_full(&self) -> bool {
+        self.full
+    }
+
+    /// Returns a pair of slices which contain, in order, the contents of the `Deque`.
+    pub fn as_slices(&self) -> (&[T], &[T]) {
+        // NOTE(unsafe) avoid bound checks in the slicing operation
+        unsafe {
+            if self.is_empty() {
+                (&[], &[])
+            } else if self.back <= self.front {
+                (
+                    slice::from_raw_parts(
+                        self.buffer.as_ptr().add(self.front) as *const T,
+                        N - self.front,
+                    ),
+                    slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.back),
+                )
+            } else {
+                (
+                    slice::from_raw_parts(
+                        self.buffer.as_ptr().add(self.front) as *const T,
+                        self.back - self.front,
+                    ),
+                    &[],
+                )
+            }
+        }
+    }
+
+    /// Returns a pair of mutable slices which contain, in order, the contents of the `Deque`.
+    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
+        let ptr = self.buffer.as_mut_ptr();
+
+        // NOTE(unsafe) avoid bound checks in the slicing operation
+        unsafe {
+            if self.is_empty() {
+                (&mut [], &mut [])
+            } else if self.back <= self.front {
+                (
+                    slice::from_raw_parts_mut(ptr.add(self.front) as *mut T, N - self.front),
+                    slice::from_raw_parts_mut(ptr as *mut T, self.back),
+                )
+            } else {
+                (
+                    slice::from_raw_parts_mut(
+                        ptr.add(self.front) as *mut T,
+                        self.back - self.front,
+                    ),
+                    &mut [],
+                )
+            }
+        }
+    }
+
+    /// Provides a reference to the front element, or None if the `Deque` is empty.
+    pub fn front(&self) -> Option<&T> {
+        if self.is_empty() {
+            None
+        } else {
+            Some(unsafe { &*self.buffer.get_unchecked(self.front).as_ptr() })
+        }
+    }
+
+    /// Provides a mutable reference to the front element, or None if the `Deque` is empty.
+    pub fn front_mut(&mut self) -> Option<&mut T> {
+        if self.is_empty() {
+            None
+        } else {
+            Some(unsafe { &mut *self.buffer.get_unchecked_mut(self.front).as_mut_ptr() })
+        }
+    }
+
+    /// Provides a reference to the back element, or None if the `Deque` is empty.
+    pub fn back(&self) -> Option<&T> {
+        if self.is_empty() {
+            None
+        } else {
+            let index = Self::decrement(self.back);
+            Some(unsafe { &*self.buffer.get_unchecked(index).as_ptr() })
+        }
+    }
+
+    /// Provides a mutable reference to the back element, or None if the `Deque` is empty.
+    pub fn back_mut(&mut self) -> Option<&mut T> {
+        if self.is_empty() {
+            None
+        } else {
+            let index = Self::decrement(self.back);
+            Some(unsafe { &mut *self.buffer.get_unchecked_mut(index).as_mut_ptr() })
+        }
+    }
+
+    /// Removes the item from the front of the deque and returns it, or `None` if it's empty
+    pub fn pop_front(&mut self) -> Option<T> {
+        if self.is_empty() {
+            None
+        } else {
+            Some(unsafe { self.pop_front_unchecked() })
+        }
+    }
+
+    /// Removes the item from the back of the deque and returns it, or `None` if it's empty
+    pub fn pop_back(&mut self) -> Option<T> {
+        if self.is_empty() {
+            None
+        } else {
+            Some(unsafe { self.pop_back_unchecked() })
+        }
+    }
+
+    /// Appends an `item` to the front of the deque
+    ///
+    /// Returns back the `item` if the deque is full
+    pub fn push_front(&mut self, item: T) -> Result<(), T> {
+        if self.is_full() {
+            Err(item)
+        } else {
+            unsafe { self.push_front_unchecked(item) }
+            Ok(())
+        }
+    }
+
+    /// Appends an `item` to the back of the deque
+    ///
+    /// Returns back the `item` if the deque is full
+    pub fn push_back(&mut self, item: T) -> Result<(), T> {
+        if self.is_full() {
+            Err(item)
+        } else {
+            unsafe { self.push_back_unchecked(item) }
+            Ok(())
+        }
+    }
+
+    /// Removes an item from the front of the deque and returns it, without checking that the deque
+    /// is not empty
+    ///
+    /// # Safety
+    ///
+    /// It's undefined behavior to call this on an empty deque
+    pub unsafe fn pop_front_unchecked(&mut self) -> T {
+        debug_assert!(!self.is_empty());
+
+        let index = self.front;
+        self.full = false;
+        self.front = Self::increment(self.front);
+        (self.buffer.get_unchecked_mut(index).as_ptr() as *const T).read()
+    }
+
+    /// Removes an item from the back of the deque and returns it, without checking that the deque
+    /// is not empty
+    ///
+    /// # Safety
+    ///
+    /// It's undefined behavior to call this on an empty deque
+    pub unsafe fn pop_back_unchecked(&mut self) -> T {
+        debug_assert!(!self.is_empty());
+
+        self.full = false;
+        self.back = Self::decrement(self.back);
+        (self.buffer.get_unchecked_mut(self.back).as_ptr() as *const T).read()
+    }
+
+    /// Appends an `item` to the front of the deque
+    ///
+    /// # Safety
+    ///
+    /// This assumes the deque is not full.
+    pub unsafe fn push_front_unchecked(&mut self, item: T) {
+        debug_assert!(!self.is_full());
+
+        let index = Self::decrement(self.front);
+        // NOTE: the memory slot that we are about to write to is uninitialized. We assign
+        // a `MaybeUninit` to avoid running `T`'s destructor on the uninitialized memory
+        *self.buffer.get_unchecked_mut(index) = MaybeUninit::new(item);
+        self.front = index;
+        if self.front == self.back {
+            self.full = true;
+        }
+    }
+
+    /// Appends an `item` to the back of the deque
+    ///
+    /// # Safety
+    ///
+    /// This assumes the deque is not full.
+    pub unsafe fn push_back_unchecked(&mut self, item: T) {
+        debug_assert!(!self.is_full());
+
+        // NOTE: the memory slot that we are about to write to is uninitialized. We assign
+        // a `MaybeUninit` to avoid running `T`'s destructor on the uninitialized memory
+        *self.buffer.get_unchecked_mut(self.back) = MaybeUninit::new(item);
+        self.back = Self::increment(self.back);
+        if self.front == self.back {
+            self.full = true;
+        }
+    }
+
+    /// Returns an iterator over the deque.
+    pub fn iter(&self) -> Iter<'_, T, N> {
+        let done = self.is_empty();
+        Iter {
+            _phantom: PhantomData,
+            buffer: &self.buffer as *const MaybeUninit<T>,
+            front: self.front,
+            back: self.back,
+            done,
+        }
+    }
+
+    /// Returns an iterator that allows modifying each value.
+    pub fn iter_mut(&mut self) -> IterMut<'_, T, N> {
+        let done = self.is_empty();
+        IterMut {
+            _phantom: PhantomData,
+            buffer: &mut self.buffer as *mut _ as *mut MaybeUninit<T>,
+            front: self.front,
+            back: self.back,
+            done,
+        }
+    }
+}
+
+// Trait implementations
+
+impl<T, const N: usize> Default for Deque<T, N> {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl<T, const N: usize> Drop for Deque<T, N> {
+    fn drop(&mut self) {
+        // safety: `self` is left in an inconsistent state but it doesn't matter since
+        // it's getting dropped. Nothing should be able to observe `self` after drop.
+        unsafe { self.drop_contents() }
+    }
+}
+
+impl<T: fmt::Debug, const N: usize> fmt::Debug for Deque<T, N> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_list().entries(self).finish()
+    }
+}
+
+/// An iterator that moves out of a [`Deque`].
+///
+/// This struct is created by calling the `into_iter` method.
+///
+#[derive(Clone)]
+pub struct IntoIter<T, const N: usize> {
+    deque: Deque<T, N>,
+}
+
+impl<T, const N: usize> Iterator for IntoIter<T, N> {
+    type Item = T;
+    fn next(&mut self) -> Option<Self::Item> {
+        self.deque.pop_front()
+    }
+}
+
+impl<T, const N: usize> IntoIterator for Deque<T, N> {
+    type Item = T;
+    type IntoIter = IntoIter<T, N>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        IntoIter { deque: self }
+    }
+}
+
+/// An iterator over the elements of a [`Deque`].
+///
+/// This struct is created by calling the `iter` method.
+#[derive(Clone)]
+pub struct Iter<'a, T, const N: usize> {
+    buffer: *const MaybeUninit<T>,
+    _phantom: PhantomData<&'a T>,
+    front: usize,
+    back: usize,
+    done: bool,
+}
+
+impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
+    type Item = &'a T;
+    fn next(&mut self) -> Option<Self::Item> {
+        if self.done {
+            None
+        } else {
+            let index = self.front;
+            self.front = Deque::<T, N>::increment(self.front);
+            if self.front == self.back {
+                self.done = true;
+            }
+            Some(unsafe { &*(self.buffer.add(index) as *const T) })
+        }
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let len = if self.done {
+            0
+        } else if self.back <= self.front {
+            self.back + N - self.front
+        } else {
+            self.back - self.front
+        };
+
+        (len, Some(len))
+    }
+}
+
+impl<'a, T, const N: usize> DoubleEndedIterator for Iter<'a, T, N> {
+    fn next_back(&mut self) -> Option<Self::Item> {
+        if self.done {
+            None
+        } else {
+            self.back = Deque::<T, N>::decrement(self.back);
+            if self.front == self.back {
+                self.done = true;
+            }
+            Some(unsafe { &*(self.buffer.add(self.back) as *const T) })
+        }
+    }
+}
+
+impl<'a, T, const N: usize> ExactSizeIterator for Iter<'a, T, N> {}
+impl<'a, T, const N: usize> FusedIterator for Iter<'a, T, N> {}
+
+/// An iterator over the elements of a [`Deque`].
+///
+/// This struct is created by calling the `iter` method.
+pub struct IterMut<'a, T, const N: usize> {
+    buffer: *mut MaybeUninit<T>,
+    _phantom: PhantomData<&'a mut T>,
+    front: usize,
+    back: usize,
+    done: bool,
+}
+
+impl<'a, T, const N: usize> Iterator for IterMut<'a, T, N> {
+    type Item = &'a mut T;
+    fn next(&mut self) -> Option<Self::Item> {
+        if self.done {
+            None
+        } else {
+            let index = self.front;
+            self.front = Deque::<T, N>::increment(self.front);
+            if self.front == self.back {
+                self.done = true;
+            }
+            Some(unsafe { &mut *(self.buffer.add(index) as *mut T) })
+        }
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let len = if self.done {
+            0
+        } else if self.back <= self.front {
+            self.back + N - self.front
+        } else {
+            self.back - self.front
+        };
+
+        (len, Some(len))
+    }
+}
+
+impl<'a, T, const N: usize> DoubleEndedIterator for IterMut<'a, T, N> {
+    fn next_back(&mut self) -> Option<Self::Item> {
+        if self.done {
+            None
+        } else {
+            self.back = Deque::<T, N>::decrement(self.back);
+            if self.front == self.back {
+                self.done = true;
+            }
+            Some(unsafe { &mut *(self.buffer.add(self.back) as *mut T) })
+        }
+    }
+}
+
+impl<'a, T, const N: usize> ExactSizeIterator for IterMut<'a, T, N> {}
+impl<'a, T, const N: usize> FusedIterator for IterMut<'a, T, N> {}
+
+impl<'a, T, const N: usize> IntoIterator for &'a Deque<T, N> {
+    type Item = &'a T;
+    type IntoIter = Iter<'a, T, N>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl<'a, T, const N: usize> IntoIterator for &'a mut Deque<T, N> {
+    type Item = &'a mut T;
+    type IntoIter = IterMut<'a, T, N>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter_mut()
+    }
+}
+
+impl<T, const N: usize> Clone for Deque<T, N>
+where
+    T: Clone,
+{
+    fn clone(&self) -> Self {
+        let mut res = Deque::new();
+        for i in self {
+            // safety: the original and new deques have the same capacity, so it can
+            // not become full.
+            unsafe { res.push_back_unchecked(i.clone()) }
+        }
+        res
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::Deque;
+
+    #[test]
+    fn static_new() {
+        static mut _V: Deque<i32, 4> = Deque::new();
+    }
+
+    #[test]
+    fn stack_new() {
+        let mut _v: Deque<i32, 4> = Deque::new();
+    }
+
+    #[test]
+    fn drop() {
+        droppable!();
+
+        {
+            let mut v: Deque<Droppable, 2> = Deque::new();
+            v.push_back(Droppable::new()).ok().unwrap();
+            v.push_back(Droppable::new()).ok().unwrap();
+            v.pop_front().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut v: Deque<Droppable, 2> = Deque::new();
+            v.push_back(Droppable::new()).ok().unwrap();
+            v.push_back(Droppable::new()).ok().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+        {
+            let mut v: Deque<Droppable, 2> = Deque::new();
+            v.push_front(Droppable::new()).ok().unwrap();
+            v.push_front(Droppable::new()).ok().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+    }
+
+    #[test]
+    fn full() {
+        let mut v: Deque<i32, 4> = Deque::new();
+
+        v.push_back(0).unwrap();
+        v.push_front(1).unwrap();
+        v.push_back(2).unwrap();
+        v.push_back(3).unwrap();
+
+        assert!(v.push_front(4).is_err());
+        assert!(v.push_back(4).is_err());
+        assert!(v.is_full());
+    }
+
+    #[test]
+    fn empty() {
+        let mut v: Deque<i32, 4> = Deque::new();
+        assert!(v.is_empty());
+
+        v.push_back(0).unwrap();
+        assert!(!v.is_empty());
+
+        v.push_front(1).unwrap();
+        assert!(!v.is_empty());
+
+        v.pop_front().unwrap();
+        v.pop_front().unwrap();
+
+        assert!(v.pop_front().is_none());
+        assert!(v.pop_back().is_none());
+        assert!(v.is_empty());
+    }
+
+    #[test]
+    fn front_back() {
+        let mut v: Deque<i32, 4> = Deque::new();
+        assert_eq!(v.front(), None);
+        assert_eq!(v.front_mut(), None);
+        assert_eq!(v.back(), None);
+        assert_eq!(v.back_mut(), None);
+
+        v.push_back(4).unwrap();
+        assert_eq!(v.front(), Some(&4));
+        assert_eq!(v.front_mut(), Some(&mut 4));
+        assert_eq!(v.back(), Some(&4));
+        assert_eq!(v.back_mut(), Some(&mut 4));
+
+        v.push_front(3).unwrap();
+        assert_eq!(v.front(), Some(&3));
+        assert_eq!(v.front_mut(), Some(&mut 3));
+        assert_eq!(v.back(), Some(&4));
+        assert_eq!(v.back_mut(), Some(&mut 4));
+
+        v.pop_back().unwrap();
+        assert_eq!(v.front(), Some(&3));
+        assert_eq!(v.front_mut(), Some(&mut 3));
+        assert_eq!(v.back(), Some(&3));
+        assert_eq!(v.back_mut(), Some(&mut 3));
+
+        v.pop_front().unwrap();
+        assert_eq!(v.front(), None);
+        assert_eq!(v.front_mut(), None);
+        assert_eq!(v.back(), None);
+        assert_eq!(v.back_mut(), None);
+    }
+
+    #[test]
+    fn iter() {
+        let mut v: Deque<i32, 4> = Deque::new();
+
+        v.push_back(0).unwrap();
+        v.push_back(1).unwrap();
+        v.push_front(2).unwrap();
+        v.push_front(3).unwrap();
+        v.pop_back().unwrap();
+        v.push_front(4).unwrap();
+
+        let mut items = v.iter();
+
+        assert_eq!(items.next(), Some(&4));
+        assert_eq!(items.next(), Some(&3));
+        assert_eq!(items.next(), Some(&2));
+        assert_eq!(items.next(), Some(&0));
+        assert_eq!(items.next(), None);
+    }
+
+    #[test]
+    fn iter_mut() {
+        let mut v: Deque<i32, 4> = Deque::new();
+
+        v.push_back(0).unwrap();
+        v.push_back(1).unwrap();
+        v.push_front(2).unwrap();
+        v.push_front(3).unwrap();
+        v.pop_back().unwrap();
+        v.push_front(4).unwrap();
+
+        let mut items = v.iter_mut();
+
+        assert_eq!(items.next(), Some(&mut 4));
+        assert_eq!(items.next(), Some(&mut 3));
+        assert_eq!(items.next(), Some(&mut 2));
+        assert_eq!(items.next(), Some(&mut 0));
+        assert_eq!(items.next(), None);
+    }
+
+    #[test]
+    fn iter_move() {
+        let mut v: Deque<i32, 4> = Deque::new();
+        v.push_back(0).unwrap();
+        v.push_back(1).unwrap();
+        v.push_back(2).unwrap();
+        v.push_back(3).unwrap();
+
+        let mut items = v.into_iter();
+
+        assert_eq!(items.next(), Some(0));
+        assert_eq!(items.next(), Some(1));
+        assert_eq!(items.next(), Some(2));
+        assert_eq!(items.next(), Some(3));
+        assert_eq!(items.next(), None);
+    }
+
+    #[test]
+    fn iter_move_drop() {
+        droppable!();
+
+        {
+            let mut deque: Deque<Droppable, 2> = Deque::new();
+            deque.push_back(Droppable::new()).ok().unwrap();
+            deque.push_back(Droppable::new()).ok().unwrap();
+            let mut items = deque.into_iter();
+            // Move all
+            let _ = items.next();
+            let _ = items.next();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut deque: Deque<Droppable, 2> = Deque::new();
+            deque.push_back(Droppable::new()).ok().unwrap();
+            deque.push_back(Droppable::new()).ok().unwrap();
+            let _items = deque.into_iter();
+            // Move none
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut deque: Deque<Droppable, 2> = Deque::new();
+            deque.push_back(Droppable::new()).ok().unwrap();
+            deque.push_back(Droppable::new()).ok().unwrap();
+            let mut items = deque.into_iter();
+            let _ = items.next(); // Move partly
+        }
+
+        assert_eq!(Droppable::count(), 0);
+    }
+
+    #[test]
+    fn push_and_pop() {
+        let mut q: Deque<i32, 4> = Deque::new();
+        assert_eq!(q.len(), 0);
+
+        assert_eq!(q.pop_front(), None);
+        assert_eq!(q.pop_back(), None);
+        assert_eq!(q.len(), 0);
+
+        q.push_back(0).unwrap();
+        assert_eq!(q.len(), 1);
+
+        assert_eq!(q.pop_back(), Some(0));
+        assert_eq!(q.len(), 0);
+
+        q.push_back(0).unwrap();
+        q.push_back(1).unwrap();
+        q.push_front(2).unwrap();
+        q.push_front(3).unwrap();
+        assert_eq!(q.len(), 4);
+
+        // deque contains: 3 2 0 1
+        assert_eq!(q.pop_front(), Some(3));
+        assert_eq!(q.len(), 3);
+        assert_eq!(q.pop_front(), Some(2));
+        assert_eq!(q.len(), 2);
+        assert_eq!(q.pop_back(), Some(1));
+        assert_eq!(q.len(), 1);
+        assert_eq!(q.pop_front(), Some(0));
+        assert_eq!(q.len(), 0);
+
+        // deque is now empty
+        assert_eq!(q.pop_front(), None);
+        assert_eq!(q.pop_back(), None);
+        assert_eq!(q.len(), 0);
+    }
+
+    #[test]
+    fn as_slices() {
+        let mut q: Deque<i32, 4> = Deque::new();
+        assert_eq!(q.len(), 0);
+
+        q.push_back(0).unwrap();
+        q.push_back(1).unwrap();
+        q.push_back(2).unwrap();
+        q.push_back(3).unwrap();
+        assert_eq!(q.as_slices(), (&[0, 1, 2, 3][..], &[][..]));
+
+        q.pop_front().unwrap();
+        assert_eq!(q.as_slices(), (&[1, 2, 3][..], &[][..]));
+
+        q.push_back(4).unwrap();
+        assert_eq!(q.as_slices(), (&[1, 2, 3][..], &[4][..]));
+    }
+
+    #[test]
+    fn clear() {
+        let mut q: Deque<i32, 4> = Deque::new();
+        assert_eq!(q.len(), 0);
+
+        q.push_back(0).unwrap();
+        q.push_back(1).unwrap();
+        q.push_back(2).unwrap();
+        q.push_back(3).unwrap();
+        assert_eq!(q.len(), 4);
+
+        q.clear();
+        assert_eq!(q.len(), 0);
+
+        q.push_back(0).unwrap();
+        assert_eq!(q.len(), 1);
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/histbuf.rs.html b/docs/doc/src/heapless/histbuf.rs.html new file mode 100644 index 0000000..125cbee --- /dev/null +++ b/docs/doc/src/heapless/histbuf.rs.html @@ -0,0 +1,867 @@ +histbuf.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+
use core::fmt;
+use core::mem::MaybeUninit;
+use core::ops::Deref;
+use core::ptr;
+use core::slice;
+
+/// A "history buffer", similar to a write-only ring buffer of fixed length.
+///
+/// This buffer keeps a fixed number of elements.  On write, the oldest element
+/// is overwritten. Thus, the buffer is useful to keep a history of values with
+/// some desired depth, and for example calculate a rolling average.
+///
+/// # Examples
+/// ```
+/// use heapless::HistoryBuffer;
+///
+/// // Initialize a new buffer with 8 elements.
+/// let mut buf = HistoryBuffer::<_, 8>::new();
+///
+/// // Starts with no data
+/// assert_eq!(buf.recent(), None);
+///
+/// buf.write(3);
+/// buf.write(5);
+/// buf.extend(&[4, 4]);
+///
+/// // The most recent written element is a four.
+/// assert_eq!(buf.recent(), Some(&4));
+///
+/// // To access all elements in an unspecified order, use `as_slice()`.
+/// for el in buf.as_slice() { println!("{:?}", el); }
+///
+/// // Now we can prepare an average of all values, which comes out to 4.
+/// let avg = buf.as_slice().iter().sum::<usize>() / buf.len();
+/// assert_eq!(avg, 4);
+/// ```
+pub struct HistoryBuffer<T, const N: usize> {
+    data: [MaybeUninit<T>; N],
+    write_at: usize,
+    filled: bool,
+}
+
+impl<T, const N: usize> HistoryBuffer<T, N> {
+    const INIT: MaybeUninit<T> = MaybeUninit::uninit();
+
+    /// Constructs a new history buffer.
+    ///
+    /// The construction of a `HistoryBuffer` works in `const` contexts.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::HistoryBuffer;
+    ///
+    /// // Allocate a 16-element buffer on the stack
+    /// let x: HistoryBuffer<u8, 16> = HistoryBuffer::new();
+    /// assert_eq!(x.len(), 0);
+    /// ```
+    #[inline]
+    pub const fn new() -> Self {
+        // Const assert
+        crate::sealed::greater_than_0::<N>();
+
+        Self {
+            data: [Self::INIT; N],
+            write_at: 0,
+            filled: false,
+        }
+    }
+
+    /// Clears the buffer, replacing every element with the default value of
+    /// type `T`.
+    pub fn clear(&mut self) {
+        *self = Self::new();
+    }
+}
+
+impl<T, const N: usize> HistoryBuffer<T, N>
+where
+    T: Copy + Clone,
+{
+    /// Constructs a new history buffer, where every element is the given value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::HistoryBuffer;
+    ///
+    /// // Allocate a 16-element buffer on the stack
+    /// let mut x: HistoryBuffer<u8, 16> = HistoryBuffer::new_with(4);
+    /// // All elements are four
+    /// assert_eq!(x.as_slice(), [4; 16]);
+    /// ```
+    #[inline]
+    pub fn new_with(t: T) -> Self {
+        Self {
+            data: [MaybeUninit::new(t); N],
+            write_at: 0,
+            filled: true,
+        }
+    }
+
+    /// Clears the buffer, replacing every element with the given value.
+    pub fn clear_with(&mut self, t: T) {
+        *self = Self::new_with(t);
+    }
+}
+
+impl<T, const N: usize> HistoryBuffer<T, N> {
+    /// Returns the current fill level of the buffer.
+    #[inline]
+    pub fn len(&self) -> usize {
+        if self.filled {
+            N
+        } else {
+            self.write_at
+        }
+    }
+
+    /// Returns the capacity of the buffer, which is the length of the
+    /// underlying backing array.
+    #[inline]
+    pub fn capacity(&self) -> usize {
+        N
+    }
+
+    /// Writes an element to the buffer, overwriting the oldest value.
+    pub fn write(&mut self, t: T) {
+        if self.filled {
+            // Drop the old before we overwrite it.
+            unsafe { ptr::drop_in_place(self.data[self.write_at].as_mut_ptr()) }
+        }
+        self.data[self.write_at] = MaybeUninit::new(t);
+
+        self.write_at += 1;
+        if self.write_at == self.capacity() {
+            self.write_at = 0;
+            self.filled = true;
+        }
+    }
+
+    /// Clones and writes all elements in a slice to the buffer.
+    ///
+    /// If the slice is longer than the buffer, only the last `self.len()`
+    /// elements will actually be stored.
+    pub fn extend_from_slice(&mut self, other: &[T])
+    where
+        T: Clone,
+    {
+        for item in other {
+            self.write(item.clone());
+        }
+    }
+
+    /// Returns a reference to the most recently written value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::HistoryBuffer;
+    ///
+    /// let mut x: HistoryBuffer<u8, 16> = HistoryBuffer::new();
+    /// x.write(4);
+    /// x.write(10);
+    /// assert_eq!(x.recent(), Some(&10));
+    /// ```
+    pub fn recent(&self) -> Option<&T> {
+        if self.write_at == 0 {
+            if self.filled {
+                Some(unsafe { &*self.data[self.capacity() - 1].as_ptr() })
+            } else {
+                None
+            }
+        } else {
+            Some(unsafe { &*self.data[self.write_at - 1].as_ptr() })
+        }
+    }
+
+    /// Returns the array slice backing the buffer, without keeping track
+    /// of the write position. Therefore, the element order is unspecified.
+    pub fn as_slice(&self) -> &[T] {
+        unsafe { slice::from_raw_parts(self.data.as_ptr() as *const _, self.len()) }
+    }
+
+    /// Returns an iterator for iterating over the buffer from oldest to newest.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::HistoryBuffer;
+    ///
+    /// let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
+    /// buffer.extend([0, 0, 0, 1, 2, 3, 4, 5, 6]);
+    /// let expected = [1, 2, 3, 4, 5, 6];
+    /// for (x, y) in buffer.oldest_ordered().zip(expected.iter()) {
+    ///     assert_eq!(x, y)
+    /// }
+    ///
+    /// ```
+    pub fn oldest_ordered<'a>(&'a self) -> OldestOrdered<'a, T, N> {
+        if self.filled {
+            OldestOrdered {
+                buf: self,
+                cur: self.write_at,
+                wrapped: false,
+            }
+        } else {
+            // special case: act like we wrapped already to handle empty buffer.
+            OldestOrdered {
+                buf: self,
+                cur: 0,
+                wrapped: true,
+            }
+        }
+    }
+}
+
+impl<T, const N: usize> Extend<T> for HistoryBuffer<T, N> {
+    fn extend<I>(&mut self, iter: I)
+    where
+        I: IntoIterator<Item = T>,
+    {
+        for item in iter.into_iter() {
+            self.write(item);
+        }
+    }
+}
+
+impl<'a, T, const N: usize> Extend<&'a T> for HistoryBuffer<T, N>
+where
+    T: 'a + Clone,
+{
+    fn extend<I>(&mut self, iter: I)
+    where
+        I: IntoIterator<Item = &'a T>,
+    {
+        self.extend(iter.into_iter().cloned())
+    }
+}
+
+impl<T, const N: usize> Drop for HistoryBuffer<T, N> {
+    fn drop(&mut self) {
+        unsafe {
+            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(
+                self.data.as_mut_ptr() as *mut T,
+                self.len(),
+            ))
+        }
+    }
+}
+
+impl<T, const N: usize> Deref for HistoryBuffer<T, N> {
+    type Target = [T];
+
+    fn deref(&self) -> &[T] {
+        self.as_slice()
+    }
+}
+
+impl<T, const N: usize> AsRef<[T]> for HistoryBuffer<T, N> {
+    #[inline]
+    fn as_ref(&self) -> &[T] {
+        self
+    }
+}
+
+impl<T, const N: usize> fmt::Debug for HistoryBuffer<T, N>
+where
+    T: fmt::Debug,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        <[T] as fmt::Debug>::fmt(self, f)
+    }
+}
+
+impl<T, const N: usize> Default for HistoryBuffer<T, N> {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+/// An iterator on the underlying buffer ordered from oldest data to newest
+#[derive(Clone)]
+pub struct OldestOrdered<'a, T, const N: usize> {
+    buf: &'a HistoryBuffer<T, N>,
+    cur: usize,
+    wrapped: bool,
+}
+
+impl<'a, T, const N: usize> Iterator for OldestOrdered<'a, T, N> {
+    type Item = &'a T;
+
+    fn next(&mut self) -> Option<&'a T> {
+        if self.cur == self.buf.len() && self.buf.filled {
+            // roll-over
+            self.cur = 0;
+            self.wrapped = true;
+        }
+
+        if self.cur == self.buf.write_at && self.wrapped {
+            return None;
+        }
+
+        let item = &self.buf[self.cur];
+        self.cur += 1;
+        Some(item)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::HistoryBuffer;
+    use core::fmt::Debug;
+
+    #[test]
+    fn new() {
+        let x: HistoryBuffer<u8, 4> = HistoryBuffer::new_with(1);
+        assert_eq!(x.len(), 4);
+        assert_eq!(x.as_slice(), [1; 4]);
+        assert_eq!(*x, [1; 4]);
+
+        let x: HistoryBuffer<u8, 4> = HistoryBuffer::new();
+        assert_eq!(x.as_slice(), []);
+    }
+
+    #[test]
+    fn write() {
+        let mut x: HistoryBuffer<u8, 4> = HistoryBuffer::new();
+        x.write(1);
+        x.write(4);
+        assert_eq!(x.as_slice(), [1, 4]);
+
+        x.write(5);
+        x.write(6);
+        x.write(10);
+        assert_eq!(x.as_slice(), [10, 4, 5, 6]);
+
+        x.extend([11, 12].iter());
+        assert_eq!(x.as_slice(), [10, 11, 12, 6]);
+    }
+
+    #[test]
+    fn clear() {
+        let mut x: HistoryBuffer<u8, 4> = HistoryBuffer::new_with(1);
+        x.clear();
+        assert_eq!(x.as_slice(), []);
+
+        let mut x: HistoryBuffer<u8, 4> = HistoryBuffer::new();
+        x.clear_with(1);
+        assert_eq!(x.as_slice(), [1; 4]);
+    }
+
+    #[test]
+    fn recent() {
+        let mut x: HistoryBuffer<u8, 4> = HistoryBuffer::new();
+        assert_eq!(x.recent(), None);
+
+        x.write(1);
+        x.write(4);
+        assert_eq!(x.recent(), Some(&4));
+
+        x.write(5);
+        x.write(6);
+        x.write(10);
+        assert_eq!(x.recent(), Some(&10));
+    }
+
+    #[test]
+    fn as_slice() {
+        let mut x: HistoryBuffer<u8, 4> = HistoryBuffer::new();
+
+        assert_eq!(x.as_slice(), []);
+
+        x.extend([1, 2, 3, 4, 5].iter());
+
+        assert_eq!(x.as_slice(), [5, 2, 3, 4]);
+    }
+
+    #[test]
+    fn ordered() {
+        // test on an empty buffer
+        let buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
+        let mut iter = buffer.oldest_ordered();
+        assert_eq!(iter.next(), None);
+        assert_eq!(iter.next(), None);
+
+        // test on a un-filled buffer
+        let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
+        buffer.extend([1, 2, 3]);
+        assert_eq!(buffer.len(), 3);
+        assert_eq_iter(buffer.oldest_ordered(), &[1, 2, 3]);
+
+        // test on a filled buffer
+        let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
+        buffer.extend([0, 0, 0, 1, 2, 3, 4, 5, 6]);
+        assert_eq!(buffer.len(), 6);
+        assert_eq_iter(buffer.oldest_ordered(), &[1, 2, 3, 4, 5, 6]);
+
+        // comprehensive test all cases
+        for n in 0..50 {
+            const N: usize = 7;
+            let mut buffer: HistoryBuffer<u8, N> = HistoryBuffer::new();
+            buffer.extend(0..n);
+            assert_eq_iter(
+                buffer.oldest_ordered().copied(),
+                n.saturating_sub(N as u8)..n,
+            );
+        }
+    }
+
+    /// Compares two iterators item by item, making sure they stop at the same time.
+    fn assert_eq_iter<I: Eq + Debug>(
+        a: impl IntoIterator<Item = I>,
+        b: impl IntoIterator<Item = I>,
+    ) {
+        let mut a = a.into_iter();
+        let mut b = b.into_iter();
+
+        let mut i = 0;
+        loop {
+            let a_item = a.next();
+            let b_item = b.next();
+
+            assert_eq!(a_item, b_item, "{}", i);
+
+            i += 1;
+
+            if b_item.is_none() {
+                break;
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/indexmap.rs.html b/docs/doc/src/heapless/indexmap.rs.html new file mode 100644 index 0000000..39cc733 --- /dev/null +++ b/docs/doc/src/heapless/indexmap.rs.html @@ -0,0 +1,2763 @@ +indexmap.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+742
+743
+744
+745
+746
+747
+748
+749
+750
+751
+752
+753
+754
+755
+756
+757
+758
+759
+760
+761
+762
+763
+764
+765
+766
+767
+768
+769
+770
+771
+772
+773
+774
+775
+776
+777
+778
+779
+780
+781
+782
+783
+784
+785
+786
+787
+788
+789
+790
+791
+792
+793
+794
+795
+796
+797
+798
+799
+800
+801
+802
+803
+804
+805
+806
+807
+808
+809
+810
+811
+812
+813
+814
+815
+816
+817
+818
+819
+820
+821
+822
+823
+824
+825
+826
+827
+828
+829
+830
+831
+832
+833
+834
+835
+836
+837
+838
+839
+840
+841
+842
+843
+844
+845
+846
+847
+848
+849
+850
+851
+852
+853
+854
+855
+856
+857
+858
+859
+860
+861
+862
+863
+864
+865
+866
+867
+868
+869
+870
+871
+872
+873
+874
+875
+876
+877
+878
+879
+880
+881
+882
+883
+884
+885
+886
+887
+888
+889
+890
+891
+892
+893
+894
+895
+896
+897
+898
+899
+900
+901
+902
+903
+904
+905
+906
+907
+908
+909
+910
+911
+912
+913
+914
+915
+916
+917
+918
+919
+920
+921
+922
+923
+924
+925
+926
+927
+928
+929
+930
+931
+932
+933
+934
+935
+936
+937
+938
+939
+940
+941
+942
+943
+944
+945
+946
+947
+948
+949
+950
+951
+952
+953
+954
+955
+956
+957
+958
+959
+960
+961
+962
+963
+964
+965
+966
+967
+968
+969
+970
+971
+972
+973
+974
+975
+976
+977
+978
+979
+980
+981
+982
+983
+984
+985
+986
+987
+988
+989
+990
+991
+992
+993
+994
+995
+996
+997
+998
+999
+1000
+1001
+1002
+1003
+1004
+1005
+1006
+1007
+1008
+1009
+1010
+1011
+1012
+1013
+1014
+1015
+1016
+1017
+1018
+1019
+1020
+1021
+1022
+1023
+1024
+1025
+1026
+1027
+1028
+1029
+1030
+1031
+1032
+1033
+1034
+1035
+1036
+1037
+1038
+1039
+1040
+1041
+1042
+1043
+1044
+1045
+1046
+1047
+1048
+1049
+1050
+1051
+1052
+1053
+1054
+1055
+1056
+1057
+1058
+1059
+1060
+1061
+1062
+1063
+1064
+1065
+1066
+1067
+1068
+1069
+1070
+1071
+1072
+1073
+1074
+1075
+1076
+1077
+1078
+1079
+1080
+1081
+1082
+1083
+1084
+1085
+1086
+1087
+1088
+1089
+1090
+1091
+1092
+1093
+1094
+1095
+1096
+1097
+1098
+1099
+1100
+1101
+1102
+1103
+1104
+1105
+1106
+1107
+1108
+1109
+1110
+1111
+1112
+1113
+1114
+1115
+1116
+1117
+1118
+1119
+1120
+1121
+1122
+1123
+1124
+1125
+1126
+1127
+1128
+1129
+1130
+1131
+1132
+1133
+1134
+1135
+1136
+1137
+1138
+1139
+1140
+1141
+1142
+1143
+1144
+1145
+1146
+1147
+1148
+1149
+1150
+1151
+1152
+1153
+1154
+1155
+1156
+1157
+1158
+1159
+1160
+1161
+1162
+1163
+1164
+1165
+1166
+1167
+1168
+1169
+1170
+1171
+1172
+1173
+1174
+1175
+1176
+1177
+1178
+1179
+1180
+1181
+1182
+1183
+1184
+1185
+1186
+1187
+1188
+1189
+1190
+1191
+1192
+1193
+1194
+1195
+1196
+1197
+1198
+1199
+1200
+1201
+1202
+1203
+1204
+1205
+1206
+1207
+1208
+1209
+1210
+1211
+1212
+1213
+1214
+1215
+1216
+1217
+1218
+1219
+1220
+1221
+1222
+1223
+1224
+1225
+1226
+1227
+1228
+1229
+1230
+1231
+1232
+1233
+1234
+1235
+1236
+1237
+1238
+1239
+1240
+1241
+1242
+1243
+1244
+1245
+1246
+1247
+1248
+1249
+1250
+1251
+1252
+1253
+1254
+1255
+1256
+1257
+1258
+1259
+1260
+1261
+1262
+1263
+1264
+1265
+1266
+1267
+1268
+1269
+1270
+1271
+1272
+1273
+1274
+1275
+1276
+1277
+1278
+1279
+1280
+1281
+1282
+1283
+1284
+1285
+1286
+1287
+1288
+1289
+1290
+1291
+1292
+1293
+1294
+1295
+1296
+1297
+1298
+1299
+1300
+1301
+1302
+1303
+1304
+1305
+1306
+1307
+1308
+1309
+1310
+1311
+1312
+1313
+1314
+1315
+1316
+1317
+1318
+1319
+1320
+1321
+1322
+1323
+1324
+1325
+1326
+1327
+1328
+1329
+1330
+1331
+1332
+1333
+1334
+1335
+1336
+1337
+1338
+1339
+1340
+1341
+1342
+1343
+1344
+1345
+1346
+1347
+1348
+1349
+1350
+1351
+1352
+1353
+1354
+1355
+1356
+1357
+1358
+1359
+1360
+1361
+1362
+1363
+1364
+1365
+1366
+1367
+1368
+1369
+1370
+1371
+1372
+1373
+1374
+1375
+1376
+1377
+1378
+1379
+1380
+1381
+
use core::{borrow::Borrow, fmt, iter::FromIterator, mem, num::NonZeroU32, ops, slice};
+
+use hash32::{BuildHasher, BuildHasherDefault, FnvHasher, Hash, Hasher};
+
+use crate::Vec;
+
+/// A [`heapless::IndexMap`](./struct.IndexMap.html) using the default FNV hasher
+///
+/// A list of all Methods and Traits available for `FnvIndexMap` can be found in
+/// the [`heapless::IndexMap`](./struct.IndexMap.html) documentation.
+///
+/// # Examples
+/// ```
+/// use heapless::FnvIndexMap;
+///
+/// // A hash map with a capacity of 16 key-value pairs allocated on the stack
+/// let mut book_reviews = FnvIndexMap::<_, _, 16>::new();
+///
+/// // review some books.
+/// book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.").unwrap();
+/// book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.").unwrap();
+/// book_reviews.insert("Pride and Prejudice",               "Very enjoyable.").unwrap();
+/// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.").unwrap();
+///
+/// // check for a specific one.
+/// if !book_reviews.contains_key("Les Misérables") {
+///     println!("We've got {} reviews, but Les Misérables ain't one.",
+///              book_reviews.len());
+/// }
+///
+/// // oops, this review has a lot of spelling mistakes, let's delete it.
+/// book_reviews.remove("The Adventures of Sherlock Holmes");
+///
+/// // look up the values associated with some keys.
+/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
+/// for book in &to_find {
+///     match book_reviews.get(book) {
+///         Some(review) => println!("{}: {}", book, review),
+///         None => println!("{} is unreviewed.", book)
+///     }
+/// }
+///
+/// // iterate over everything.
+/// for (book, review) in &book_reviews {
+///     println!("{}: \"{}\"", book, review);
+/// }
+/// ```
+pub type FnvIndexMap<K, V, const N: usize> = IndexMap<K, V, BuildHasherDefault<FnvHasher>, N>;
+
+#[derive(Clone, Copy, Eq, PartialEq)]
+struct HashValue(u16);
+
+impl HashValue {
+    fn desired_pos(&self, mask: usize) -> usize {
+        usize::from(self.0) & mask
+    }
+
+    fn probe_distance(&self, mask: usize, current: usize) -> usize {
+        current.wrapping_sub(self.desired_pos(mask) as usize) & mask
+    }
+}
+
+#[doc(hidden)]
+#[derive(Clone)]
+pub struct Bucket<K, V> {
+    hash: HashValue,
+    key: K,
+    value: V,
+}
+
+#[doc(hidden)]
+#[derive(Clone, Copy, PartialEq)]
+pub struct Pos {
+    // compact representation of `{ hash_value: u16, index: u16 }`
+    // To get the most from `NonZero` we store the *value minus 1*. This way `None::Option<Pos>`
+    // is equivalent to the very unlikely value of  `{ hash_value: 0xffff, index: 0xffff }` instead
+    // the more likely of `{ hash_value: 0x00, index: 0x00 }`
+    nz: NonZeroU32,
+}
+
+impl Pos {
+    fn new(index: usize, hash: HashValue) -> Self {
+        Pos {
+            nz: unsafe {
+                NonZeroU32::new_unchecked(
+                    ((u32::from(hash.0) << 16) + index as u32).wrapping_add(1),
+                )
+            },
+        }
+    }
+
+    fn hash(&self) -> HashValue {
+        HashValue((self.nz.get().wrapping_sub(1) >> 16) as u16)
+    }
+
+    fn index(&self) -> usize {
+        self.nz.get().wrapping_sub(1) as u16 as usize
+    }
+}
+
+enum Insert<K, V> {
+    Success(Inserted<V>),
+    Full((K, V)),
+}
+struct Inserted<V> {
+    index: usize,
+    old_value: Option<V>,
+}
+
+macro_rules! probe_loop {
+    ($probe_var: ident < $len: expr, $body: expr) => {
+        loop {
+            if $probe_var < $len {
+                $body
+                    $probe_var += 1;
+            } else {
+                $probe_var = 0;
+            }
+        }
+    }
+}
+
+struct CoreMap<K, V, const N: usize> {
+    entries: Vec<Bucket<K, V>, N>,
+    indices: [Option<Pos>; N],
+}
+
+impl<K, V, const N: usize> CoreMap<K, V, N> {
+    const fn new() -> Self {
+        const INIT: Option<Pos> = None;
+
+        CoreMap {
+            entries: Vec::new(),
+            indices: [INIT; N],
+        }
+    }
+}
+
+impl<K, V, const N: usize> CoreMap<K, V, N>
+where
+    K: Eq + Hash,
+{
+    fn capacity() -> usize {
+        N
+    }
+
+    fn mask() -> usize {
+        Self::capacity() - 1
+    }
+
+    fn find<Q>(&self, hash: HashValue, query: &Q) -> Option<(usize, usize)>
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Eq,
+    {
+        let mut probe = hash.desired_pos(Self::mask());
+        let mut dist = 0;
+
+        probe_loop!(probe < self.indices.len(), {
+            if let Some(pos) = self.indices[probe] {
+                let entry_hash = pos.hash();
+                // NOTE(i) we use unchecked indexing below
+                let i = pos.index();
+                debug_assert!(i < self.entries.len());
+
+                if dist > entry_hash.probe_distance(Self::mask(), probe) {
+                    // give up when probe distance is too long
+                    return None;
+                } else if entry_hash == hash
+                    && unsafe { self.entries.get_unchecked(i).key.borrow() == query }
+                {
+                    return Some((probe, i));
+                }
+            } else {
+                return None;
+            }
+
+            dist += 1;
+        });
+    }
+
+    fn insert(&mut self, hash: HashValue, key: K, value: V) -> Insert<K, V> {
+        let mut probe = hash.desired_pos(Self::mask());
+        let mut dist = 0;
+
+        probe_loop!(probe < self.indices.len(), {
+            let pos = &mut self.indices[probe];
+
+            if let Some(pos) = *pos {
+                let entry_hash = pos.hash();
+                // NOTE(i) we use unchecked indexing below
+                let i = pos.index();
+                debug_assert!(i < self.entries.len());
+
+                let their_dist = entry_hash.probe_distance(Self::mask(), probe);
+
+                if their_dist < dist {
+                    if self.entries.is_full() {
+                        return Insert::Full((key, value));
+                    }
+                    // robin hood: steal the spot if it's better for us
+                    let index = self.entries.len();
+                    unsafe { self.entries.push_unchecked(Bucket { hash, key, value }) };
+                    return Insert::Success(Inserted {
+                        index: self.insert_phase_2(probe, Pos::new(index, hash)),
+                        old_value: None,
+                    });
+                } else if entry_hash == hash && unsafe { self.entries.get_unchecked(i).key == key }
+                {
+                    return Insert::Success(Inserted {
+                        index: i,
+                        old_value: Some(mem::replace(
+                            unsafe { &mut self.entries.get_unchecked_mut(i).value },
+                            value,
+                        )),
+                    });
+                }
+            } else {
+                if self.entries.is_full() {
+                    return Insert::Full((key, value));
+                }
+                // empty bucket, insert here
+                let index = self.entries.len();
+                *pos = Some(Pos::new(index, hash));
+                unsafe { self.entries.push_unchecked(Bucket { hash, key, value }) };
+                return Insert::Success(Inserted {
+                    index,
+                    old_value: None,
+                });
+            }
+            dist += 1;
+        });
+    }
+
+    // phase 2 is post-insert where we forward-shift `Pos` in the indices.
+    fn insert_phase_2(&mut self, mut probe: usize, mut old_pos: Pos) -> usize {
+        probe_loop!(probe < self.indices.len(), {
+            let pos = unsafe { self.indices.get_unchecked_mut(probe) };
+
+            let mut is_none = true; // work around lack of NLL
+            if let Some(pos) = pos.as_mut() {
+                old_pos = mem::replace(pos, old_pos);
+                is_none = false;
+            }
+
+            if is_none {
+                *pos = Some(old_pos);
+                return probe;
+            }
+        });
+    }
+
+    fn remove_found(&mut self, probe: usize, found: usize) -> (K, V) {
+        // index `probe` and entry `found` is to be removed
+        // use swap_remove, but then we need to update the index that points
+        // to the other entry that has to move
+        self.indices[probe] = None;
+        let entry = unsafe { self.entries.swap_remove_unchecked(found) };
+
+        // correct index that points to the entry that had to swap places
+        if let Some(entry) = self.entries.get(found) {
+            // was not last element
+            // examine new element in `found` and find it in indices
+            let mut probe = entry.hash.desired_pos(Self::mask());
+
+            probe_loop!(probe < self.indices.len(), {
+                if let Some(pos) = self.indices[probe] {
+                    if pos.index() >= self.entries.len() {
+                        // found it
+                        self.indices[probe] = Some(Pos::new(found, entry.hash));
+                        break;
+                    }
+                }
+            });
+        }
+
+        self.backward_shift_after_removal(probe);
+
+        (entry.key, entry.value)
+    }
+
+    fn backward_shift_after_removal(&mut self, probe_at_remove: usize) {
+        // backward shift deletion in self.indices
+        // after probe, shift all non-ideally placed indices backward
+        let mut last_probe = probe_at_remove;
+        let mut probe = probe_at_remove + 1;
+
+        probe_loop!(probe < self.indices.len(), {
+            if let Some(pos) = self.indices[probe] {
+                let entry_hash = pos.hash();
+
+                if entry_hash.probe_distance(Self::mask(), probe) > 0 {
+                    unsafe { *self.indices.get_unchecked_mut(last_probe) = self.indices[probe] }
+                    self.indices[probe] = None;
+                } else {
+                    break;
+                }
+            } else {
+                break;
+            }
+            last_probe = probe;
+        });
+    }
+}
+
+impl<K, V, const N: usize> Clone for CoreMap<K, V, N>
+where
+    K: Eq + Hash + Clone,
+    V: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            entries: self.entries.clone(),
+            indices: self.indices.clone(),
+        }
+    }
+}
+
+/// A view into an entry in the map
+pub enum Entry<'a, K, V, const N: usize> {
+    /// The entry corresponding to the key `K` exists in the map
+    Occupied(OccupiedEntry<'a, K, V, N>),
+    /// The entry corresponding to the key `K` does not exist in the map
+    Vacant(VacantEntry<'a, K, V, N>),
+}
+
+/// An occupied entry which can be manipulated
+pub struct OccupiedEntry<'a, K, V, const N: usize> {
+    key: K,
+    probe: usize,
+    pos: usize,
+    core: &'a mut CoreMap<K, V, N>,
+}
+
+impl<'a, K, V, const N: usize> OccupiedEntry<'a, K, V, N>
+where
+    K: Eq + Hash,
+{
+    /// Gets a reference to the key that this entity corresponds to
+    pub fn key(&self) -> &K {
+        &self.key
+    }
+
+    /// Removes this entry from the map and yields its corresponding key and value
+    pub fn remove_entry(self) -> (K, V) {
+        self.core.remove_found(self.probe, self.pos)
+    }
+
+    /// Gets a reference to the value associated with this entry
+    pub fn get(&self) -> &V {
+        // SAFETY: Already checked existence at instantiation and the only mutable reference
+        // to the map is internally held.
+        unsafe { &self.core.entries.get_unchecked(self.pos).value }
+    }
+
+    /// Gets a mutable reference to the value associated with this entry
+    pub fn get_mut(&mut self) -> &mut V {
+        // SAFETY: Already checked existence at instantiation and the only mutable reference
+        // to the map is internally held.
+        unsafe { &mut self.core.entries.get_unchecked_mut(self.pos).value }
+    }
+
+    /// Consumes this entry and yields a reference to the underlying value
+    pub fn into_mut(self) -> &'a mut V {
+        // SAFETY: Already checked existence at instantiation and the only mutable reference
+        // to the map is internally held.
+        unsafe { &mut self.core.entries.get_unchecked_mut(self.pos).value }
+    }
+
+    /// Overwrites the underlying map's value with this entry's value
+    pub fn insert(self, value: V) -> V {
+        // SAFETY: Already checked existence at instantiation and the only mutable reference
+        // to the map is internally held.
+        unsafe {
+            mem::replace(
+                &mut self.core.entries.get_unchecked_mut(self.pos).value,
+                value,
+            )
+        }
+    }
+
+    /// Removes this entry from the map and yields its value
+    pub fn remove(self) -> V {
+        self.remove_entry().1
+    }
+}
+
+/// A view into an empty slot in the underlying map
+pub struct VacantEntry<'a, K, V, const N: usize> {
+    key: K,
+    hash_val: HashValue,
+    core: &'a mut CoreMap<K, V, N>,
+}
+impl<'a, K, V, const N: usize> VacantEntry<'a, K, V, N>
+where
+    K: Eq + Hash,
+{
+    /// Get the key associated with this entry
+    pub fn key(&self) -> &K {
+        &self.key
+    }
+
+    /// Consumes this entry to yield to key associated with it
+    pub fn into_key(self) -> K {
+        self.key
+    }
+
+    /// Inserts this entry into to underlying map, yields a mutable reference to the inserted value.
+    /// If the map is at capacity the value is returned instead.
+    pub fn insert(self, value: V) -> Result<&'a mut V, V> {
+        if self.core.entries.is_full() {
+            Err(value)
+        } else {
+            match self.core.insert(self.hash_val, self.key, value) {
+                Insert::Success(inserted) => {
+                    unsafe {
+                        // SAFETY: Already checked existence at instantiation and the only mutable reference
+                        // to the map is internally held.
+                        Ok(&mut (*self.core.entries.as_mut_ptr().add(inserted.index)).value)
+                    }
+                }
+                Insert::Full((_, v)) => Err(v),
+            }
+        }
+    }
+}
+
+/// Fixed capacity [`IndexMap`](https://docs.rs/indexmap/1/indexmap/map/struct.IndexMap.html)
+///
+/// Note that you cannot use `IndexMap` directly, since it is generic around the hashing algorithm
+/// in use. Pick a concrete instantiation like [`FnvIndexMap`](./type.FnvIndexMap.html) instead
+/// or create your own.
+///
+/// Note that the capacity of the `IndexMap` must be a power of 2.
+///
+/// # Examples
+/// Since `IndexMap` cannot be used directly, we're using its `FnvIndexMap` instantiation
+/// for this example.
+///
+/// ```
+/// use heapless::FnvIndexMap;
+///
+/// // A hash map with a capacity of 16 key-value pairs allocated on the stack
+/// let mut book_reviews = FnvIndexMap::<_, _, 16>::new();
+///
+/// // review some books.
+/// book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.").unwrap();
+/// book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.").unwrap();
+/// book_reviews.insert("Pride and Prejudice",               "Very enjoyable.").unwrap();
+/// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.").unwrap();
+///
+/// // check for a specific one.
+/// if !book_reviews.contains_key("Les Misérables") {
+///     println!("We've got {} reviews, but Les Misérables ain't one.",
+///              book_reviews.len());
+/// }
+///
+/// // oops, this review has a lot of spelling mistakes, let's delete it.
+/// book_reviews.remove("The Adventures of Sherlock Holmes");
+///
+/// // look up the values associated with some keys.
+/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
+/// for book in &to_find {
+///     match book_reviews.get(book) {
+///         Some(review) => println!("{}: {}", book, review),
+///         None => println!("{} is unreviewed.", book)
+///     }
+/// }
+///
+/// // iterate over everything.
+/// for (book, review) in &book_reviews {
+///     println!("{}: \"{}\"", book, review);
+/// }
+/// ```
+pub struct IndexMap<K, V, S, const N: usize> {
+    core: CoreMap<K, V, N>,
+    build_hasher: S,
+}
+
+impl<K, V, S, const N: usize> IndexMap<K, V, BuildHasherDefault<S>, N> {
+    /// Creates an empty `IndexMap`.
+    pub const fn new() -> Self {
+        // Const assert
+        crate::sealed::greater_than_1::<N>();
+        crate::sealed::power_of_two::<N>();
+
+        IndexMap {
+            build_hasher: BuildHasherDefault::new(),
+            core: CoreMap::new(),
+        }
+    }
+}
+
+impl<K, V, S, const N: usize> IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher,
+{
+    /* Public API */
+    /// Returns the number of elements the map can hold
+    pub fn capacity(&self) -> usize {
+        N
+    }
+
+    /// Return an iterator over the keys of the map, in their order
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for key in map.keys() {
+    ///     println!("{}", key);
+    /// }
+    /// ```
+    pub fn keys(&self) -> impl Iterator<Item = &K> {
+        self.core.entries.iter().map(|bucket| &bucket.key)
+    }
+
+    /// Return an iterator over the values of the map, in their order
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for val in map.values() {
+    ///     println!("{}", val);
+    /// }
+    /// ```
+    pub fn values(&self) -> impl Iterator<Item = &V> {
+        self.core.entries.iter().map(|bucket| &bucket.value)
+    }
+
+    /// Return an iterator over mutable references to the the values of the map, in their order
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for val in map.values_mut() {
+    ///     *val += 10;
+    /// }
+    ///
+    /// for val in map.values() {
+    ///     println!("{}", val);
+    /// }
+    /// ```
+    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
+        self.core.entries.iter_mut().map(|bucket| &mut bucket.value)
+    }
+
+    /// Return an iterator over the key-value pairs of the map, in their order
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for (key, val) in map.iter() {
+    ///     println!("key: {} val: {}", key, val);
+    /// }
+    /// ```
+    pub fn iter(&self) -> Iter<'_, K, V> {
+        Iter {
+            iter: self.core.entries.iter(),
+        }
+    }
+
+    /// Return an iterator over the key-value pairs of the map, in their order
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for (_, val) in map.iter_mut() {
+    ///     *val = 2;
+    /// }
+    ///
+    /// for (key, val) in &map {
+    ///     println!("key: {} val: {}", key, val);
+    /// }
+    /// ```
+    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
+        IterMut {
+            iter: self.core.entries.iter_mut(),
+        }
+    }
+
+    /// Get the first key-value pair
+    ///
+    /// Computes in **O(1)** time
+    pub fn first(&self) -> Option<(&K, &V)> {
+        self.core
+            .entries
+            .first()
+            .map(|bucket| (&bucket.key, &bucket.value))
+    }
+
+    /// Get the first key-value pair, with mutable access to the value
+    ///
+    /// Computes in **O(1)** time
+    pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
+        self.core
+            .entries
+            .first_mut()
+            .map(|bucket| (&bucket.key, &mut bucket.value))
+    }
+
+    /// Get the last key-value pair
+    ///
+    /// Computes in **O(1)** time
+    pub fn last(&self) -> Option<(&K, &V)> {
+        self.core
+            .entries
+            .last()
+            .map(|bucket| (&bucket.key, &bucket.value))
+    }
+
+    /// Get the last key-value pair, with mutable access to the value
+    ///
+    /// Computes in **O(1)** time
+    pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
+        self.core
+            .entries
+            .last_mut()
+            .map(|bucket| (&bucket.key, &mut bucket.value))
+    }
+
+    /// Returns an entry for the corresponding key
+    /// ```
+    /// use heapless::FnvIndexMap;
+    /// use heapless::Entry;
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// if let Entry::Vacant(v) = map.entry("a") {
+    ///     v.insert(1).unwrap();
+    /// }
+    /// if let Entry::Occupied(mut o) = map.entry("a") {
+    ///     println!("found {}", *o.get()); // Prints 1
+    ///     o.insert(2);
+    /// }
+    /// // Prints 2
+    /// println!("val: {}", *map.get("a").unwrap());
+    /// ```
+    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, N> {
+        let hash_val = hash_with(&key, &self.build_hasher);
+        if let Some((probe, pos)) = self.core.find(hash_val, &key) {
+            Entry::Occupied(OccupiedEntry {
+                key,
+                probe,
+                pos,
+                core: &mut self.core,
+            })
+        } else {
+            Entry::Vacant(VacantEntry {
+                key,
+                hash_val,
+                core: &mut self.core,
+            })
+        }
+    }
+
+    /// Return the number of key-value pairs in the map.
+    ///
+    /// Computes in **O(1)** time.
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut a = FnvIndexMap::<_, _, 16>::new();
+    /// assert_eq!(a.len(), 0);
+    /// a.insert(1, "a").unwrap();
+    /// assert_eq!(a.len(), 1);
+    /// ```
+    pub fn len(&self) -> usize {
+        self.core.entries.len()
+    }
+
+    /// Returns true if the map contains no elements.
+    ///
+    /// Computes in **O(1)** time.
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut a = FnvIndexMap::<_, _, 16>::new();
+    /// assert!(a.is_empty());
+    /// a.insert(1, "a");
+    /// assert!(!a.is_empty());
+    /// ```
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    /// Remove all key-value pairs in the map, while preserving its capacity.
+    ///
+    /// Computes in **O(n)** time.
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut a = FnvIndexMap::<_, _, 16>::new();
+    /// a.insert(1, "a");
+    /// a.clear();
+    /// assert!(a.is_empty());
+    /// ```
+    pub fn clear(&mut self) {
+        self.core.entries.clear();
+        for pos in self.core.indices.iter_mut() {
+            *pos = None;
+        }
+    }
+
+    /// Returns a reference to the value corresponding to the key.
+    ///
+    /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
+    /// form *must* match those for the key type.
+    ///
+    /// Computes in **O(1)** time (average).
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 16>::new();
+    /// map.insert(1, "a").unwrap();
+    /// assert_eq!(map.get(&1), Some(&"a"));
+    /// assert_eq!(map.get(&2), None);
+    /// ```
+    pub fn get<Q>(&self, key: &Q) -> Option<&V>
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Hash + Eq,
+    {
+        self.find(key)
+            .map(|(_, found)| unsafe { &self.core.entries.get_unchecked(found).value })
+    }
+
+    /// Returns true if the map contains a value for the specified key.
+    ///
+    /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
+    /// form *must* match those for the key type.
+    ///
+    /// Computes in **O(1)** time (average).
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 8>::new();
+    /// map.insert(1, "a").unwrap();
+    /// assert_eq!(map.contains_key(&1), true);
+    /// assert_eq!(map.contains_key(&2), false);
+    /// ```
+    pub fn contains_key<Q>(&self, key: &Q) -> bool
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Eq + Hash,
+    {
+        self.find(key).is_some()
+    }
+
+    /// Returns a mutable reference to the value corresponding to the key.
+    ///
+    /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
+    /// form *must* match those for the key type.
+    ///
+    /// Computes in **O(1)** time (average).
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 8>::new();
+    /// map.insert(1, "a").unwrap();
+    /// if let Some(x) = map.get_mut(&1) {
+    ///     *x = "b";
+    /// }
+    /// assert_eq!(map[&1], "b");
+    /// ```
+    pub fn get_mut<'v, Q>(&'v mut self, key: &Q) -> Option<&'v mut V>
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Hash + Eq,
+    {
+        if let Some((_, found)) = self.find(key) {
+            Some(unsafe { &mut self.core.entries.get_unchecked_mut(found).value })
+        } else {
+            None
+        }
+    }
+
+    /// Inserts a key-value pair into the map.
+    ///
+    /// If an equivalent key already exists in the map: the key remains and retains in its place in
+    /// the order, its corresponding value is updated with `value` and the older value is returned
+    /// inside `Some(_)`.
+    ///
+    /// If no equivalent key existed in the map: the new key-value pair is inserted, last in order,
+    /// and `None` is returned.
+    ///
+    /// Computes in **O(1)** time (average).
+    ///
+    /// See also entry if you you want to insert or modify or if you need to get the index of the
+    /// corresponding key-value pair.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 8>::new();
+    /// assert_eq!(map.insert(37, "a"), Ok(None));
+    /// assert_eq!(map.is_empty(), false);
+    ///
+    /// map.insert(37, "b");
+    /// assert_eq!(map.insert(37, "c"), Ok(Some("b")));
+    /// assert_eq!(map[&37], "c");
+    /// ```
+    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)> {
+        let hash = hash_with(&key, &self.build_hasher);
+        match self.core.insert(hash, key, value) {
+            Insert::Success(inserted) => Ok(inserted.old_value),
+            Insert::Full((k, v)) => Err((k, v)),
+        }
+    }
+
+    /// Same as [`swap_remove`](struct.IndexMap.html#method.swap_remove)
+    ///
+    /// Computes in **O(1)** time (average).
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexMap;
+    ///
+    /// let mut map = FnvIndexMap::<_, _, 8>::new();
+    /// map.insert(1, "a").unwrap();
+    /// assert_eq!(map.remove(&1), Some("a"));
+    /// assert_eq!(map.remove(&1), None);
+    /// ```
+    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Hash + Eq,
+    {
+        self.swap_remove(key)
+    }
+
+    /// Remove the key-value pair equivalent to `key` and return its value.
+    ///
+    /// Like `Vec::swap_remove`, the pair is removed by swapping it with the last element of the map
+    /// and popping it off. **This perturbs the postion of what used to be the last element!**
+    ///
+    /// Return `None` if `key` is not in map.
+    ///
+    /// Computes in **O(1)** time (average).
+    pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Hash + Eq,
+    {
+        self.find(key)
+            .map(|(probe, found)| self.core.remove_found(probe, found).1)
+    }
+
+    /* Private API */
+    /// Return probe (indices) and position (entries)
+    fn find<Q>(&self, key: &Q) -> Option<(usize, usize)>
+    where
+        K: Borrow<Q>,
+        Q: ?Sized + Hash + Eq,
+    {
+        if self.len() == 0 {
+            return None;
+        }
+        let h = hash_with(key, &self.build_hasher);
+        self.core.find(h, key)
+    }
+}
+
+impl<'a, K, Q, V, S, const N: usize> ops::Index<&'a Q> for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash + Borrow<Q>,
+    Q: ?Sized + Eq + Hash,
+    S: BuildHasher,
+{
+    type Output = V;
+
+    fn index(&self, key: &Q) -> &V {
+        self.get(key).expect("key not found")
+    }
+}
+
+impl<'a, K, Q, V, S, const N: usize> ops::IndexMut<&'a Q> for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash + Borrow<Q>,
+    Q: ?Sized + Eq + Hash,
+    S: BuildHasher,
+{
+    fn index_mut(&mut self, key: &Q) -> &mut V {
+        self.get_mut(key).expect("key not found")
+    }
+}
+
+impl<K, V, S, const N: usize> Clone for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash + Clone,
+    V: Clone,
+    S: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            core: self.core.clone(),
+            build_hasher: self.build_hasher.clone(),
+        }
+    }
+}
+
+impl<K, V, S, const N: usize> fmt::Debug for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash + fmt::Debug,
+    V: fmt::Debug,
+    S: BuildHasher,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_map().entries(self.iter()).finish()
+    }
+}
+
+impl<K, V, S, const N: usize> Default for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher + Default,
+{
+    fn default() -> Self {
+        // Const assert
+        crate::sealed::greater_than_1::<N>();
+        crate::sealed::power_of_two::<N>();
+
+        IndexMap {
+            build_hasher: <_>::default(),
+            core: CoreMap::new(),
+        }
+    }
+}
+
+impl<K, V, S, S2, const N: usize, const N2: usize> PartialEq<IndexMap<K, V, S2, N2>>
+    for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    V: Eq,
+    S: BuildHasher,
+    S2: BuildHasher,
+{
+    fn eq(&self, other: &IndexMap<K, V, S2, N2>) -> bool {
+        self.len() == other.len()
+            && self
+                .iter()
+                .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
+    }
+}
+
+impl<K, V, S, const N: usize> Eq for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    V: Eq,
+    S: BuildHasher,
+{
+}
+
+impl<K, V, S, const N: usize> Extend<(K, V)> for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher,
+{
+    fn extend<I>(&mut self, iterable: I)
+    where
+        I: IntoIterator<Item = (K, V)>,
+    {
+        for (k, v) in iterable {
+            self.insert(k, v).ok().unwrap();
+        }
+    }
+}
+
+impl<'a, K, V, S, const N: usize> Extend<(&'a K, &'a V)> for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash + Copy,
+    V: Copy,
+    S: BuildHasher,
+{
+    fn extend<I>(&mut self, iterable: I)
+    where
+        I: IntoIterator<Item = (&'a K, &'a V)>,
+    {
+        self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)))
+    }
+}
+
+impl<K, V, S, const N: usize> FromIterator<(K, V)> for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher + Default,
+{
+    fn from_iter<I>(iterable: I) -> Self
+    where
+        I: IntoIterator<Item = (K, V)>,
+    {
+        let mut map = IndexMap::default();
+        map.extend(iterable);
+        map
+    }
+}
+
+#[derive(Clone)]
+pub struct IntoIter<K, V, const N: usize> {
+    entries: Vec<Bucket<K, V>, N>,
+}
+
+impl<K, V, const N: usize> Iterator for IntoIter<K, V, N> {
+    type Item = (K, V);
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.entries.pop().map(|bucket| (bucket.key, bucket.value))
+    }
+}
+
+impl<K, V, S, const N: usize> IntoIterator for IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher,
+{
+    type Item = (K, V);
+    type IntoIter = IntoIter<K, V, N>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        IntoIter {
+            entries: self.core.entries,
+        }
+    }
+}
+
+impl<'a, K, V, S, const N: usize> IntoIterator for &'a IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher,
+{
+    type Item = (&'a K, &'a V);
+    type IntoIter = Iter<'a, K, V>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl<'a, K, V, S, const N: usize> IntoIterator for &'a mut IndexMap<K, V, S, N>
+where
+    K: Eq + Hash,
+    S: BuildHasher,
+{
+    type Item = (&'a K, &'a mut V);
+    type IntoIter = IterMut<'a, K, V>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter_mut()
+    }
+}
+
+pub struct Iter<'a, K, V> {
+    iter: slice::Iter<'a, Bucket<K, V>>,
+}
+
+impl<'a, K, V> Iterator for Iter<'a, K, V> {
+    type Item = (&'a K, &'a V);
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.iter.next().map(|bucket| (&bucket.key, &bucket.value))
+    }
+}
+
+impl<'a, K, V> Clone for Iter<'a, K, V> {
+    fn clone(&self) -> Self {
+        Self {
+            iter: self.iter.clone(),
+        }
+    }
+}
+
+pub struct IterMut<'a, K, V> {
+    iter: slice::IterMut<'a, Bucket<K, V>>,
+}
+
+impl<'a, K, V> Iterator for IterMut<'a, K, V> {
+    type Item = (&'a K, &'a mut V);
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.iter
+            .next()
+            .map(|bucket| (&bucket.key, &mut bucket.value))
+    }
+}
+
+fn hash_with<K, S>(key: &K, build_hasher: &S) -> HashValue
+where
+    K: ?Sized + Hash,
+    S: BuildHasher,
+{
+    let mut h = build_hasher.build_hasher();
+    key.hash(&mut h);
+    HashValue(h.finish() as u16)
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::{indexmap::Entry, FnvIndexMap};
+
+    use core::mem;
+
+    #[test]
+    fn size() {
+        const CAP: usize = 4;
+        assert_eq!(
+            mem::size_of::<FnvIndexMap<i16, u16, CAP>>(),
+            CAP * mem::size_of::<u32>() + // indices
+                CAP * (mem::size_of::<i16>() + // key
+                     mem::size_of::<u16>() + // value
+                     mem::size_of::<u16>() // hash
+                ) + // buckets
+                mem::size_of::<usize>() // entries.length
+        )
+    }
+
+    #[test]
+    fn partial_eq() {
+        {
+            let mut a: FnvIndexMap<_, _, 4> = FnvIndexMap::new();
+            a.insert("k1", "v1").unwrap();
+
+            let mut b: FnvIndexMap<_, _, 4> = FnvIndexMap::new();
+            b.insert("k1", "v1").unwrap();
+
+            assert!(a == b);
+
+            b.insert("k2", "v2").unwrap();
+
+            assert!(a != b);
+        }
+
+        {
+            let mut a: FnvIndexMap<_, _, 4> = FnvIndexMap::new();
+            a.insert("k1", "v1").unwrap();
+            a.insert("k2", "v2").unwrap();
+
+            let mut b: FnvIndexMap<_, _, 4> = FnvIndexMap::new();
+            b.insert("k2", "v2").unwrap();
+            b.insert("k1", "v1").unwrap();
+
+            assert!(a == b);
+        }
+    }
+
+    #[test]
+    fn into_iter() {
+        let mut src: FnvIndexMap<_, _, 4> = FnvIndexMap::new();
+        src.insert("k1", "v1").unwrap();
+        src.insert("k2", "v2").unwrap();
+        src.insert("k3", "v3").unwrap();
+        src.insert("k4", "v4").unwrap();
+        let clone = src.clone();
+        for (k, v) in clone.into_iter() {
+            assert_eq!(v, *src.get(k).unwrap());
+        }
+    }
+
+    #[test]
+    fn insert_replaces_on_full_map() {
+        let mut a: FnvIndexMap<_, _, 2> = FnvIndexMap::new();
+        a.insert("k1", "v1").unwrap();
+        a.insert("k2", "v2").unwrap();
+        a.insert("k1", "v2").unwrap();
+        assert_eq!(a.get("k1"), a.get("k2"));
+    }
+
+    const MAP_SLOTS: usize = 4096;
+    fn almost_filled_map() -> FnvIndexMap<usize, usize, MAP_SLOTS> {
+        let mut almost_filled = FnvIndexMap::new();
+        for i in 1..MAP_SLOTS {
+            almost_filled.insert(i, i).unwrap();
+        }
+        almost_filled
+    }
+
+    #[test]
+    fn entry_find() {
+        let key = 0;
+        let value = 0;
+        let mut src = almost_filled_map();
+        let entry = src.entry(key);
+        match entry {
+            Entry::Occupied(_) => {
+                panic!("Found entry without inserting");
+            }
+            Entry::Vacant(v) => {
+                assert_eq!(&key, v.key());
+                assert_eq!(key, v.into_key());
+            }
+        }
+        src.insert(key, value).unwrap();
+        let entry = src.entry(key);
+        match entry {
+            Entry::Occupied(mut o) => {
+                assert_eq!(&key, o.key());
+                assert_eq!(&value, o.get());
+                assert_eq!(&value, o.get_mut());
+                assert_eq!(&value, o.into_mut());
+            }
+            Entry::Vacant(_) => {
+                panic!("Entry not found");
+            }
+        }
+    }
+
+    #[test]
+    fn entry_vacant_insert() {
+        let key = 0;
+        let value = 0;
+        let mut src = almost_filled_map();
+        assert_eq!(MAP_SLOTS - 1, src.len());
+        let entry = src.entry(key);
+        match entry {
+            Entry::Occupied(_) => {
+                panic!("Entry found when empty");
+            }
+            Entry::Vacant(v) => {
+                v.insert(value).unwrap();
+            }
+        };
+        assert_eq!(value, *src.get(&key).unwrap())
+    }
+
+    #[test]
+    fn entry_occupied_insert() {
+        let key = 0;
+        let value = 0;
+        let value2 = 5;
+        let mut src = almost_filled_map();
+        assert_eq!(MAP_SLOTS - 1, src.len());
+        src.insert(key, value).unwrap();
+        let entry = src.entry(key);
+        match entry {
+            Entry::Occupied(o) => {
+                assert_eq!(value, o.insert(value2));
+            }
+            Entry::Vacant(_) => {
+                panic!("Entry not found");
+            }
+        };
+        assert_eq!(value2, *src.get(&key).unwrap())
+    }
+
+    #[test]
+    fn entry_remove_entry() {
+        let key = 0;
+        let value = 0;
+        let mut src = almost_filled_map();
+        src.insert(key, value).unwrap();
+        assert_eq!(MAP_SLOTS, src.len());
+        let entry = src.entry(key);
+        match entry {
+            Entry::Occupied(o) => {
+                assert_eq!((key, value), o.remove_entry());
+            }
+            Entry::Vacant(_) => {
+                panic!("Entry not found")
+            }
+        };
+        assert_eq!(MAP_SLOTS - 1, src.len());
+    }
+
+    #[test]
+    fn entry_remove() {
+        let key = 0;
+        let value = 0;
+        let mut src = almost_filled_map();
+        src.insert(key, value).unwrap();
+        assert_eq!(MAP_SLOTS, src.len());
+        let entry = src.entry(key);
+        match entry {
+            Entry::Occupied(o) => {
+                assert_eq!(value, o.remove());
+            }
+            Entry::Vacant(_) => {
+                panic!("Entry not found");
+            }
+        };
+        assert_eq!(MAP_SLOTS - 1, src.len());
+    }
+
+    #[test]
+    fn entry_roll_through_all() {
+        let mut src: FnvIndexMap<usize, usize, MAP_SLOTS> = FnvIndexMap::new();
+        for i in 0..MAP_SLOTS {
+            match src.entry(i) {
+                Entry::Occupied(_) => {
+                    panic!("Entry found before insert");
+                }
+                Entry::Vacant(v) => {
+                    v.insert(i).unwrap();
+                }
+            }
+        }
+        let add_mod = 99;
+        for i in 0..MAP_SLOTS {
+            match src.entry(i) {
+                Entry::Occupied(o) => {
+                    assert_eq!(i, o.insert(i + add_mod));
+                }
+                Entry::Vacant(_) => {
+                    panic!("Entry not found after insert");
+                }
+            }
+        }
+        for i in 0..MAP_SLOTS {
+            match src.entry(i) {
+                Entry::Occupied(o) => {
+                    assert_eq!((i, i + add_mod), o.remove_entry());
+                }
+                Entry::Vacant(_) => {
+                    panic!("Entry not found after insert");
+                }
+            }
+        }
+        for i in 0..MAP_SLOTS {
+            assert!(matches!(src.entry(i), Entry::Vacant(_)));
+        }
+        assert!(src.is_empty());
+    }
+
+    #[test]
+    fn first_last() {
+        let mut map = FnvIndexMap::<_, _, 4>::new();
+
+        assert_eq!(None, map.first());
+        assert_eq!(None, map.last());
+
+        map.insert(0, 0).unwrap();
+        map.insert(2, 2).unwrap();
+
+        assert_eq!(Some((&0, &0)), map.first());
+        assert_eq!(Some((&2, &2)), map.last());
+
+        map.insert(1, 1).unwrap();
+
+        assert_eq!(Some((&1, &1)), map.last());
+
+        *map.first_mut().unwrap().1 += 1;
+        *map.last_mut().unwrap().1 += 1;
+
+        assert_eq!(Some((&0, &1)), map.first());
+        assert_eq!(Some((&1, &2)), map.last());
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/indexset.rs.html b/docs/doc/src/heapless/indexset.rs.html new file mode 100644 index 0000000..56abc13 --- /dev/null +++ b/docs/doc/src/heapless/indexset.rs.html @@ -0,0 +1,1279 @@ +indexset.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+
use crate::indexmap::{self, IndexMap};
+use core::{borrow::Borrow, fmt, iter::FromIterator};
+use hash32::{BuildHasher, BuildHasherDefault, FnvHasher, Hash};
+
+/// A [`heapless::IndexSet`](./struct.IndexSet.html) using the
+/// default FNV hasher.
+/// A list of all Methods and Traits available for `FnvIndexSet` can be found in
+/// the [`heapless::IndexSet`](./struct.IndexSet.html) documentation.
+///
+/// # Examples
+/// ```
+/// use heapless::FnvIndexSet;
+///
+/// // A hash set with a capacity of 16 elements allocated on the stack
+/// let mut books = FnvIndexSet::<_, 16>::new();
+///
+/// // Add some books.
+/// books.insert("A Dance With Dragons").unwrap();
+/// books.insert("To Kill a Mockingbird").unwrap();
+/// books.insert("The Odyssey").unwrap();
+/// books.insert("The Great Gatsby").unwrap();
+///
+/// // Check for a specific one.
+/// if !books.contains("The Winds of Winter") {
+///     println!("We have {} books, but The Winds of Winter ain't one.",
+///              books.len());
+/// }
+///
+/// // Remove a book.
+/// books.remove("The Odyssey");
+///
+/// // Iterate over everything.
+/// for book in &books {
+///     println!("{}", book);
+/// }
+/// ```
+pub type FnvIndexSet<T, const N: usize> = IndexSet<T, BuildHasherDefault<FnvHasher>, N>;
+
+/// Fixed capacity [`IndexSet`](https://docs.rs/indexmap/1/indexmap/set/struct.IndexSet.html).
+///
+/// Note that you cannot use `IndexSet` directly, since it is generic around the hashing algorithm
+/// in use. Pick a concrete instantiation like [`FnvIndexSet`](./type.FnvIndexSet.html) instead
+/// or create your own.
+///
+/// Note that the capacity of the `IndexSet` must be a power of 2.
+///
+/// # Examples
+/// Since `IndexSet` cannot be used directly, we're using its `FnvIndexSet` instantiation
+/// for this example.
+///
+/// ```
+/// use heapless::FnvIndexSet;
+///
+/// // A hash set with a capacity of 16 elements allocated on the stack
+/// let mut books = FnvIndexSet::<_, 16>::new();
+///
+/// // Add some books.
+/// books.insert("A Dance With Dragons").unwrap();
+/// books.insert("To Kill a Mockingbird").unwrap();
+/// books.insert("The Odyssey").unwrap();
+/// books.insert("The Great Gatsby").unwrap();
+///
+/// // Check for a specific one.
+/// if !books.contains("The Winds of Winter") {
+///     println!("We have {} books, but The Winds of Winter ain't one.",
+///              books.len());
+/// }
+///
+/// // Remove a book.
+/// books.remove("The Odyssey");
+///
+/// // Iterate over everything.
+/// for book in &books {
+///     println!("{}", book);
+/// }
+/// ```
+pub struct IndexSet<T, S, const N: usize> {
+    map: IndexMap<T, (), S, N>,
+}
+
+impl<T, S, const N: usize> IndexSet<T, BuildHasherDefault<S>, N> {
+    /// Creates an empty `IndexSet`
+    pub const fn new() -> Self {
+        IndexSet {
+            map: IndexMap::new(),
+        }
+    }
+}
+
+impl<T, S, const N: usize> IndexSet<T, S, N>
+where
+    T: Eq + Hash,
+    S: BuildHasher,
+{
+    /// Returns the number of elements the set can hold
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let set = FnvIndexSet::<i32, 16>::new();
+    /// assert_eq!(set.capacity(), 16);
+    /// ```
+    pub fn capacity(&self) -> usize {
+        self.map.capacity()
+    }
+
+    /// Return an iterator over the values of the set, in their order
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut set = FnvIndexSet::<_, 16>::new();
+    /// set.insert("a").unwrap();
+    /// set.insert("b").unwrap();
+    ///
+    /// // Will print in an arbitrary order.
+    /// for x in set.iter() {
+    ///     println!("{}", x);
+    /// }
+    /// ```
+    pub fn iter(&self) -> Iter<'_, T> {
+        Iter {
+            iter: self.map.iter(),
+        }
+    }
+
+    /// Get the first value
+    ///
+    /// Computes in **O(1)** time
+    pub fn first(&self) -> Option<&T> {
+        self.map.first().map(|(k, _v)| k)
+    }
+
+    /// Get the last value
+    ///
+    /// Computes in **O(1)** time
+    pub fn last(&self) -> Option<&T> {
+        self.map.last().map(|(k, _v)| k)
+    }
+
+    /// Visits the values representing the difference, i.e. the values that are in `self` but not in
+    /// `other`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+    ///
+    /// // Can be seen as `a - b`.
+    /// for x in a.difference(&b) {
+    ///     println!("{}", x); // Print 1
+    /// }
+    ///
+    /// let diff: FnvIndexSet<_, 16> = a.difference(&b).collect();
+    /// assert_eq!(diff, [1].iter().collect::<FnvIndexSet<_, 16>>());
+    ///
+    /// // Note that difference is not symmetric,
+    /// // and `b - a` means something else:
+    /// let diff: FnvIndexSet<_, 16> = b.difference(&a).collect();
+    /// assert_eq!(diff, [4].iter().collect::<FnvIndexSet<_, 16>>());
+    /// ```
+    pub fn difference<'a, S2, const N2: usize>(
+        &'a self,
+        other: &'a IndexSet<T, S2, N2>,
+    ) -> Difference<'a, T, S2, N2>
+    where
+        S2: BuildHasher,
+    {
+        Difference {
+            iter: self.iter(),
+            other,
+        }
+    }
+
+    /// Visits the values representing the symmetric difference, i.e. the values that are in `self`
+    /// or in `other` but not in both.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+    ///
+    /// // Print 1, 4 in that order order.
+    /// for x in a.symmetric_difference(&b) {
+    ///     println!("{}", x);
+    /// }
+    ///
+    /// let diff1: FnvIndexSet<_, 16> = a.symmetric_difference(&b).collect();
+    /// let diff2: FnvIndexSet<_, 16> = b.symmetric_difference(&a).collect();
+    ///
+    /// assert_eq!(diff1, diff2);
+    /// assert_eq!(diff1, [1, 4].iter().collect::<FnvIndexSet<_, 16>>());
+    /// ```
+    pub fn symmetric_difference<'a, S2, const N2: usize>(
+        &'a self,
+        other: &'a IndexSet<T, S2, N2>,
+    ) -> impl Iterator<Item = &'a T>
+    where
+        S2: BuildHasher,
+    {
+        self.difference(other).chain(other.difference(self))
+    }
+
+    /// Visits the values representing the intersection, i.e. the values that are both in `self` and
+    /// `other`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+    ///
+    /// // Print 2, 3 in that order.
+    /// for x in a.intersection(&b) {
+    ///     println!("{}", x);
+    /// }
+    ///
+    /// let intersection: FnvIndexSet<_, 16> = a.intersection(&b).collect();
+    /// assert_eq!(intersection, [2, 3].iter().collect::<FnvIndexSet<_, 16>>());
+    /// ```
+    pub fn intersection<'a, S2, const N2: usize>(
+        &'a self,
+        other: &'a IndexSet<T, S2, N2>,
+    ) -> Intersection<'a, T, S2, N2>
+    where
+        S2: BuildHasher,
+    {
+        Intersection {
+            iter: self.iter(),
+            other,
+        }
+    }
+
+    /// Visits the values representing the union, i.e. all the values in `self` or `other`, without
+    /// duplicates.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// let mut b: FnvIndexSet<_, 16> = [4, 2, 3, 4].iter().cloned().collect();
+    ///
+    /// // Print 1, 2, 3, 4 in that order.
+    /// for x in a.union(&b) {
+    ///     println!("{}", x);
+    /// }
+    ///
+    /// let union: FnvIndexSet<_, 16> = a.union(&b).collect();
+    /// assert_eq!(union, [1, 2, 3, 4].iter().collect::<FnvIndexSet<_, 16>>());
+    /// ```
+    pub fn union<'a, S2, const N2: usize>(
+        &'a self,
+        other: &'a IndexSet<T, S2, N2>,
+    ) -> impl Iterator<Item = &'a T>
+    where
+        S2: BuildHasher,
+    {
+        self.iter().chain(other.difference(self))
+    }
+
+    /// Returns the number of elements in the set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+    /// assert_eq!(v.len(), 0);
+    /// v.insert(1).unwrap();
+    /// assert_eq!(v.len(), 1);
+    /// ```
+    pub fn len(&self) -> usize {
+        self.map.len()
+    }
+
+    /// Returns `true` if the set contains no elements.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+    /// assert!(v.is_empty());
+    /// v.insert(1).unwrap();
+    /// assert!(!v.is_empty());
+    /// ```
+    pub fn is_empty(&self) -> bool {
+        self.map.is_empty()
+    }
+
+    /// Clears the set, removing all values.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut v: FnvIndexSet<_, 16> = FnvIndexSet::new();
+    /// v.insert(1).unwrap();
+    /// v.clear();
+    /// assert!(v.is_empty());
+    /// ```
+    pub fn clear(&mut self) {
+        self.map.clear()
+    }
+
+    /// Returns `true` if the set contains a value.
+    ///
+    /// The value may be any borrowed form of the set's value type, but `Hash` and `Eq` on the
+    /// borrowed form must match those for the value type.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let set: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// assert_eq!(set.contains(&1), true);
+    /// assert_eq!(set.contains(&4), false);
+    /// ```
+    pub fn contains<Q>(&self, value: &Q) -> bool
+    where
+        T: Borrow<Q>,
+        Q: ?Sized + Eq + Hash,
+    {
+        self.map.contains_key(value)
+    }
+
+    /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
+    /// checking for an empty intersection.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let a: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// let mut b = FnvIndexSet::<_, 16>::new();
+    ///
+    /// assert_eq!(a.is_disjoint(&b), true);
+    /// b.insert(4).unwrap();
+    /// assert_eq!(a.is_disjoint(&b), true);
+    /// b.insert(1).unwrap();
+    /// assert_eq!(a.is_disjoint(&b), false);
+    /// ```
+    pub fn is_disjoint<S2, const N2: usize>(&self, other: &IndexSet<T, S2, N2>) -> bool
+    where
+        S2: BuildHasher,
+    {
+        self.iter().all(|v| !other.contains(v))
+    }
+
+    /// Returns `true` if the set is a subset of another, i.e. `other` contains at least all the
+    /// values in `self`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let sup: FnvIndexSet<_, 16> = [1, 2, 3].iter().cloned().collect();
+    /// let mut set = FnvIndexSet::<_, 16>::new();
+    ///
+    /// assert_eq!(set.is_subset(&sup), true);
+    /// set.insert(2).unwrap();
+    /// assert_eq!(set.is_subset(&sup), true);
+    /// set.insert(4).unwrap();
+    /// assert_eq!(set.is_subset(&sup), false);
+    /// ```
+    pub fn is_subset<S2, const N2: usize>(&self, other: &IndexSet<T, S2, N2>) -> bool
+    where
+        S2: BuildHasher,
+    {
+        self.iter().all(|v| other.contains(v))
+    }
+
+    // Returns `true` if the set is a superset of another, i.e. `self` contains at least all the
+    // values in `other`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let sub: FnvIndexSet<_, 16> = [1, 2].iter().cloned().collect();
+    /// let mut set = FnvIndexSet::<_, 16>::new();
+    ///
+    /// assert_eq!(set.is_superset(&sub), false);
+    ///
+    /// set.insert(0).unwrap();
+    /// set.insert(1).unwrap();
+    /// assert_eq!(set.is_superset(&sub), false);
+    ///
+    /// set.insert(2).unwrap();
+    /// assert_eq!(set.is_superset(&sub), true);
+    /// ```
+    pub fn is_superset<S2, const N2: usize>(&self, other: &IndexSet<T, S2, N2>) -> bool
+    where
+        S2: BuildHasher,
+    {
+        other.is_subset(self)
+    }
+
+    /// Adds a value to the set.
+    ///
+    /// If the set did not have this value present, `true` is returned.
+    ///
+    /// If the set did have this value present, `false` is returned.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut set = FnvIndexSet::<_, 16>::new();
+    ///
+    /// assert_eq!(set.insert(2).unwrap(), true);
+    /// assert_eq!(set.insert(2).unwrap(), false);
+    /// assert_eq!(set.len(), 1);
+    /// ```
+    pub fn insert(&mut self, value: T) -> Result<bool, T> {
+        self.map
+            .insert(value, ())
+            .map(|old| old.is_none())
+            .map_err(|(k, _)| k)
+    }
+
+    /// Removes a value from the set. Returns `true` if the value was present in the set.
+    ///
+    /// The value may be any borrowed form of the set's value type, but `Hash` and `Eq` on the
+    /// borrowed form must match those for the value type.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::FnvIndexSet;
+    ///
+    /// let mut set = FnvIndexSet::<_, 16>::new();
+    ///
+    /// set.insert(2).unwrap();
+    /// assert_eq!(set.remove(&2), true);
+    /// assert_eq!(set.remove(&2), false);
+    /// ```
+    pub fn remove<Q>(&mut self, value: &Q) -> bool
+    where
+        T: Borrow<Q>,
+        Q: ?Sized + Eq + Hash,
+    {
+        self.map.remove(value).is_some()
+    }
+}
+
+impl<T, S, const N: usize> Clone for IndexSet<T, S, N>
+where
+    T: Eq + Hash + Clone,
+    S: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            map: self.map.clone(),
+        }
+    }
+}
+
+impl<T, S, const N: usize> fmt::Debug for IndexSet<T, S, N>
+where
+    T: Eq + Hash + fmt::Debug,
+    S: BuildHasher,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_set().entries(self.iter()).finish()
+    }
+}
+
+impl<T, S, const N: usize> Default for IndexSet<T, S, N>
+where
+    T: Eq + Hash,
+    S: BuildHasher + Default,
+{
+    fn default() -> Self {
+        IndexSet {
+            map: <_>::default(),
+        }
+    }
+}
+
+impl<T, S1, S2, const N1: usize, const N2: usize> PartialEq<IndexSet<T, S2, N2>>
+    for IndexSet<T, S1, N1>
+where
+    T: Eq + Hash,
+    S1: BuildHasher,
+    S2: BuildHasher,
+{
+    fn eq(&self, other: &IndexSet<T, S2, N2>) -> bool {
+        self.len() == other.len() && self.is_subset(other)
+    }
+}
+
+impl<T, S, const N: usize> Extend<T> for IndexSet<T, S, N>
+where
+    T: Eq + Hash,
+    S: BuildHasher,
+{
+    fn extend<I>(&mut self, iterable: I)
+    where
+        I: IntoIterator<Item = T>,
+    {
+        self.map.extend(iterable.into_iter().map(|k| (k, ())))
+    }
+}
+
+impl<'a, T, S, const N: usize> Extend<&'a T> for IndexSet<T, S, N>
+where
+    T: 'a + Eq + Hash + Copy,
+    S: BuildHasher,
+{
+    fn extend<I>(&mut self, iterable: I)
+    where
+        I: IntoIterator<Item = &'a T>,
+    {
+        self.extend(iterable.into_iter().cloned())
+    }
+}
+
+impl<T, S, const N: usize> FromIterator<T> for IndexSet<T, S, N>
+where
+    T: Eq + Hash,
+    S: BuildHasher + Default,
+{
+    fn from_iter<I>(iter: I) -> Self
+    where
+        I: IntoIterator<Item = T>,
+    {
+        let mut set = IndexSet::default();
+        set.extend(iter);
+        set
+    }
+}
+
+impl<'a, T, S, const N: usize> IntoIterator for &'a IndexSet<T, S, N>
+where
+    T: Eq + Hash,
+    S: BuildHasher,
+{
+    type Item = &'a T;
+    type IntoIter = Iter<'a, T>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+pub struct Iter<'a, T> {
+    iter: indexmap::Iter<'a, T, ()>,
+}
+
+impl<'a, T> Iterator for Iter<'a, T> {
+    type Item = &'a T;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.iter.next().map(|(k, _)| k)
+    }
+}
+
+impl<'a, T> Clone for Iter<'a, T> {
+    fn clone(&self) -> Self {
+        Self {
+            iter: self.iter.clone(),
+        }
+    }
+}
+
+pub struct Difference<'a, T, S, const N: usize>
+where
+    S: BuildHasher,
+    T: Eq + Hash,
+{
+    iter: Iter<'a, T>,
+    other: &'a IndexSet<T, S, N>,
+}
+
+impl<'a, T, S, const N: usize> Iterator for Difference<'a, T, S, N>
+where
+    S: BuildHasher,
+    T: Eq + Hash,
+{
+    type Item = &'a T;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        loop {
+            let elt = self.iter.next()?;
+            if !self.other.contains(elt) {
+                return Some(elt);
+            }
+        }
+    }
+}
+
+pub struct Intersection<'a, T, S, const N: usize>
+where
+    S: BuildHasher,
+    T: Eq + Hash,
+{
+    iter: Iter<'a, T>,
+    other: &'a IndexSet<T, S, N>,
+}
+
+impl<'a, T, S, const N: usize> Iterator for Intersection<'a, T, S, N>
+where
+    S: BuildHasher,
+    T: Eq + Hash,
+{
+    type Item = &'a T;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        loop {
+            let elt = self.iter.next()?;
+            if self.other.contains(elt) {
+                return Some(elt);
+            }
+        }
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/lib.rs.html b/docs/doc/src/heapless/lib.rs.html new file mode 100644 index 0000000..c6f3799 --- /dev/null +++ b/docs/doc/src/heapless/lib.rs.html @@ -0,0 +1,239 @@ +lib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+
//! `static` friendly data structures that don't require dynamic memory allocation
+//!
+//! The core principle behind `heapless` is that its data structures are backed by a *static* memory
+//! allocation. For example, you can think of `heapless::Vec` as an alternative version of
+//! `std::Vec` with fixed capacity and that can't be re-allocated on the fly (e.g. via `push`).
+//!
+//! All `heapless` data structures store their memory allocation *inline* and specify their capacity
+//! via their type parameter `N`. This means that you can instantiate a `heapless` data structure on
+//! the stack, in a `static` variable, or even in the heap.
+//!
+//! ```
+//! use heapless::Vec; // fixed capacity `std::Vec`
+//!
+//! // on the stack
+//! let mut xs: Vec<u8, 8> = Vec::new(); // can hold up to 8 elements
+//! xs.push(42).unwrap();
+//! assert_eq!(xs.pop(), Some(42));
+//!
+//! // in a `static` variable
+//! static mut XS: Vec<u8, 8> = Vec::new();
+//!
+//! let xs = unsafe { &mut XS };
+//!
+//! xs.push(42);
+//! assert_eq!(xs.pop(), Some(42));
+//!
+//! // in the heap (though kind of pointless because no reallocation)
+//! let mut ys: Box<Vec<u8, 8>> = Box::new(Vec::new());
+//! ys.push(42).unwrap();
+//! assert_eq!(ys.pop(), Some(42));
+//! ```
+//!
+//! Because they have fixed capacity `heapless` data structures don't implicitly reallocate. This
+//! means that operations like `heapless::Vec.push` are *truly* constant time rather than amortized
+//! constant time with potentially unbounded (depends on the allocator) worst case execution time
+//! (which is bad / unacceptable for hard real time applications).
+//!
+//! `heapless` data structures don't use a memory allocator which means no risk of an uncatchable
+//! Out Of Memory (OOM) condition while performing operations on them. It's certainly possible to
+//! run out of capacity while growing `heapless` data structures, but the API lets you handle this
+//! possibility by returning a `Result` on operations that may exhaust the capacity of the data
+//! structure.
+//!
+//! List of currently implemented data structures:
+//!
+//! - [`Arc`](pool/singleton/arc/struct.Arc.html) -- Thread-safe reference-counting pointer backed by a memory pool
+//! - [`BinaryHeap`](binary_heap/struct.BinaryHeap.html) -- priority queue
+//! - [`IndexMap`](struct.IndexMap.html) -- hash table
+//! - [`IndexSet`](struct.IndexSet.html) -- hash set
+//! - [`LinearMap`](struct.LinearMap.html)
+//! - [`Pool`](pool/struct.Pool.html) -- lock-free memory pool
+//! - [`String`](struct.String.html)
+//! - [`Vec`](struct.Vec.html)
+//! - [`mpmc::Q*`](mpmc/index.html) -- multiple producer multiple consumer lock-free queue
+//! - [`spsc::Queue`](spsc/struct.Queue.html) -- single producer single consumer lock-free queue
+//!
+//! # Optional Features
+//!
+//! The `heapless` crate provides the following optional Cargo features:
+//!
+//! - `ufmt-impl`: Implement [`ufmt_write::uWrite`] for `String<N>` and `Vec<u8, N>`
+//!
+//! [`ufmt_write::uWrite`]: https://docs.rs/ufmt-write/
+//!
+//! # Minimum Supported Rust Version (MSRV)
+//!
+//! This crate is guaranteed to compile on stable Rust 1.51 and up with its default set of features.
+//! It *might* compile on older versions but that may change in any new patch release.
+
+#![cfg_attr(not(test), no_std)]
+#![deny(missing_docs)]
+#![deny(rust_2018_compatibility)]
+#![deny(rust_2018_idioms)]
+#![deny(warnings)]
+#![deny(const_err)]
+
+pub use binary_heap::BinaryHeap;
+pub use deque::Deque;
+pub use histbuf::{HistoryBuffer, OldestOrdered};
+pub use indexmap::{Bucket, Entry, FnvIndexMap, IndexMap, OccupiedEntry, Pos, VacantEntry};
+pub use indexset::{FnvIndexSet, IndexSet};
+pub use linear_map::LinearMap;
+#[cfg(all(has_cas, feature = "cas"))]
+pub use pool::singleton::arc::Arc;
+pub use string::String;
+pub use vec::Vec;
+
+#[macro_use]
+#[cfg(test)]
+mod test_helpers;
+
+mod deque;
+mod histbuf;
+mod indexmap;
+mod indexset;
+mod linear_map;
+mod string;
+mod vec;
+
+#[cfg(feature = "serde")]
+mod de;
+#[cfg(feature = "serde")]
+mod ser;
+
+pub mod binary_heap;
+#[cfg(feature = "defmt-impl")]
+mod defmt;
+#[cfg(all(has_cas, feature = "cas"))]
+pub mod mpmc;
+#[cfg(all(has_cas, feature = "cas"))]
+pub mod pool;
+pub mod sorted_linked_list;
+#[cfg(has_atomics)]
+pub mod spsc;
+
+#[cfg(feature = "ufmt-impl")]
+mod ufmt;
+
+mod sealed;
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/linear_map.rs.html b/docs/doc/src/heapless/linear_map.rs.html new file mode 100644 index 0000000..67c57de --- /dev/null +++ b/docs/doc/src/heapless/linear_map.rs.html @@ -0,0 +1,1089 @@ +linear_map.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+
use crate::Vec;
+use core::{borrow::Borrow, fmt, iter::FromIterator, mem, ops, slice};
+
+/// A fixed capacity map / dictionary that performs lookups via linear search
+///
+/// Note that as this map doesn't use hashing so most operations are **O(N)** instead of O(1)
+
+pub struct LinearMap<K, V, const N: usize> {
+    pub(crate) buffer: Vec<(K, V), N>,
+}
+
+impl<K, V, const N: usize> LinearMap<K, V, N> {
+    /// Creates an empty `LinearMap`
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// // allocate the map on the stack
+    /// let mut map: LinearMap<&str, isize, 8> = LinearMap::new();
+    ///
+    /// // allocate the map in a static variable
+    /// static mut MAP: LinearMap<&str, isize, 8> = LinearMap::new();
+    /// ```
+    pub const fn new() -> Self {
+        Self { buffer: Vec::new() }
+    }
+}
+
+impl<K, V, const N: usize> LinearMap<K, V, N>
+where
+    K: Eq,
+{
+    /// Returns the number of elements that the map can hold
+    ///
+    /// Computes in **O(1)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let map: LinearMap<&str, isize, 8> = LinearMap::new();
+    /// assert_eq!(map.capacity(), 8);
+    /// ```
+    pub fn capacity(&self) -> usize {
+        N
+    }
+
+    /// Clears the map, removing all key-value pairs
+    ///
+    /// Computes in **O(1)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert(1, "a").unwrap();
+    /// map.clear();
+    /// assert!(map.is_empty());
+    /// ```
+    pub fn clear(&mut self) {
+        self.buffer.clear()
+    }
+
+    /// Returns true if the map contains a value for the specified key.
+    ///
+    /// Computes in **O(N)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert(1, "a").unwrap();
+    /// assert_eq!(map.contains_key(&1), true);
+    /// assert_eq!(map.contains_key(&2), false);
+    /// ```
+    pub fn contains_key(&self, key: &K) -> bool {
+        self.get(key).is_some()
+    }
+
+    /// Returns a reference to the value corresponding to the key
+    ///
+    /// Computes in **O(N)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert(1, "a").unwrap();
+    /// assert_eq!(map.get(&1), Some(&"a"));
+    /// assert_eq!(map.get(&2), None);
+    /// ```
+    pub fn get<Q>(&self, key: &Q) -> Option<&V>
+    where
+        K: Borrow<Q>,
+        Q: Eq + ?Sized,
+    {
+        self.iter()
+            .find(|&(k, _)| k.borrow() == key)
+            .map(|(_, v)| v)
+    }
+
+    /// Returns a mutable reference to the value corresponding to the key
+    ///
+    /// Computes in **O(N)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert(1, "a").unwrap();
+    /// if let Some(x) = map.get_mut(&1) {
+    ///     *x = "b";
+    /// }
+    /// assert_eq!(map[&1], "b");
+    /// ```
+    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
+    where
+        K: Borrow<Q>,
+        Q: Eq + ?Sized,
+    {
+        self.iter_mut()
+            .find(|&(k, _)| k.borrow() == key)
+            .map(|(_, v)| v)
+    }
+
+    /// Returns the number of elements in this map
+    ///
+    /// Computes in **O(1)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut a: LinearMap<_, _, 8> = LinearMap::new();
+    /// assert_eq!(a.len(), 0);
+    /// a.insert(1, "a").unwrap();
+    /// assert_eq!(a.len(), 1);
+    /// ```
+    pub fn len(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Inserts a key-value pair into the map.
+    ///
+    /// If the map did not have this key present, `None` is returned.
+    ///
+    /// If the map did have this key present, the value is updated, and the old value is returned.
+    ///
+    /// Computes in **O(N)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// assert_eq!(map.insert(37, "a").unwrap(), None);
+    /// assert_eq!(map.is_empty(), false);
+    ///
+    /// map.insert(37, "b").unwrap();
+    /// assert_eq!(map.insert(37, "c").unwrap(), Some("b"));
+    /// assert_eq!(map[&37], "c");
+    /// ```
+    pub fn insert(&mut self, key: K, mut value: V) -> Result<Option<V>, (K, V)> {
+        if let Some((_, v)) = self.iter_mut().find(|&(k, _)| *k == key) {
+            mem::swap(v, &mut value);
+            return Ok(Some(value));
+        }
+
+        self.buffer.push((key, value))?;
+        Ok(None)
+    }
+
+    /// Returns true if the map contains no elements
+    ///
+    /// Computes in **O(1)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut a: LinearMap<_, _, 8> = LinearMap::new();
+    /// assert!(a.is_empty());
+    /// a.insert(1, "a").unwrap();
+    /// assert!(!a.is_empty());
+    /// ```
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    /// An iterator visiting all key-value pairs in arbitrary order.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for (key, val) in map.iter() {
+    ///     println!("key: {} val: {}", key, val);
+    /// }
+    /// ```
+    pub fn iter(&self) -> Iter<'_, K, V> {
+        Iter {
+            iter: self.buffer.as_slice().iter(),
+        }
+    }
+
+    /// An iterator visiting all key-value pairs in arbitrary order, with mutable references to the
+    /// values
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// // Update all values
+    /// for (_, val) in map.iter_mut() {
+    ///     *val = 2;
+    /// }
+    ///
+    /// for (key, val) in &map {
+    ///     println!("key: {} val: {}", key, val);
+    /// }
+    /// ```
+    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
+        IterMut {
+            iter: self.buffer.as_mut_slice().iter_mut(),
+        }
+    }
+
+    /// An iterator visiting all keys in arbitrary order
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for key in map.keys() {
+    ///     println!("{}", key);
+    /// }
+    /// ```
+    pub fn keys(&self) -> impl Iterator<Item = &K> {
+        self.iter().map(|(k, _)| k)
+    }
+
+    /// Removes a key from the map, returning the value at the key if the key was previously in the
+    /// map
+    ///
+    /// Computes in **O(N)** time
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert(1, "a").unwrap();
+    /// assert_eq!(map.remove(&1), Some("a"));
+    /// assert_eq!(map.remove(&1), None);
+    /// ```
+    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
+    where
+        K: Borrow<Q>,
+        Q: Eq + ?Sized,
+    {
+        let idx = self
+            .keys()
+            .enumerate()
+            .find(|&(_, k)| k.borrow() == key)
+            .map(|(idx, _)| idx);
+
+        idx.map(|idx| self.buffer.swap_remove(idx).1)
+    }
+
+    /// An iterator visiting all values in arbitrary order
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for val in map.values() {
+    ///     println!("{}", val);
+    /// }
+    /// ```
+    pub fn values(&self) -> impl Iterator<Item = &V> {
+        self.iter().map(|(_, v)| v)
+    }
+
+    /// An iterator visiting all values mutably in arbitrary order
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::LinearMap;
+    ///
+    /// let mut map: LinearMap<_, _, 8> = LinearMap::new();
+    /// map.insert("a", 1).unwrap();
+    /// map.insert("b", 2).unwrap();
+    /// map.insert("c", 3).unwrap();
+    ///
+    /// for val in map.values_mut() {
+    ///     *val += 10;
+    /// }
+    ///
+    /// for val in map.values() {
+    ///     println!("{}", val);
+    /// }
+    /// ```
+    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
+        self.iter_mut().map(|(_, v)| v)
+    }
+}
+
+impl<'a, K, V, Q, const N: usize> ops::Index<&'a Q> for LinearMap<K, V, N>
+where
+    K: Borrow<Q> + Eq,
+    Q: Eq + ?Sized,
+{
+    type Output = V;
+
+    fn index(&self, key: &Q) -> &V {
+        self.get(key).expect("no entry found for key")
+    }
+}
+
+impl<'a, K, V, Q, const N: usize> ops::IndexMut<&'a Q> for LinearMap<K, V, N>
+where
+    K: Borrow<Q> + Eq,
+    Q: Eq + ?Sized,
+{
+    fn index_mut(&mut self, key: &Q) -> &mut V {
+        self.get_mut(key).expect("no entry found for key")
+    }
+}
+
+impl<K, V, const N: usize> Default for LinearMap<K, V, N>
+where
+    K: Eq,
+{
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl<K, V, const N: usize> Clone for LinearMap<K, V, N>
+where
+    K: Eq + Clone,
+    V: Clone,
+{
+    fn clone(&self) -> Self {
+        Self {
+            buffer: self.buffer.clone(),
+        }
+    }
+}
+
+impl<K, V, const N: usize> fmt::Debug for LinearMap<K, V, N>
+where
+    K: Eq + fmt::Debug,
+    V: fmt::Debug,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_map().entries(self.iter()).finish()
+    }
+}
+
+impl<K, V, const N: usize> FromIterator<(K, V)> for LinearMap<K, V, N>
+where
+    K: Eq,
+{
+    fn from_iter<I>(iter: I) -> Self
+    where
+        I: IntoIterator<Item = (K, V)>,
+    {
+        let mut out = Self::new();
+        out.buffer.extend(iter);
+        out
+    }
+}
+
+pub struct IntoIter<K, V, const N: usize>
+where
+    K: Eq,
+{
+    inner: <Vec<(K, V), N> as IntoIterator>::IntoIter,
+}
+
+impl<K, V, const N: usize> Iterator for IntoIter<K, V, N>
+where
+    K: Eq,
+{
+    type Item = (K, V);
+    fn next(&mut self) -> Option<Self::Item> {
+        self.inner.next()
+    }
+}
+
+impl<'a, K, V, const N: usize> IntoIterator for &'a LinearMap<K, V, N>
+where
+    K: Eq,
+{
+    type Item = (&'a K, &'a V);
+    type IntoIter = Iter<'a, K, V>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+pub struct Iter<'a, K, V> {
+    iter: slice::Iter<'a, (K, V)>,
+}
+
+impl<'a, K, V> Iterator for Iter<'a, K, V> {
+    type Item = (&'a K, &'a V);
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.iter.next().map(|&(ref k, ref v)| (k, v))
+    }
+}
+
+impl<'a, K, V> Clone for Iter<'a, K, V> {
+    fn clone(&self) -> Self {
+        Self {
+            iter: self.iter.clone(),
+        }
+    }
+}
+
+impl<K, V, const N: usize> Drop for LinearMap<K, V, N> {
+    fn drop(&mut self) {
+        // heapless::Vec implements drop right?
+        drop(&self.buffer);
+        // original code below
+        // unsafe { ptr::drop_in_place(self.buffer.as_mut_slice()) }
+    }
+}
+
+pub struct IterMut<'a, K, V> {
+    iter: slice::IterMut<'a, (K, V)>,
+}
+
+impl<'a, K, V> Iterator for IterMut<'a, K, V> {
+    type Item = (&'a K, &'a mut V);
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.iter.next().map(|&mut (ref k, ref mut v)| (k, v))
+    }
+}
+
+impl<K, V, const N: usize, const N2: usize> PartialEq<LinearMap<K, V, N2>> for LinearMap<K, V, N>
+where
+    K: Eq,
+    V: PartialEq,
+{
+    fn eq(&self, other: &LinearMap<K, V, N2>) -> bool {
+        self.len() == other.len()
+            && self
+                .iter()
+                .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
+    }
+}
+
+impl<K, V, const N: usize> Eq for LinearMap<K, V, N>
+where
+    K: Eq,
+    V: PartialEq,
+{
+}
+
+#[cfg(test)]
+mod test {
+    use crate::LinearMap;
+
+    #[test]
+    fn static_new() {
+        static mut _L: LinearMap<i32, i32, 8> = LinearMap::new();
+    }
+
+    #[test]
+    fn partial_eq() {
+        {
+            let mut a = LinearMap::<_, _, 1>::new();
+            a.insert("k1", "v1").unwrap();
+
+            let mut b = LinearMap::<_, _, 2>::new();
+            b.insert("k1", "v1").unwrap();
+
+            assert!(a == b);
+
+            b.insert("k2", "v2").unwrap();
+
+            assert!(a != b);
+        }
+
+        {
+            let mut a = LinearMap::<_, _, 2>::new();
+            a.insert("k1", "v1").unwrap();
+            a.insert("k2", "v2").unwrap();
+
+            let mut b = LinearMap::<_, _, 2>::new();
+            b.insert("k2", "v2").unwrap();
+            b.insert("k1", "v1").unwrap();
+
+            assert!(a == b);
+        }
+    }
+
+    // TODO: drop test
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/sealed.rs.html b/docs/doc/src/heapless/sealed.rs.html new file mode 100644 index 0000000..d6da634 --- /dev/null +++ b/docs/doc/src/heapless/sealed.rs.html @@ -0,0 +1,117 @@ +sealed.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+
#[allow(dead_code)]
+#[allow(path_statements)]
+pub(crate) const fn smaller_than<const N: usize, const MAX: usize>() {
+    Assert::<N, MAX>::LESS;
+}
+
+#[allow(dead_code)]
+#[allow(path_statements)]
+pub(crate) const fn greater_than_eq_0<const N: usize>() {
+    Assert::<N, 0>::GREATER_EQ;
+}
+
+#[allow(dead_code)]
+#[allow(path_statements)]
+pub(crate) const fn greater_than_0<const N: usize>() {
+    Assert::<N, 0>::GREATER;
+}
+
+#[allow(dead_code)]
+#[allow(path_statements)]
+pub(crate) const fn greater_than_1<const N: usize>() {
+    Assert::<N, 1>::GREATER;
+}
+
+#[allow(dead_code)]
+#[allow(path_statements)]
+pub(crate) const fn power_of_two<const N: usize>() {
+    Assert::<N, 0>::GREATER;
+    Assert::<N, 0>::POWER_OF_TWO;
+}
+
+#[allow(dead_code)]
+/// Const assert hack
+pub struct Assert<const L: usize, const R: usize>;
+
+#[allow(dead_code)]
+impl<const L: usize, const R: usize> Assert<L, R> {
+    /// Const assert hack
+    pub const GREATER_EQ: usize = L - R;
+
+    /// Const assert hack
+    pub const LESS_EQ: usize = R - L;
+
+    /// Const assert hack
+    pub const NOT_EQ: isize = 0 / (R as isize - L as isize);
+
+    /// Const assert hack
+    pub const EQ: usize = (R - L) + (L - R);
+
+    /// Const assert hack
+    pub const GREATER: usize = L - R - 1;
+
+    /// Const assert hack
+    pub const LESS: usize = R - L - 1;
+
+    /// Const assert hack
+    pub const POWER_OF_TWO: usize = 0 - (L & (L - 1));
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/sorted_linked_list.rs.html b/docs/doc/src/heapless/sorted_linked_list.rs.html new file mode 100644 index 0000000..9f04c5b --- /dev/null +++ b/docs/doc/src/heapless/sorted_linked_list.rs.html @@ -0,0 +1,1733 @@ +sorted_linked_list.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+742
+743
+744
+745
+746
+747
+748
+749
+750
+751
+752
+753
+754
+755
+756
+757
+758
+759
+760
+761
+762
+763
+764
+765
+766
+767
+768
+769
+770
+771
+772
+773
+774
+775
+776
+777
+778
+779
+780
+781
+782
+783
+784
+785
+786
+787
+788
+789
+790
+791
+792
+793
+794
+795
+796
+797
+798
+799
+800
+801
+802
+803
+804
+805
+806
+807
+808
+809
+810
+811
+812
+813
+814
+815
+816
+817
+818
+819
+820
+821
+822
+823
+824
+825
+826
+827
+828
+829
+830
+831
+832
+833
+834
+835
+836
+837
+838
+839
+840
+841
+842
+843
+844
+845
+846
+847
+848
+849
+850
+851
+852
+853
+854
+855
+856
+857
+858
+859
+860
+861
+862
+863
+864
+865
+866
+
//! A fixed sorted priority linked list, similar to [`BinaryHeap`] but with different properties
+//! on `push`, `pop`, etc.
+//! For example, the sorting of the list will never `memcpy` the underlying value, so having large
+//! objects in the list will not cause a performance hit.
+//!
+//! # Examples
+//!
+//! ```
+//! use heapless::sorted_linked_list::{SortedLinkedList, Max};
+//! let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+//!
+//! // The largest value will always be first
+//! ll.push(1).unwrap();
+//! assert_eq!(ll.peek(), Some(&1));
+//!
+//! ll.push(2).unwrap();
+//! assert_eq!(ll.peek(), Some(&2));
+//!
+//! ll.push(3).unwrap();
+//! assert_eq!(ll.peek(), Some(&3));
+//!
+//! // This will not fit in the queue.
+//! assert_eq!(ll.push(4), Err(4));
+//! ```
+//!
+//! [`BinaryHeap`]: `crate::binary_heap::BinaryHeap`
+
+use core::cmp::Ordering;
+use core::fmt;
+use core::marker::PhantomData;
+use core::mem::MaybeUninit;
+use core::ops::{Deref, DerefMut};
+use core::ptr;
+
+/// Trait for defining an index for the linked list, never implemented by users.
+pub trait SortedLinkedListIndex: Copy {
+    #[doc(hidden)]
+    unsafe fn new_unchecked(val: usize) -> Self;
+    #[doc(hidden)]
+    unsafe fn get_unchecked(self) -> usize;
+    #[doc(hidden)]
+    fn option(self) -> Option<usize>;
+    #[doc(hidden)]
+    fn none() -> Self;
+}
+
+/// Marker for Min sorted [`SortedLinkedList`].
+pub struct Min;
+
+/// Marker for Max sorted [`SortedLinkedList`].
+pub struct Max;
+
+/// The linked list kind: min-list or max-list
+pub trait Kind: private::Sealed {
+    #[doc(hidden)]
+    fn ordering() -> Ordering;
+}
+
+impl Kind for Min {
+    fn ordering() -> Ordering {
+        Ordering::Less
+    }
+}
+
+impl Kind for Max {
+    fn ordering() -> Ordering {
+        Ordering::Greater
+    }
+}
+
+/// Sealed traits
+mod private {
+    pub trait Sealed {}
+}
+
+impl private::Sealed for Max {}
+impl private::Sealed for Min {}
+
+/// A node in the [`SortedLinkedList`].
+pub struct Node<T, Idx> {
+    val: MaybeUninit<T>,
+    next: Idx,
+}
+
+/// The linked list.
+pub struct SortedLinkedList<T, Idx, K, const N: usize>
+where
+    Idx: SortedLinkedListIndex,
+{
+    list: [Node<T, Idx>; N],
+    head: Idx,
+    free: Idx,
+    _kind: PhantomData<K>,
+}
+
+// Internal macro for generating indexes for the linkedlist and const new for the linked list
+macro_rules! impl_index_and_const_new {
+    ($name:ident, $ty:ty, $new_name:ident, $max_val:expr) => {
+        /// Index for the [`SortedLinkedList`] with specific backing storage.
+        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+        pub struct $name($ty);
+
+        impl SortedLinkedListIndex for $name {
+            #[inline(always)]
+            unsafe fn new_unchecked(val: usize) -> Self {
+                Self::new_unchecked(val as $ty)
+            }
+
+            /// This is only valid if `self.option()` is not `None`.
+            #[inline(always)]
+            unsafe fn get_unchecked(self) -> usize {
+                self.0 as usize
+            }
+
+            #[inline(always)]
+            fn option(self) -> Option<usize> {
+                if self.0 == <$ty>::MAX {
+                    None
+                } else {
+                    Some(self.0 as usize)
+                }
+            }
+
+            #[inline(always)]
+            fn none() -> Self {
+                Self::none()
+            }
+        }
+
+        impl $name {
+            /// Needed for a `const fn new()`.
+            #[inline]
+            const unsafe fn new_unchecked(value: $ty) -> Self {
+                $name(value)
+            }
+
+            /// Needed for a `const fn new()`.
+            #[inline]
+            const fn none() -> Self {
+                $name(<$ty>::MAX)
+            }
+        }
+
+        impl<T, K, const N: usize> SortedLinkedList<T, $name, K, N> {
+            const UNINIT: Node<T, $name> = Node {
+                val: MaybeUninit::uninit(),
+                next: $name::none(),
+            };
+
+            /// Create a new linked list.
+            pub const fn $new_name() -> Self {
+                // Const assert N < MAX
+                crate::sealed::smaller_than::<N, $max_val>();
+
+                let mut list = SortedLinkedList {
+                    list: [Self::UNINIT; N],
+                    head: $name::none(),
+                    free: unsafe { $name::new_unchecked(0) },
+                    _kind: PhantomData,
+                };
+
+                if N == 0 {
+                    list.free = $name::none();
+                    return list;
+                }
+
+                let mut free = 0;
+
+                // Initialize indexes
+                while free < N - 1 {
+                    list.list[free].next = unsafe { $name::new_unchecked(free as $ty + 1) };
+                    free += 1;
+                }
+
+                list
+            }
+        }
+    };
+}
+
+impl_index_and_const_new!(LinkedIndexU8, u8, new_u8, { u8::MAX as usize - 1 });
+impl_index_and_const_new!(LinkedIndexU16, u16, new_u16, { u16::MAX as usize - 1 });
+impl_index_and_const_new!(LinkedIndexUsize, usize, new_usize, { usize::MAX - 1 });
+
+impl<T, Idx, K, const N: usize> SortedLinkedList<T, Idx, K, N>
+where
+    Idx: SortedLinkedListIndex,
+{
+    /// Internal access helper
+    #[inline(always)]
+    fn node_at(&self, index: usize) -> &Node<T, Idx> {
+        // Safety: The entire `self.list` is initialized in `new`, which makes this safe.
+        unsafe { self.list.get_unchecked(index) }
+    }
+
+    /// Internal access helper
+    #[inline(always)]
+    fn node_at_mut(&mut self, index: usize) -> &mut Node<T, Idx> {
+        // Safety: The entire `self.list` is initialized in `new`, which makes this safe.
+        unsafe { self.list.get_unchecked_mut(index) }
+    }
+
+    /// Internal access helper
+    #[inline(always)]
+    fn write_data_in_node_at(&mut self, index: usize, data: T) {
+        // Safety: The entire `self.list` is initialized in `new`, which makes this safe.
+        unsafe {
+            self.node_at_mut(index).val.as_mut_ptr().write(data);
+        }
+    }
+
+    /// Internal access helper
+    #[inline(always)]
+    fn read_data_in_node_at(&self, index: usize) -> &T {
+        // Safety: The entire `self.list` is initialized in `new`, which makes this safe.
+        unsafe { &*self.node_at(index).val.as_ptr() }
+    }
+
+    /// Internal access helper
+    #[inline(always)]
+    fn read_mut_data_in_node_at(&mut self, index: usize) -> &mut T {
+        // Safety: The entire `self.list` is initialized in `new`, which makes this safe.
+        unsafe { &mut *self.node_at_mut(index).val.as_mut_ptr() }
+    }
+
+    /// Internal access helper
+    #[inline(always)]
+    fn extract_data_in_node_at(&mut self, index: usize) -> T {
+        // Safety: The entire `self.list` is initialized in `new`, which makes this safe.
+        unsafe { self.node_at(index).val.as_ptr().read() }
+    }
+}
+
+impl<T, Idx, K, const N: usize> SortedLinkedList<T, Idx, K, N>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    /// Pushes a value onto the list without checking if the list is full.
+    ///
+    /// Complexity is worst-case `O(N)`.
+    ///
+    /// # Safety
+    ///
+    /// Assumes that the list is not full.
+    pub unsafe fn push_unchecked(&mut self, value: T) {
+        let new = self.free.get_unchecked();
+
+        // Store the data and update the next free spot
+        self.write_data_in_node_at(new, value);
+        self.free = self.node_at(new).next;
+
+        if let Some(head) = self.head.option() {
+            // Check if we need to replace head
+            if self
+                .read_data_in_node_at(head)
+                .cmp(self.read_data_in_node_at(new))
+                != K::ordering()
+            {
+                self.node_at_mut(new).next = self.head;
+                self.head = Idx::new_unchecked(new);
+            } else {
+                // It's not head, search the list for the correct placement
+                let mut current = head;
+
+                while let Some(next) = self.node_at(current).next.option() {
+                    if self
+                        .read_data_in_node_at(next)
+                        .cmp(self.read_data_in_node_at(new))
+                        != K::ordering()
+                    {
+                        break;
+                    }
+
+                    current = next;
+                }
+
+                self.node_at_mut(new).next = self.node_at(current).next;
+                self.node_at_mut(current).next = Idx::new_unchecked(new);
+            }
+        } else {
+            self.node_at_mut(new).next = self.head;
+            self.head = Idx::new_unchecked(new);
+        }
+    }
+
+    /// Pushes an element to the linked list and sorts it into place.
+    ///
+    /// Complexity is worst-case `O(N)`.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// // The largest value will always be first
+    /// ll.push(1).unwrap();
+    /// assert_eq!(ll.peek(), Some(&1));
+    ///
+    /// ll.push(2).unwrap();
+    /// assert_eq!(ll.peek(), Some(&2));
+    ///
+    /// ll.push(3).unwrap();
+    /// assert_eq!(ll.peek(), Some(&3));
+    ///
+    /// // This will not fit in the queue.
+    /// assert_eq!(ll.push(4), Err(4));
+    /// ```
+    pub fn push(&mut self, value: T) -> Result<(), T> {
+        if !self.is_full() {
+            Ok(unsafe { self.push_unchecked(value) })
+        } else {
+            Err(value)
+        }
+    }
+
+    /// Get an iterator over the sorted list.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// ll.push(1).unwrap();
+    /// ll.push(2).unwrap();
+    ///
+    /// let mut iter = ll.iter();
+    ///
+    /// assert_eq!(iter.next(), Some(&2));
+    /// assert_eq!(iter.next(), Some(&1));
+    /// assert_eq!(iter.next(), None);
+    /// ```
+    pub fn iter(&self) -> Iter<'_, T, Idx, K, N> {
+        Iter {
+            list: self,
+            index: self.head,
+        }
+    }
+
+    /// Find an element in the list that can be changed and resorted.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// ll.push(1).unwrap();
+    /// ll.push(2).unwrap();
+    /// ll.push(3).unwrap();
+    ///
+    /// // Find a value and update it
+    /// let mut find = ll.find_mut(|v| *v == 2).unwrap();
+    /// *find += 1000;
+    /// find.finish();
+    ///
+    /// assert_eq!(ll.pop(), Ok(1002));
+    /// assert_eq!(ll.pop(), Ok(3));
+    /// assert_eq!(ll.pop(), Ok(1));
+    /// assert_eq!(ll.pop(), Err(()));
+    /// ```
+    pub fn find_mut<F>(&mut self, mut f: F) -> Option<FindMut<'_, T, Idx, K, N>>
+    where
+        F: FnMut(&T) -> bool,
+    {
+        let head = self.head.option()?;
+
+        // Special-case, first element
+        if f(self.read_data_in_node_at(head)) {
+            return Some(FindMut {
+                is_head: true,
+                prev_index: Idx::none(),
+                index: self.head,
+                list: self,
+                maybe_changed: false,
+            });
+        }
+
+        let mut current = head;
+
+        while let Some(next) = self.node_at(current).next.option() {
+            if f(self.read_data_in_node_at(next)) {
+                return Some(FindMut {
+                    is_head: false,
+                    prev_index: unsafe { Idx::new_unchecked(current) },
+                    index: unsafe { Idx::new_unchecked(next) },
+                    list: self,
+                    maybe_changed: false,
+                });
+            }
+
+            current = next;
+        }
+
+        None
+    }
+
+    /// Peek at the first element.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max, Min};
+    /// let mut ll_max: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// // The largest value will always be first
+    /// ll_max.push(1).unwrap();
+    /// assert_eq!(ll_max.peek(), Some(&1));
+    /// ll_max.push(2).unwrap();
+    /// assert_eq!(ll_max.peek(), Some(&2));
+    /// ll_max.push(3).unwrap();
+    /// assert_eq!(ll_max.peek(), Some(&3));
+    ///
+    /// let mut ll_min: SortedLinkedList<_, _, Min, 3> = SortedLinkedList::new_usize();
+    ///
+    /// // The Smallest value will always be first
+    /// ll_min.push(3).unwrap();
+    /// assert_eq!(ll_min.peek(), Some(&3));
+    /// ll_min.push(2).unwrap();
+    /// assert_eq!(ll_min.peek(), Some(&2));
+    /// ll_min.push(1).unwrap();
+    /// assert_eq!(ll_min.peek(), Some(&1));
+    /// ```
+    pub fn peek(&self) -> Option<&T> {
+        self.head
+            .option()
+            .map(|head| self.read_data_in_node_at(head))
+    }
+
+    /// Pop an element from the list without checking so the list is not empty.
+    ///
+    /// # Safety
+    ///
+    /// Assumes that the list is not empty.
+    pub unsafe fn pop_unchecked(&mut self) -> T {
+        let head = self.head.get_unchecked();
+        let current = head;
+        self.head = self.node_at(head).next;
+        self.node_at_mut(current).next = self.free;
+        self.free = Idx::new_unchecked(current);
+
+        self.extract_data_in_node_at(current)
+    }
+
+    /// Pops the first element in the list.
+    ///
+    /// Complexity is worst-case `O(1)`.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// ll.push(1).unwrap();
+    /// ll.push(2).unwrap();
+    ///
+    /// assert_eq!(ll.pop(), Ok(2));
+    /// assert_eq!(ll.pop(), Ok(1));
+    /// assert_eq!(ll.pop(), Err(()));
+    /// ```
+    pub fn pop(&mut self) -> Result<T, ()> {
+        if !self.is_empty() {
+            Ok(unsafe { self.pop_unchecked() })
+        } else {
+            Err(())
+        }
+    }
+
+    /// Checks if the linked list is full.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// assert_eq!(ll.is_full(), false);
+    ///
+    /// ll.push(1).unwrap();
+    /// assert_eq!(ll.is_full(), false);
+    /// ll.push(2).unwrap();
+    /// assert_eq!(ll.is_full(), false);
+    /// ll.push(3).unwrap();
+    /// assert_eq!(ll.is_full(), true);
+    /// ```
+    #[inline]
+    pub fn is_full(&self) -> bool {
+        self.free.option().is_none()
+    }
+
+    /// Checks if the linked list is empty.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// assert_eq!(ll.is_empty(), true);
+    ///
+    /// ll.push(1).unwrap();
+    /// assert_eq!(ll.is_empty(), false);
+    /// ```
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.head.option().is_none()
+    }
+}
+
+/// Iterator for the linked list.
+pub struct Iter<'a, T, Idx, K, const N: usize>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    list: &'a SortedLinkedList<T, Idx, K, N>,
+    index: Idx,
+}
+
+impl<'a, T, Idx, K, const N: usize> Iterator for Iter<'a, T, Idx, K, N>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    type Item = &'a T;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        let index = self.index.option()?;
+
+        let node = self.list.node_at(index);
+        self.index = node.next;
+
+        Some(self.list.read_data_in_node_at(index))
+    }
+}
+
+/// Comes from [`SortedLinkedList::find_mut`].
+pub struct FindMut<'a, T, Idx, K, const N: usize>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    list: &'a mut SortedLinkedList<T, Idx, K, N>,
+    is_head: bool,
+    prev_index: Idx,
+    index: Idx,
+    maybe_changed: bool,
+}
+
+impl<'a, T, Idx, K, const N: usize> FindMut<'a, T, Idx, K, N>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    fn pop_internal(&mut self) -> T {
+        if self.is_head {
+            // If it is the head element, we can do a normal pop
+            unsafe { self.list.pop_unchecked() }
+        } else {
+            // Somewhere in the list
+            let prev = unsafe { self.prev_index.get_unchecked() };
+            let curr = unsafe { self.index.get_unchecked() };
+
+            // Re-point the previous index
+            self.list.node_at_mut(prev).next = self.list.node_at_mut(curr).next;
+
+            // Release the index into the free queue
+            self.list.node_at_mut(curr).next = self.list.free;
+            self.list.free = self.index;
+
+            self.list.extract_data_in_node_at(curr)
+        }
+    }
+
+    /// This will pop the element from the list.
+    ///
+    /// Complexity is worst-case `O(1)`.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// ll.push(1).unwrap();
+    /// ll.push(2).unwrap();
+    /// ll.push(3).unwrap();
+    ///
+    /// // Find a value and update it
+    /// let mut find = ll.find_mut(|v| *v == 2).unwrap();
+    /// find.pop();
+    ///
+    /// assert_eq!(ll.pop(), Ok(3));
+    /// assert_eq!(ll.pop(), Ok(1));
+    /// assert_eq!(ll.pop(), Err(()));
+    /// ```
+    #[inline]
+    pub fn pop(mut self) -> T {
+        self.pop_internal()
+    }
+
+    /// This will resort the element into the correct position in the list if needed. The resorting
+    /// will only happen if the element has been accessed mutably.
+    ///
+    /// Same as calling `drop`.
+    ///
+    /// Complexity is worst-case `O(N)`.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use heapless::sorted_linked_list::{SortedLinkedList, Max};
+    /// let mut ll: SortedLinkedList<_, _, Max, 3> = SortedLinkedList::new_usize();
+    ///
+    /// ll.push(1).unwrap();
+    /// ll.push(2).unwrap();
+    /// ll.push(3).unwrap();
+    ///
+    /// let mut find = ll.find_mut(|v| *v == 2).unwrap();
+    /// find.finish(); // No resort, we did not access the value.
+    ///
+    /// let mut find = ll.find_mut(|v| *v == 2).unwrap();
+    /// *find += 1000;
+    /// find.finish(); // Will resort, we accessed (and updated) the value.
+    ///
+    /// assert_eq!(ll.pop(), Ok(1002));
+    /// assert_eq!(ll.pop(), Ok(3));
+    /// assert_eq!(ll.pop(), Ok(1));
+    /// assert_eq!(ll.pop(), Err(()));
+    /// ```
+    #[inline]
+    pub fn finish(self) {
+        drop(self)
+    }
+}
+
+impl<T, Idx, K, const N: usize> Drop for FindMut<'_, T, Idx, K, N>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    fn drop(&mut self) {
+        // Only resort the list if the element has changed
+        if self.maybe_changed {
+            let val = self.pop_internal();
+            unsafe { self.list.push_unchecked(val) };
+        }
+    }
+}
+
+impl<T, Idx, K, const N: usize> Deref for FindMut<'_, T, Idx, K, N>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    type Target = T;
+
+    fn deref(&self) -> &Self::Target {
+        self.list
+            .read_data_in_node_at(unsafe { self.index.get_unchecked() })
+    }
+}
+
+impl<T, Idx, K, const N: usize> DerefMut for FindMut<'_, T, Idx, K, N>
+where
+    T: Ord,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        self.maybe_changed = true;
+        self.list
+            .read_mut_data_in_node_at(unsafe { self.index.get_unchecked() })
+    }
+}
+
+// /// Useful for debug during development.
+// impl<T, Idx, K, const N: usize> fmt::Debug for FindMut<'_, T, Idx, K, N>
+// where
+//     T: Ord + core::fmt::Debug,
+//     Idx: SortedLinkedListIndex,
+//     K: Kind,
+// {
+//     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+//         f.debug_struct("FindMut")
+//             .field("prev_index", &self.prev_index.option())
+//             .field("index", &self.index.option())
+//             .field(
+//                 "prev_value",
+//                 &self
+//                     .list
+//                     .read_data_in_node_at(self.prev_index.option().unwrap()),
+//             )
+//             .field(
+//                 "value",
+//                 &self.list.read_data_in_node_at(self.index.option().unwrap()),
+//             )
+//             .finish()
+//     }
+// }
+
+impl<T, Idx, K, const N: usize> fmt::Debug for SortedLinkedList<T, Idx, K, N>
+where
+    T: Ord + core::fmt::Debug,
+    Idx: SortedLinkedListIndex,
+    K: Kind,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_list().entries(self.iter()).finish()
+    }
+}
+
+impl<T, Idx, K, const N: usize> Drop for SortedLinkedList<T, Idx, K, N>
+where
+    Idx: SortedLinkedListIndex,
+{
+    fn drop(&mut self) {
+        let mut index = self.head;
+
+        while let Some(i) = index.option() {
+            let node = self.node_at_mut(i);
+            index = node.next;
+
+            unsafe {
+                ptr::drop_in_place(node.val.as_mut_ptr());
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn const_new() {
+        static mut _V1: SortedLinkedList<u32, LinkedIndexU8, Max, 100> = SortedLinkedList::new_u8();
+        static mut _V2: SortedLinkedList<u32, LinkedIndexU16, Max, 10_000> =
+            SortedLinkedList::new_u16();
+        static mut _V3: SortedLinkedList<u32, LinkedIndexUsize, Max, 100_000> =
+            SortedLinkedList::new_usize();
+    }
+
+    #[test]
+    fn test_peek() {
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+
+        ll.push(1).unwrap();
+        assert_eq!(ll.peek().unwrap(), &1);
+
+        ll.push(2).unwrap();
+        assert_eq!(ll.peek().unwrap(), &2);
+
+        ll.push(3).unwrap();
+        assert_eq!(ll.peek().unwrap(), &3);
+
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Min, 3> = SortedLinkedList::new_usize();
+
+        ll.push(2).unwrap();
+        assert_eq!(ll.peek().unwrap(), &2);
+
+        ll.push(1).unwrap();
+        assert_eq!(ll.peek().unwrap(), &1);
+
+        ll.push(3).unwrap();
+        assert_eq!(ll.peek().unwrap(), &1);
+    }
+
+    #[test]
+    fn test_full() {
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+        ll.push(1).unwrap();
+        ll.push(2).unwrap();
+        ll.push(3).unwrap();
+
+        assert!(ll.is_full())
+    }
+
+    #[test]
+    fn test_empty() {
+        let ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+
+        assert!(ll.is_empty())
+    }
+
+    #[test]
+    fn test_zero_size() {
+        let ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 0> = SortedLinkedList::new_usize();
+
+        assert!(ll.is_empty());
+        assert!(ll.is_full());
+    }
+
+    #[test]
+    fn test_rejected_push() {
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+        ll.push(1).unwrap();
+        ll.push(2).unwrap();
+        ll.push(3).unwrap();
+
+        // This won't fit
+        let r = ll.push(4);
+
+        assert_eq!(r, Err(4));
+    }
+
+    #[test]
+    fn test_updating() {
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+        ll.push(1).unwrap();
+        ll.push(2).unwrap();
+        ll.push(3).unwrap();
+
+        let mut find = ll.find_mut(|v| *v == 2).unwrap();
+
+        *find += 1000;
+        find.finish();
+
+        assert_eq!(ll.peek().unwrap(), &1002);
+
+        let mut find = ll.find_mut(|v| *v == 3).unwrap();
+
+        *find += 1000;
+        find.finish();
+
+        assert_eq!(ll.peek().unwrap(), &1003);
+
+        // Remove largest element
+        ll.find_mut(|v| *v == 1003).unwrap().pop();
+
+        assert_eq!(ll.peek().unwrap(), &1002);
+    }
+
+    #[test]
+    fn test_updating_1() {
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+        ll.push(1).unwrap();
+
+        let v = ll.pop().unwrap();
+
+        assert_eq!(v, 1);
+    }
+
+    #[test]
+    fn test_updating_2() {
+        let mut ll: SortedLinkedList<u32, LinkedIndexUsize, Max, 3> = SortedLinkedList::new_usize();
+        ll.push(1).unwrap();
+
+        let mut find = ll.find_mut(|v| *v == 1).unwrap();
+
+        *find += 1000;
+        find.finish();
+
+        assert_eq!(ll.peek().unwrap(), &1001);
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/string.rs.html b/docs/doc/src/heapless/string.rs.html new file mode 100644 index 0000000..3009779 --- /dev/null +++ b/docs/doc/src/heapless/string.rs.html @@ -0,0 +1,1441 @@ +string.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+
use core::{cmp::Ordering, fmt, fmt::Write, hash, iter, ops, str};
+
+use hash32;
+
+use crate::Vec;
+
+/// A fixed capacity [`String`](https://doc.rust-lang.org/std/string/struct.String.html)
+pub struct String<const N: usize> {
+    vec: Vec<u8, N>,
+}
+
+impl<const N: usize> String<N> {
+    /// Constructs a new, empty `String` with a fixed capacity of `N` bytes
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// // allocate the string on the stack
+    /// let mut s: String<4> = String::new();
+    ///
+    /// // allocate the string in a static variable
+    /// static mut S: String<4> = String::new();
+    /// ```
+    #[inline]
+    pub const fn new() -> Self {
+        Self { vec: Vec::new() }
+    }
+
+    /// Converts a `String` into a byte vector.
+    ///
+    /// This consumes the `String`, so we do not need to copy its contents.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let s: String<4> = String::from("ab");
+    /// let b = s.into_bytes();
+    /// assert!(b.len() == 2);
+    ///
+    /// assert_eq!(&['a' as u8, 'b' as u8], &b[..]);
+    /// ```
+    #[inline]
+    pub fn into_bytes(self) -> Vec<u8, N> {
+        self.vec
+    }
+
+    /// Extracts a string slice containing the entire string.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<4> = String::from("ab");
+    /// assert!(s.as_str() == "ab");
+    ///
+    /// let _s = s.as_str();
+    /// // s.push('c'); // <- cannot borrow `s` as mutable because it is also borrowed as immutable
+    /// ```
+    #[inline]
+    pub fn as_str(&self) -> &str {
+        unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }
+    }
+
+    /// Converts a `String` into a mutable string slice.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<4> = String::from("ab");
+    /// let s = s.as_mut_str();
+    /// s.make_ascii_uppercase();
+    /// ```
+    #[inline]
+    pub fn as_mut_str(&mut self) -> &mut str {
+        unsafe { str::from_utf8_unchecked_mut(self.vec.as_mut_slice()) }
+    }
+
+    /// Returns a mutable reference to the contents of this `String`.
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe because it does not check that the bytes passed
+    /// to it are valid UTF-8. If this constraint is violated, it may cause
+    /// memory unsafety issues with future users of the `String`, as the rest of
+    /// the library assumes that `String`s are valid UTF-8.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// let mut s = String::from("hello");
+    ///
+    /// unsafe {
+    ///     let vec = s.as_mut_vec();
+    ///     assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
+    ///
+    ///     vec.reverse();
+    /// }
+    /// assert_eq!(s, "olleh");
+    /// ```
+    pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, N> {
+        &mut self.vec
+    }
+
+    /// Appends a given string slice onto the end of this `String`.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<8> = String::from("foo");
+    ///
+    /// assert!(s.push_str("bar").is_ok());
+    ///
+    /// assert_eq!("foobar", s);
+    ///
+    /// assert!(s.push_str("tender").is_err());
+    /// ```
+    #[inline]
+    pub fn push_str(&mut self, string: &str) -> Result<(), ()> {
+        self.vec.extend_from_slice(string.as_bytes())
+    }
+
+    /// Returns the maximum number of elements the String can hold
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<4> = String::new();
+    /// assert!(s.capacity() == 4);
+    /// ```
+    #[inline]
+    pub fn capacity(&self) -> usize {
+        self.vec.capacity()
+    }
+
+    /// Appends the given [`char`] to the end of this `String`.
+    ///
+    /// [`char`]: ../../std/primitive.char.html
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<8> = String::from("abc");
+    ///
+    /// s.push('1').unwrap();
+    /// s.push('2').unwrap();
+    /// s.push('3').unwrap();
+    ///
+    /// assert!("abc123" == s.as_str());
+    ///
+    /// assert_eq!("abc123", s);
+    /// ```
+    #[inline]
+    pub fn push(&mut self, c: char) -> Result<(), ()> {
+        match c.len_utf8() {
+            1 => self.vec.push(c as u8).map_err(|_| {}),
+            _ => self
+                .vec
+                .extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
+        }
+    }
+
+    /// Shortens this `String` to the specified length.
+    ///
+    /// If `new_len` is greater than the string's current length, this has no
+    /// effect.
+    ///
+    /// Note that this method has no effect on the allocated capacity
+    /// of the string
+    ///
+    /// # Panics
+    ///
+    /// Panics if `new_len` does not lie on a [`char`] boundary.
+    ///
+    /// [`char`]: ../../std/primitive.char.html
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<8> = String::from("hello");
+    ///
+    /// s.truncate(2);
+    ///
+    /// assert_eq!("he", s);
+    /// ```
+    #[inline]
+    pub fn truncate(&mut self, new_len: usize) {
+        if new_len <= self.len() {
+            assert!(self.is_char_boundary(new_len));
+            self.vec.truncate(new_len)
+        }
+    }
+
+    /// Removes the last character from the string buffer and returns it.
+    ///
+    /// Returns [`None`] if this `String` is empty.
+    ///
+    /// [`None`]: ../../std/option/enum.Option.html#variant.None
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<8> = String::from("foo");
+    ///
+    /// assert_eq!(s.pop(), Some('o'));
+    /// assert_eq!(s.pop(), Some('o'));
+    /// assert_eq!(s.pop(), Some('f'));
+    ///
+    /// assert_eq!(s.pop(), None);
+    /// ```
+    pub fn pop(&mut self) -> Option<char> {
+        let ch = self.chars().rev().next()?;
+
+        // pop bytes that correspond to `ch`
+        for _ in 0..ch.len_utf8() {
+            unsafe {
+                self.vec.pop_unchecked();
+            }
+        }
+
+        Some(ch)
+    }
+
+    /// Truncates this `String`, removing all contents.
+    ///
+    /// While this means the `String` will have a length of zero, it does not
+    /// touch its capacity.
+    ///
+    /// # Examples
+    ///
+    /// Basic usage:
+    ///
+    /// ```
+    /// use heapless::String;
+    ///
+    /// let mut s: String<8> = String::from("foo");
+    ///
+    /// s.clear();
+    ///
+    /// assert!(s.is_empty());
+    /// assert_eq!(0, s.len());
+    /// assert_eq!(8, s.capacity());
+    /// ```
+    #[inline]
+    pub fn clear(&mut self) {
+        self.vec.clear()
+    }
+}
+
+impl<const N: usize> Default for String<N> {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl<'a, const N: usize> From<&'a str> for String<N> {
+    fn from(s: &'a str) -> Self {
+        let mut new = String::new();
+        new.push_str(s).unwrap();
+        new
+    }
+}
+
+impl<const N: usize> str::FromStr for String<N> {
+    type Err = ();
+
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        let mut new = String::new();
+        new.push_str(s)?;
+        Ok(new)
+    }
+}
+
+impl<const N: usize> iter::FromIterator<char> for String<N> {
+    fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
+        let mut new = String::new();
+        for c in iter {
+            new.push(c).unwrap();
+        }
+        new
+    }
+}
+
+impl<'a, const N: usize> iter::FromIterator<&'a char> for String<N> {
+    fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
+        let mut new = String::new();
+        for c in iter {
+            new.push(*c).unwrap();
+        }
+        new
+    }
+}
+
+impl<'a, const N: usize> iter::FromIterator<&'a str> for String<N> {
+    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
+        let mut new = String::new();
+        for c in iter {
+            new.push_str(c).unwrap();
+        }
+        new
+    }
+}
+
+impl<const N: usize> Clone for String<N> {
+    fn clone(&self) -> Self {
+        Self {
+            vec: self.vec.clone(),
+        }
+    }
+}
+
+impl<const N: usize> fmt::Debug for String<N> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        <str as fmt::Debug>::fmt(self, f)
+    }
+}
+
+impl<const N: usize> fmt::Display for String<N> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        <str as fmt::Display>::fmt(self, f)
+    }
+}
+
+impl<const N: usize> hash::Hash for String<N> {
+    #[inline]
+    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
+        <str as hash::Hash>::hash(self, hasher)
+    }
+}
+
+impl<const N: usize> hash32::Hash for String<N> {
+    #[inline]
+    fn hash<H: hash32::Hasher>(&self, hasher: &mut H) {
+        <str as hash32::Hash>::hash(self, hasher)
+    }
+}
+
+impl<const N: usize> fmt::Write for String<N> {
+    fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
+        self.push_str(s).map_err(|_| fmt::Error)
+    }
+
+    fn write_char(&mut self, c: char) -> Result<(), fmt::Error> {
+        self.push(c).map_err(|_| fmt::Error)
+    }
+}
+
+impl<const N: usize> ops::Deref for String<N> {
+    type Target = str;
+
+    fn deref(&self) -> &str {
+        self.as_str()
+    }
+}
+
+impl<const N: usize> ops::DerefMut for String<N> {
+    fn deref_mut(&mut self) -> &mut str {
+        self.as_mut_str()
+    }
+}
+
+impl<const N: usize> AsRef<str> for String<N> {
+    #[inline]
+    fn as_ref(&self) -> &str {
+        self
+    }
+}
+
+impl<const N: usize> AsRef<[u8]> for String<N> {
+    #[inline]
+    fn as_ref(&self) -> &[u8] {
+        self.as_bytes()
+    }
+}
+
+impl<const N1: usize, const N2: usize> PartialEq<String<N2>> for String<N1> {
+    fn eq(&self, rhs: &String<N2>) -> bool {
+        str::eq(&**self, &**rhs)
+    }
+
+    fn ne(&self, rhs: &String<N2>) -> bool {
+        str::ne(&**self, &**rhs)
+    }
+}
+
+// String<N> == str
+impl<const N: usize> PartialEq<str> for String<N> {
+    #[inline]
+    fn eq(&self, other: &str) -> bool {
+        str::eq(&self[..], &other[..])
+    }
+    #[inline]
+    fn ne(&self, other: &str) -> bool {
+        str::ne(&self[..], &other[..])
+    }
+}
+
+// String<N> == &'str
+impl<const N: usize> PartialEq<&str> for String<N> {
+    #[inline]
+    fn eq(&self, other: &&str) -> bool {
+        str::eq(&self[..], &other[..])
+    }
+    #[inline]
+    fn ne(&self, other: &&str) -> bool {
+        str::ne(&self[..], &other[..])
+    }
+}
+
+// str == String<N>
+impl<const N: usize> PartialEq<String<N>> for str {
+    #[inline]
+    fn eq(&self, other: &String<N>) -> bool {
+        str::eq(&self[..], &other[..])
+    }
+    #[inline]
+    fn ne(&self, other: &String<N>) -> bool {
+        str::ne(&self[..], &other[..])
+    }
+}
+
+// &'str == String<N>
+impl<const N: usize> PartialEq<String<N>> for &str {
+    #[inline]
+    fn eq(&self, other: &String<N>) -> bool {
+        str::eq(&self[..], &other[..])
+    }
+    #[inline]
+    fn ne(&self, other: &String<N>) -> bool {
+        str::ne(&self[..], &other[..])
+    }
+}
+
+impl<const N: usize> Eq for String<N> {}
+
+impl<const N1: usize, const N2: usize> PartialOrd<String<N2>> for String<N1> {
+    #[inline]
+    fn partial_cmp(&self, other: &String<N2>) -> Option<Ordering> {
+        PartialOrd::partial_cmp(&**self, &**other)
+    }
+}
+
+impl<const N: usize> Ord for String<N> {
+    #[inline]
+    fn cmp(&self, other: &Self) -> Ordering {
+        Ord::cmp(&**self, &**other)
+    }
+}
+
+macro_rules! impl_from_num {
+    ($num:ty, $size:expr) => {
+        impl<const N: usize> From<$num> for String<N> {
+            fn from(s: $num) -> Self {
+                let mut new = String::new();
+                write!(&mut new, "{}", s).unwrap();
+                new
+            }
+        }
+    };
+}
+
+impl_from_num!(i8, 4);
+impl_from_num!(i16, 6);
+impl_from_num!(i32, 11);
+impl_from_num!(i64, 20);
+
+impl_from_num!(u8, 3);
+impl_from_num!(u16, 5);
+impl_from_num!(u32, 10);
+impl_from_num!(u64, 20);
+
+#[cfg(test)]
+mod tests {
+    use crate::{String, Vec};
+
+    #[test]
+    fn static_new() {
+        static mut _S: String<8> = String::new();
+    }
+
+    #[test]
+    fn clone() {
+        let s1: String<20> = String::from("abcd");
+        let mut s2 = s1.clone();
+        s2.push_str(" efgh").unwrap();
+
+        assert_eq!(s1, "abcd");
+        assert_eq!(s2, "abcd efgh");
+    }
+
+    #[test]
+    fn cmp() {
+        let s1: String<4> = String::from("abcd");
+        let s2: String<4> = String::from("zzzz");
+
+        assert!(s1 < s2);
+    }
+
+    #[test]
+    fn cmp_heterogenous_size() {
+        let s1: String<4> = String::from("abcd");
+        let s2: String<8> = String::from("zzzz");
+
+        assert!(s1 < s2);
+    }
+
+    #[test]
+    fn debug() {
+        use core::fmt::Write;
+
+        let s: String<8> = String::from("abcd");
+        let mut std_s = std::string::String::new();
+        write!(std_s, "{:?}", s).unwrap();
+        assert_eq!("\"abcd\"", std_s);
+    }
+
+    #[test]
+    fn display() {
+        use core::fmt::Write;
+
+        let s: String<8> = String::from("abcd");
+        let mut std_s = std::string::String::new();
+        write!(std_s, "{}", s).unwrap();
+        assert_eq!("abcd", std_s);
+    }
+
+    #[test]
+    fn empty() {
+        let s: String<4> = String::new();
+        assert!(s.capacity() == 4);
+        assert_eq!(s, "");
+        assert_eq!(s.len(), 0);
+        assert_ne!(s.len(), 4);
+    }
+
+    #[test]
+    fn from() {
+        let s: String<4> = String::from("123");
+        assert!(s.len() == 3);
+        assert_eq!(s, "123");
+    }
+
+    #[test]
+    fn from_str() {
+        use core::str::FromStr;
+
+        let s: String<4> = String::<4>::from_str("123").unwrap();
+        assert!(s.len() == 3);
+        assert_eq!(s, "123");
+
+        let e: () = String::<2>::from_str("123").unwrap_err();
+        assert_eq!(e, ());
+    }
+
+    #[test]
+    fn from_iter() {
+        let mut v: Vec<char, 5> = Vec::new();
+        v.push('h').unwrap();
+        v.push('e').unwrap();
+        v.push('l').unwrap();
+        v.push('l').unwrap();
+        v.push('o').unwrap();
+        let string1: String<5> = v.iter().collect(); //&char
+        let string2: String<5> = "hello".chars().collect(); //char
+        assert_eq!(string1, "hello");
+        assert_eq!(string2, "hello");
+    }
+
+    #[test]
+    #[should_panic]
+    fn from_panic() {
+        let _: String<4> = String::from("12345");
+    }
+
+    #[test]
+    fn from_num() {
+        let v: String<20> = String::from(18446744073709551615 as u64);
+        assert_eq!(v, "18446744073709551615");
+    }
+
+    #[test]
+    fn into_bytes() {
+        let s: String<4> = String::from("ab");
+        let b: Vec<u8, 4> = s.into_bytes();
+        assert_eq!(b.len(), 2);
+        assert_eq!(&['a' as u8, 'b' as u8], &b[..]);
+    }
+
+    #[test]
+    fn as_str() {
+        let s: String<4> = String::from("ab");
+
+        assert_eq!(s.as_str(), "ab");
+        // should be moved to fail test
+        //    let _s = s.as_str();
+        // s.push('c'); // <- cannot borrow `s` as mutable because it is also borrowed as immutable
+    }
+
+    #[test]
+    fn as_mut_str() {
+        let mut s: String<4> = String::from("ab");
+        let s = s.as_mut_str();
+        s.make_ascii_uppercase();
+        assert_eq!(s, "AB");
+    }
+
+    #[test]
+    fn push_str() {
+        let mut s: String<8> = String::from("foo");
+        assert!(s.push_str("bar").is_ok());
+        assert_eq!("foobar", s);
+        assert_eq!(s, "foobar");
+        assert!(s.push_str("tender").is_err());
+        assert_eq!("foobar", s);
+        assert_eq!(s, "foobar");
+    }
+
+    #[test]
+    fn push() {
+        let mut s: String<6> = String::from("abc");
+        assert!(s.push('1').is_ok());
+        assert!(s.push('2').is_ok());
+        assert!(s.push('3').is_ok());
+        assert!(s.push('4').is_err());
+        assert!("abc123" == s.as_str());
+    }
+
+    #[test]
+    fn as_bytes() {
+        let s: String<8> = String::from("hello");
+        assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
+    }
+
+    #[test]
+    fn truncate() {
+        let mut s: String<8> = String::from("hello");
+        s.truncate(6);
+        assert_eq!(s.len(), 5);
+        s.truncate(2);
+        assert_eq!(s.len(), 2);
+        assert_eq!("he", s);
+        assert_eq!(s, "he");
+    }
+
+    #[test]
+    fn pop() {
+        let mut s: String<8> = String::from("foo");
+        assert_eq!(s.pop(), Some('o'));
+        assert_eq!(s.pop(), Some('o'));
+        assert_eq!(s.pop(), Some('f'));
+        assert_eq!(s.pop(), None);
+    }
+
+    #[test]
+    fn pop_uenc() {
+        let mut s: String<8> = String::from("é");
+        assert_eq!(s.len(), 3);
+        match s.pop() {
+            Some(c) => {
+                assert_eq!(s.len(), 1);
+                assert_eq!(c, '\u{0301}'); // accute accent of e
+                ()
+            }
+            None => assert!(false),
+        };
+    }
+
+    #[test]
+    fn is_empty() {
+        let mut v: String<8> = String::new();
+        assert!(v.is_empty());
+        let _ = v.push('a');
+        assert!(!v.is_empty());
+    }
+
+    #[test]
+    fn clear() {
+        let mut s: String<8> = String::from("foo");
+        s.clear();
+        assert!(s.is_empty());
+        assert_eq!(0, s.len());
+        assert_eq!(8, s.capacity());
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/heapless/vec.rs.html b/docs/doc/src/heapless/vec.rs.html new file mode 100644 index 0000000..1f93453 --- /dev/null +++ b/docs/doc/src/heapless/vec.rs.html @@ -0,0 +1,3201 @@ +vec.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
+518
+519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
+537
+538
+539
+540
+541
+542
+543
+544
+545
+546
+547
+548
+549
+550
+551
+552
+553
+554
+555
+556
+557
+558
+559
+560
+561
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
+590
+591
+592
+593
+594
+595
+596
+597
+598
+599
+600
+601
+602
+603
+604
+605
+606
+607
+608
+609
+610
+611
+612
+613
+614
+615
+616
+617
+618
+619
+620
+621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
+666
+667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+742
+743
+744
+745
+746
+747
+748
+749
+750
+751
+752
+753
+754
+755
+756
+757
+758
+759
+760
+761
+762
+763
+764
+765
+766
+767
+768
+769
+770
+771
+772
+773
+774
+775
+776
+777
+778
+779
+780
+781
+782
+783
+784
+785
+786
+787
+788
+789
+790
+791
+792
+793
+794
+795
+796
+797
+798
+799
+800
+801
+802
+803
+804
+805
+806
+807
+808
+809
+810
+811
+812
+813
+814
+815
+816
+817
+818
+819
+820
+821
+822
+823
+824
+825
+826
+827
+828
+829
+830
+831
+832
+833
+834
+835
+836
+837
+838
+839
+840
+841
+842
+843
+844
+845
+846
+847
+848
+849
+850
+851
+852
+853
+854
+855
+856
+857
+858
+859
+860
+861
+862
+863
+864
+865
+866
+867
+868
+869
+870
+871
+872
+873
+874
+875
+876
+877
+878
+879
+880
+881
+882
+883
+884
+885
+886
+887
+888
+889
+890
+891
+892
+893
+894
+895
+896
+897
+898
+899
+900
+901
+902
+903
+904
+905
+906
+907
+908
+909
+910
+911
+912
+913
+914
+915
+916
+917
+918
+919
+920
+921
+922
+923
+924
+925
+926
+927
+928
+929
+930
+931
+932
+933
+934
+935
+936
+937
+938
+939
+940
+941
+942
+943
+944
+945
+946
+947
+948
+949
+950
+951
+952
+953
+954
+955
+956
+957
+958
+959
+960
+961
+962
+963
+964
+965
+966
+967
+968
+969
+970
+971
+972
+973
+974
+975
+976
+977
+978
+979
+980
+981
+982
+983
+984
+985
+986
+987
+988
+989
+990
+991
+992
+993
+994
+995
+996
+997
+998
+999
+1000
+1001
+1002
+1003
+1004
+1005
+1006
+1007
+1008
+1009
+1010
+1011
+1012
+1013
+1014
+1015
+1016
+1017
+1018
+1019
+1020
+1021
+1022
+1023
+1024
+1025
+1026
+1027
+1028
+1029
+1030
+1031
+1032
+1033
+1034
+1035
+1036
+1037
+1038
+1039
+1040
+1041
+1042
+1043
+1044
+1045
+1046
+1047
+1048
+1049
+1050
+1051
+1052
+1053
+1054
+1055
+1056
+1057
+1058
+1059
+1060
+1061
+1062
+1063
+1064
+1065
+1066
+1067
+1068
+1069
+1070
+1071
+1072
+1073
+1074
+1075
+1076
+1077
+1078
+1079
+1080
+1081
+1082
+1083
+1084
+1085
+1086
+1087
+1088
+1089
+1090
+1091
+1092
+1093
+1094
+1095
+1096
+1097
+1098
+1099
+1100
+1101
+1102
+1103
+1104
+1105
+1106
+1107
+1108
+1109
+1110
+1111
+1112
+1113
+1114
+1115
+1116
+1117
+1118
+1119
+1120
+1121
+1122
+1123
+1124
+1125
+1126
+1127
+1128
+1129
+1130
+1131
+1132
+1133
+1134
+1135
+1136
+1137
+1138
+1139
+1140
+1141
+1142
+1143
+1144
+1145
+1146
+1147
+1148
+1149
+1150
+1151
+1152
+1153
+1154
+1155
+1156
+1157
+1158
+1159
+1160
+1161
+1162
+1163
+1164
+1165
+1166
+1167
+1168
+1169
+1170
+1171
+1172
+1173
+1174
+1175
+1176
+1177
+1178
+1179
+1180
+1181
+1182
+1183
+1184
+1185
+1186
+1187
+1188
+1189
+1190
+1191
+1192
+1193
+1194
+1195
+1196
+1197
+1198
+1199
+1200
+1201
+1202
+1203
+1204
+1205
+1206
+1207
+1208
+1209
+1210
+1211
+1212
+1213
+1214
+1215
+1216
+1217
+1218
+1219
+1220
+1221
+1222
+1223
+1224
+1225
+1226
+1227
+1228
+1229
+1230
+1231
+1232
+1233
+1234
+1235
+1236
+1237
+1238
+1239
+1240
+1241
+1242
+1243
+1244
+1245
+1246
+1247
+1248
+1249
+1250
+1251
+1252
+1253
+1254
+1255
+1256
+1257
+1258
+1259
+1260
+1261
+1262
+1263
+1264
+1265
+1266
+1267
+1268
+1269
+1270
+1271
+1272
+1273
+1274
+1275
+1276
+1277
+1278
+1279
+1280
+1281
+1282
+1283
+1284
+1285
+1286
+1287
+1288
+1289
+1290
+1291
+1292
+1293
+1294
+1295
+1296
+1297
+1298
+1299
+1300
+1301
+1302
+1303
+1304
+1305
+1306
+1307
+1308
+1309
+1310
+1311
+1312
+1313
+1314
+1315
+1316
+1317
+1318
+1319
+1320
+1321
+1322
+1323
+1324
+1325
+1326
+1327
+1328
+1329
+1330
+1331
+1332
+1333
+1334
+1335
+1336
+1337
+1338
+1339
+1340
+1341
+1342
+1343
+1344
+1345
+1346
+1347
+1348
+1349
+1350
+1351
+1352
+1353
+1354
+1355
+1356
+1357
+1358
+1359
+1360
+1361
+1362
+1363
+1364
+1365
+1366
+1367
+1368
+1369
+1370
+1371
+1372
+1373
+1374
+1375
+1376
+1377
+1378
+1379
+1380
+1381
+1382
+1383
+1384
+1385
+1386
+1387
+1388
+1389
+1390
+1391
+1392
+1393
+1394
+1395
+1396
+1397
+1398
+1399
+1400
+1401
+1402
+1403
+1404
+1405
+1406
+1407
+1408
+1409
+1410
+1411
+1412
+1413
+1414
+1415
+1416
+1417
+1418
+1419
+1420
+1421
+1422
+1423
+1424
+1425
+1426
+1427
+1428
+1429
+1430
+1431
+1432
+1433
+1434
+1435
+1436
+1437
+1438
+1439
+1440
+1441
+1442
+1443
+1444
+1445
+1446
+1447
+1448
+1449
+1450
+1451
+1452
+1453
+1454
+1455
+1456
+1457
+1458
+1459
+1460
+1461
+1462
+1463
+1464
+1465
+1466
+1467
+1468
+1469
+1470
+1471
+1472
+1473
+1474
+1475
+1476
+1477
+1478
+1479
+1480
+1481
+1482
+1483
+1484
+1485
+1486
+1487
+1488
+1489
+1490
+1491
+1492
+1493
+1494
+1495
+1496
+1497
+1498
+1499
+1500
+1501
+1502
+1503
+1504
+1505
+1506
+1507
+1508
+1509
+1510
+1511
+1512
+1513
+1514
+1515
+1516
+1517
+1518
+1519
+1520
+1521
+1522
+1523
+1524
+1525
+1526
+1527
+1528
+1529
+1530
+1531
+1532
+1533
+1534
+1535
+1536
+1537
+1538
+1539
+1540
+1541
+1542
+1543
+1544
+1545
+1546
+1547
+1548
+1549
+1550
+1551
+1552
+1553
+1554
+1555
+1556
+1557
+1558
+1559
+1560
+1561
+1562
+1563
+1564
+1565
+1566
+1567
+1568
+1569
+1570
+1571
+1572
+1573
+1574
+1575
+1576
+1577
+1578
+1579
+1580
+1581
+1582
+1583
+1584
+1585
+1586
+1587
+1588
+1589
+1590
+1591
+1592
+1593
+1594
+1595
+1596
+1597
+1598
+1599
+1600
+
use core::{
+    cmp::Ordering, convert::TryFrom, fmt, hash, iter::FromIterator, mem::MaybeUninit, ops, ptr,
+    slice,
+};
+use hash32;
+
+/// A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
+///
+/// # Examples
+///
+/// ```
+/// use heapless::Vec;
+///
+///
+/// // A vector with a fixed capacity of 8 elements allocated on the stack
+/// let mut vec = Vec::<_, 8>::new();
+/// vec.push(1);
+/// vec.push(2);
+///
+/// assert_eq!(vec.len(), 2);
+/// assert_eq!(vec[0], 1);
+///
+/// assert_eq!(vec.pop(), Some(2));
+/// assert_eq!(vec.len(), 1);
+///
+/// vec[0] = 7;
+/// assert_eq!(vec[0], 7);
+///
+/// vec.extend([1, 2, 3].iter().cloned());
+///
+/// for x in &vec {
+///     println!("{}", x);
+/// }
+/// assert_eq!(*vec, [7, 1, 2, 3]);
+/// ```
+pub struct Vec<T, const N: usize> {
+    // NOTE order is important for optimizations. the `len` first layout lets the compiler optimize
+    // `new` to: reserve stack space and zero the first word. With the fields in the reverse order
+    // the compiler optimizes `new` to `memclr`-ing the *entire* stack space, including the `buffer`
+    // field which should be left uninitialized. Optimizations were last checked with Rust 1.60
+    len: usize,
+
+    buffer: [MaybeUninit<T>; N],
+}
+
+impl<T, const N: usize> Vec<T, N> {
+    const ELEM: MaybeUninit<T> = MaybeUninit::uninit();
+    const INIT: [MaybeUninit<T>; N] = [Self::ELEM; N]; // important for optimization of `new`
+
+    /// Constructs a new, empty vector with a fixed capacity of `N`
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// // allocate the vector on the stack
+    /// let mut x: Vec<u8, 16> = Vec::new();
+    ///
+    /// // allocate the vector in a static variable
+    /// static mut X: Vec<u8, 16> = Vec::new();
+    /// ```
+    /// `Vec` `const` constructor; wrap the returned value in [`Vec`](../struct.Vec.html)
+    pub const fn new() -> Self {
+        // Const assert N >= 0
+        crate::sealed::greater_than_eq_0::<N>();
+
+        Self {
+            len: 0,
+            buffer: Self::INIT,
+        }
+    }
+
+    /// Constructs a new vector with a fixed capacity of `N` and fills it
+    /// with the provided slice.
+    ///
+    /// This is equivalent to the following code:
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut v: Vec<u8, 16> = Vec::new();
+    /// v.extend_from_slice(&[1, 2, 3]).unwrap();
+    /// ```
+    #[inline]
+    pub fn from_slice(other: &[T]) -> Result<Self, ()>
+    where
+        T: Clone,
+    {
+        let mut v = Vec::new();
+        v.extend_from_slice(other)?;
+        Ok(v)
+    }
+
+    /// Clones a vec into a new vec
+    pub(crate) fn clone(&self) -> Self
+    where
+        T: Clone,
+    {
+        let mut new = Self::new();
+        // avoid `extend_from_slice` as that introduces a runtime check / panicking branch
+        for elem in self {
+            unsafe {
+                new.push_unchecked(elem.clone());
+            }
+        }
+        new
+    }
+
+    /// Returns a raw pointer to the vector’s buffer.
+    pub fn as_ptr(&self) -> *const T {
+        self.buffer.as_ptr() as *const T
+    }
+
+    /// Returns a raw pointer to the vector’s buffer, which may be mutated through.
+    pub fn as_mut_ptr(&mut self) -> *mut T {
+        self.buffer.as_mut_ptr() as *mut T
+    }
+
+    /// Extracts a slice containing the entire vector.
+    ///
+    /// Equivalent to `&s[..]`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    /// let buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+    /// assert_eq!(buffer.as_slice(), &[1, 2, 3, 5, 8]);
+    /// ```
+    pub fn as_slice(&self) -> &[T] {
+        // NOTE(unsafe) avoid bound checks in the slicing operation
+        // &buffer[..self.len]
+        unsafe { slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.len) }
+    }
+
+    /// Returns the contents of the vector as an array of length `M` if the length
+    /// of the vector is exactly `M`, otherwise returns `Err(self)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    /// let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+    /// let array: [u8; 5] = buffer.into_array().unwrap();
+    /// assert_eq!(array, [1, 2, 3, 5, 8]);
+    /// ```
+    pub fn into_array<const M: usize>(self) -> Result<[T; M], Self> {
+        if self.len() == M {
+            // This is how the unstable `MaybeUninit::array_assume_init` method does it
+            let array = unsafe { (&self.buffer as *const _ as *const [T; M]).read() };
+
+            // We don't want `self`'s destructor to be called because that would drop all the
+            // items in the array
+            core::mem::forget(self);
+
+            Ok(array)
+        } else {
+            Err(self)
+        }
+    }
+
+    /// Extracts a mutable slice containing the entire vector.
+    ///
+    /// Equivalent to `&s[..]`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    /// let mut buffer: Vec<u8, 5> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
+    /// buffer[0] = 9;
+    /// assert_eq!(buffer.as_slice(), &[9, 2, 3, 5, 8]);
+    /// ```
+    pub(crate) fn as_mut_slice(&mut self) -> &mut [T] {
+        // NOTE(unsafe) avoid bound checks in the slicing operation
+        // &mut buffer[..self.len]
+        unsafe { slice::from_raw_parts_mut(self.buffer.as_mut_ptr() as *mut T, self.len) }
+    }
+
+    /// Returns the maximum number of elements the vector can hold.
+    pub const fn capacity(&self) -> usize {
+        N
+    }
+
+    /// Clears the vector, removing all values.
+    pub fn clear(&mut self) {
+        self.truncate(0);
+    }
+
+    /// Extends the vec from an iterator.
+    ///
+    /// # Panic
+    ///
+    /// Panics if the vec cannot hold all elements of the iterator.
+    pub fn extend<I>(&mut self, iter: I)
+    where
+        I: IntoIterator<Item = T>,
+    {
+        for elem in iter {
+            self.push(elem).ok().unwrap()
+        }
+    }
+
+    /// Clones and appends all elements in a slice to the `Vec`.
+    ///
+    /// Iterates over the slice `other`, clones each element, and then appends
+    /// it to this `Vec`. The `other` vector is traversed in-order.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut vec = Vec::<u8, 8>::new();
+    /// vec.push(1).unwrap();
+    /// vec.extend_from_slice(&[2, 3, 4]).unwrap();
+    /// assert_eq!(*vec, [1, 2, 3, 4]);
+    /// ```
+    pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), ()>
+    where
+        T: Clone,
+    {
+        if self.len + other.len() > self.capacity() {
+            // won't fit in the `Vec`; don't modify anything and return an error
+            Err(())
+        } else {
+            for elem in other {
+                unsafe {
+                    self.push_unchecked(elem.clone());
+                }
+            }
+            Ok(())
+        }
+    }
+
+    /// Removes the last element from a vector and returns it, or `None` if it's empty
+    pub fn pop(&mut self) -> Option<T> {
+        if self.len != 0 {
+            Some(unsafe { self.pop_unchecked() })
+        } else {
+            None
+        }
+    }
+
+    /// Appends an `item` to the back of the collection
+    ///
+    /// Returns back the `item` if the vector is full
+    pub fn push(&mut self, item: T) -> Result<(), T> {
+        if self.len < self.capacity() {
+            unsafe { self.push_unchecked(item) }
+            Ok(())
+        } else {
+            Err(item)
+        }
+    }
+
+    /// Removes the last element from a vector and returns it
+    ///
+    /// # Safety
+    ///
+    /// This assumes the vec to have at least one element.
+    pub unsafe fn pop_unchecked(&mut self) -> T {
+        debug_assert!(!self.is_empty());
+
+        self.len -= 1;
+        (self.buffer.get_unchecked_mut(self.len).as_ptr() as *const T).read()
+    }
+
+    /// Appends an `item` to the back of the collection
+    ///
+    /// # Safety
+    ///
+    /// This assumes the vec is not full.
+    pub unsafe fn push_unchecked(&mut self, item: T) {
+        // NOTE(ptr::write) the memory slot that we are about to write to is uninitialized. We
+        // use `ptr::write` to avoid running `T`'s destructor on the uninitialized memory
+        debug_assert!(!self.is_full());
+
+        *self.buffer.get_unchecked_mut(self.len) = MaybeUninit::new(item);
+
+        self.len += 1;
+    }
+
+    /// Shortens the vector, keeping the first `len` elements and dropping the rest.
+    pub fn truncate(&mut self, len: usize) {
+        // This is safe because:
+        //
+        // * the slice passed to `drop_in_place` is valid; the `len > self.len`
+        //   case avoids creating an invalid slice, and
+        // * the `len` of the vector is shrunk before calling `drop_in_place`,
+        //   such that no value will be dropped twice in case `drop_in_place`
+        //   were to panic once (if it panics twice, the program aborts).
+        unsafe {
+            // Note: It's intentional that this is `>` and not `>=`.
+            //       Changing it to `>=` has negative performance
+            //       implications in some cases. See rust-lang/rust#78884 for more.
+            if len > self.len {
+                return;
+            }
+            let remaining_len = self.len - len;
+            let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
+            self.len = len;
+            ptr::drop_in_place(s);
+        }
+    }
+
+    /// Resizes the Vec in-place so that len is equal to new_len.
+    ///
+    /// If new_len is greater than len, the Vec is extended by the
+    /// difference, with each additional slot filled with value. If
+    /// new_len is less than len, the Vec is simply truncated.
+    ///
+    /// See also [`resize_default`](struct.Vec.html#method.resize_default).
+    pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), ()>
+    where
+        T: Clone,
+    {
+        if new_len > self.capacity() {
+            return Err(());
+        }
+
+        if new_len > self.len {
+            while self.len < new_len {
+                self.push(value.clone()).ok();
+            }
+        } else {
+            self.truncate(new_len);
+        }
+
+        Ok(())
+    }
+
+    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
+    ///
+    /// If `new_len` is greater than `len`, the `Vec` is extended by the
+    /// difference, with each additional slot filled with `Default::default()`.
+    /// If `new_len` is less than `len`, the `Vec` is simply truncated.
+    ///
+    /// See also [`resize`](struct.Vec.html#method.resize).
+    pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>
+    where
+        T: Clone + Default,
+    {
+        self.resize(new_len, T::default())
+    }
+
+    /// Forces the length of the vector to `new_len`.
+    ///
+    /// This is a low-level operation that maintains none of the normal
+    /// invariants of the type. Normally changing the length of a vector
+    /// is done using one of the safe operations instead, such as
+    /// [`truncate`], [`resize`], [`extend`], or [`clear`].
+    ///
+    /// [`truncate`]: #method.truncate
+    /// [`resize`]: #method.resize
+    /// [`extend`]: https://doc.rust-lang.org/stable/core/iter/trait.Extend.html#tymethod.extend
+    /// [`clear`]: #method.clear
+    ///
+    /// # Safety
+    ///
+    /// - `new_len` must be less than or equal to [`capacity()`].
+    /// - The elements at `old_len..new_len` must be initialized.
+    ///
+    /// [`capacity()`]: #method.capacity
+    ///
+    /// # Examples
+    ///
+    /// This method can be useful for situations in which the vector
+    /// is serving as a buffer for other code, particularly over FFI:
+    ///
+    /// ```no_run
+    /// # #![allow(dead_code)]
+    /// use heapless::Vec;
+    ///
+    /// # // This is just a minimal skeleton for the doc example;
+    /// # // don't use this as a starting point for a real library.
+    /// # pub struct StreamWrapper { strm: *mut core::ffi::c_void }
+    /// # const Z_OK: i32 = 0;
+    /// # extern "C" {
+    /// #     fn deflateGetDictionary(
+    /// #         strm: *mut core::ffi::c_void,
+    /// #         dictionary: *mut u8,
+    /// #         dictLength: *mut usize,
+    /// #     ) -> i32;
+    /// # }
+    /// # impl StreamWrapper {
+    /// pub fn get_dictionary(&self) -> Option<Vec<u8, 32768>> {
+    ///     // Per the FFI method's docs, "32768 bytes is always enough".
+    ///     let mut dict = Vec::new();
+    ///     let mut dict_length = 0;
+    ///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
+    ///     // 1. `dict_length` elements were initialized.
+    ///     // 2. `dict_length` <= the capacity (32_768)
+    ///     // which makes `set_len` safe to call.
+    ///     unsafe {
+    ///         // Make the FFI call...
+    ///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
+    ///         if r == Z_OK {
+    ///             // ...and update the length to what was initialized.
+    ///             dict.set_len(dict_length);
+    ///             Some(dict)
+    ///         } else {
+    ///             None
+    ///         }
+    ///     }
+    /// }
+    /// # }
+    /// ```
+    ///
+    /// While the following example is sound, there is a memory leak since
+    /// the inner vectors were not freed prior to the `set_len` call:
+    ///
+    /// ```
+    /// use core::iter::FromIterator;
+    /// use heapless::Vec;
+    ///
+    /// let mut vec = Vec::<Vec<u8, 3>, 3>::from_iter(
+    ///     [
+    ///         Vec::from_iter([1, 0, 0].iter().cloned()),
+    ///         Vec::from_iter([0, 1, 0].iter().cloned()),
+    ///         Vec::from_iter([0, 0, 1].iter().cloned()),
+    ///     ]
+    ///     .iter()
+    ///     .cloned()
+    /// );
+    /// // SAFETY:
+    /// // 1. `old_len..0` is empty so no elements need to be initialized.
+    /// // 2. `0 <= capacity` always holds whatever `capacity` is.
+    /// unsafe {
+    ///     vec.set_len(0);
+    /// }
+    /// ```
+    ///
+    /// Normally, here, one would use [`clear`] instead to correctly drop
+    /// the contents and thus not leak memory.
+    pub unsafe fn set_len(&mut self, new_len: usize) {
+        debug_assert!(new_len <= self.capacity());
+
+        self.len = new_len
+    }
+
+    /// Removes an element from the vector and returns it.
+    ///
+    /// The removed element is replaced by the last element of the vector.
+    ///
+    /// This does not preserve ordering, but is O(1).
+    ///
+    /// # Panics
+    ///
+    /// Panics if `index` is out of bounds.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///// use heapless::consts::*;
+    ///
+    /// let mut v: Vec<_, 8> = Vec::new();
+    /// v.push("foo").unwrap();
+    /// v.push("bar").unwrap();
+    /// v.push("baz").unwrap();
+    /// v.push("qux").unwrap();
+    ///
+    /// assert_eq!(v.swap_remove(1), "bar");
+    /// assert_eq!(&*v, ["foo", "qux", "baz"]);
+    ///
+    /// assert_eq!(v.swap_remove(0), "foo");
+    /// assert_eq!(&*v, ["baz", "qux"]);
+    /// ```
+    pub fn swap_remove(&mut self, index: usize) -> T {
+        assert!(index < self.len);
+        unsafe { self.swap_remove_unchecked(index) }
+    }
+
+    /// Removes an element from the vector and returns it.
+    ///
+    /// The removed element is replaced by the last element of the vector.
+    ///
+    /// This does not preserve ordering, but is O(1).
+    ///
+    /// # Safety
+    ///
+    ///  Assumes `index` within bounds.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut v: Vec<_, 8> = Vec::new();
+    /// v.push("foo").unwrap();
+    /// v.push("bar").unwrap();
+    /// v.push("baz").unwrap();
+    /// v.push("qux").unwrap();
+    ///
+    /// assert_eq!(unsafe { v.swap_remove_unchecked(1) }, "bar");
+    /// assert_eq!(&*v, ["foo", "qux", "baz"]);
+    ///
+    /// assert_eq!(unsafe { v.swap_remove_unchecked(0) }, "foo");
+    /// assert_eq!(&*v, ["baz", "qux"]);
+    /// ```
+    pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T {
+        let length = self.len();
+        debug_assert!(index < length);
+        let value = ptr::read(self.as_ptr().add(index));
+        let base_ptr = self.as_mut_ptr();
+        ptr::copy(base_ptr.add(length - 1), base_ptr.add(index), 1);
+        self.len -= 1;
+        value
+    }
+
+    /// Returns true if the vec is full
+    #[inline]
+    pub fn is_full(&self) -> bool {
+        self.len == self.capacity()
+    }
+
+    /// Returns true if the vec is empty
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    /// Returns `true` if `needle` is a prefix of the Vec.
+    ///
+    /// Always returns `true` if `needle` is an empty slice.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+    /// assert_eq!(v.starts_with(b""), true);
+    /// assert_eq!(v.starts_with(b"ab"), true);
+    /// assert_eq!(v.starts_with(b"bc"), false);
+    /// ```
+    #[inline]
+    pub fn starts_with(&self, needle: &[T]) -> bool
+    where
+        T: PartialEq,
+    {
+        let n = needle.len();
+        self.len >= n && needle == &self[..n]
+    }
+
+    /// Returns `true` if `needle` is a suffix of the Vec.
+    ///
+    /// Always returns `true` if `needle` is an empty slice.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let v: Vec<_, 8> = Vec::from_slice(b"abc").unwrap();
+    /// assert_eq!(v.ends_with(b""), true);
+    /// assert_eq!(v.ends_with(b"ab"), false);
+    /// assert_eq!(v.ends_with(b"bc"), true);
+    /// ```
+    #[inline]
+    pub fn ends_with(&self, needle: &[T]) -> bool
+    where
+        T: PartialEq,
+    {
+        let (v, n) = (self.len(), needle.len());
+        v >= n && needle == &self[v - n..]
+    }
+
+    /// Inserts an element at position `index` within the vector, shifting all
+    /// elements after it to the right.
+    ///
+    /// Returns back the `element` if the vector is full.
+    ///
+    /// # Panics
+    ///
+    /// Panics if `index > len`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+    /// vec.insert(1, 4);
+    /// assert_eq!(vec, [1, 4, 2, 3]);
+    /// vec.insert(4, 5);
+    /// assert_eq!(vec, [1, 4, 2, 3, 5]);
+    /// ```
+    pub fn insert(&mut self, index: usize, element: T) -> Result<(), T> {
+        let len = self.len();
+        if index > len {
+            panic!(
+                "insertion index (is {}) should be <= len (is {})",
+                index, len
+            );
+        }
+
+        // check there's space for the new element
+        if self.is_full() {
+            return Err(element);
+        }
+
+        unsafe {
+            // infallible
+            // The spot to put the new value
+            {
+                let p = self.as_mut_ptr().add(index);
+                // Shift everything over to make space. (Duplicating the
+                // `index`th element into two consecutive places.)
+                ptr::copy(p, p.offset(1), len - index);
+                // Write it in, overwriting the first copy of the `index`th
+                // element.
+                ptr::write(p, element);
+            }
+            self.set_len(len + 1);
+        }
+
+        Ok(())
+    }
+
+    /// Removes and returns the element at position `index` within the vector,
+    /// shifting all elements after it to the left.
+    ///
+    /// Note: Because this shifts over the remaining elements, it has a
+    /// worst-case performance of *O*(*n*). If you don't need the order of
+    /// elements to be preserved, use [`swap_remove`] instead. If you'd like to
+    /// remove elements from the beginning of the `Vec`, consider using
+    /// [`Deque::pop_front`] instead.
+    ///
+    /// [`swap_remove`]: Vec::swap_remove
+    /// [`Deque::pop_front`]: crate::Deque::pop_front
+    ///
+    /// # Panics
+    ///
+    /// Panics if `index` is out of bounds.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut v: Vec<_, 8> = Vec::from_slice(&[1, 2, 3]).unwrap();
+    /// assert_eq!(v.remove(1), 2);
+    /// assert_eq!(v, [1, 3]);
+    /// ```
+    pub fn remove(&mut self, index: usize) -> T {
+        let len = self.len();
+        if index >= len {
+            panic!("removal index (is {}) should be < len (is {})", index, len);
+        }
+        unsafe {
+            // infallible
+            let ret;
+            {
+                // the place we are taking from.
+                let ptr = self.as_mut_ptr().add(index);
+                // copy it out, unsafely having a copy of the value on
+                // the stack and in the vector at the same time.
+                ret = ptr::read(ptr);
+
+                // Shift everything down to fill in that spot.
+                ptr::copy(ptr.offset(1), ptr, len - index - 1);
+            }
+            self.set_len(len - 1);
+            ret
+        }
+    }
+
+    /// Retains only the elements specified by the predicate.
+    ///
+    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
+    /// This method operates in place, visiting each element exactly once in the
+    /// original order, and preserves the order of the retained elements.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+    /// vec.retain(|&x| x % 2 == 0);
+    /// assert_eq!(vec, [2, 4]);
+    /// ```
+    ///
+    /// Because the elements are visited exactly once in the original order,
+    /// external state may be used to decide which elements to keep.
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4, 5]).unwrap();
+    /// let keep = [false, true, true, false, true];
+    /// let mut iter = keep.iter();
+    /// vec.retain(|_| *iter.next().unwrap());
+    /// assert_eq!(vec, [2, 3, 5]);
+    /// ```
+    pub fn retain<F>(&mut self, mut f: F)
+    where
+        F: FnMut(&T) -> bool,
+    {
+        self.retain_mut(|elem| f(elem));
+    }
+
+    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
+    ///
+    /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
+    /// This method operates in place, visiting each element exactly once in the
+    /// original order, and preserves the order of the retained elements.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use heapless::Vec;
+    ///
+    /// let mut vec: Vec<_, 8> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
+    /// vec.retain_mut(|x| if *x <= 3 {
+    ///     *x += 1;
+    ///     true
+    /// } else {
+    ///     false
+    /// });
+    /// assert_eq!(vec, [2, 3, 4]);
+    /// ```
+    pub fn retain_mut<F>(&mut self, mut f: F)
+    where
+        F: FnMut(&mut T) -> bool,
+    {
+        let original_len = self.len();
+        // Avoid double drop if the drop guard is not executed,
+        // since we may make some holes during the process.
+        unsafe { self.set_len(0) };
+
+        // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
+        //      |<-              processed len   ->| ^- next to check
+        //                  |<-  deleted cnt     ->|
+        //      |<-              original_len                          ->|
+        // Kept: Elements which predicate returns true on.
+        // Hole: Moved or dropped element slot.
+        // Unchecked: Unchecked valid elements.
+        //
+        // This drop guard will be invoked when predicate or `drop` of element panicked.
+        // It shifts unchecked elements to cover holes and `set_len` to the correct length.
+        // In cases when predicate and `drop` never panick, it will be optimized out.
+        struct BackshiftOnDrop<'a, T, const N: usize> {
+            v: &'a mut Vec<T, N>,
+            processed_len: usize,
+            deleted_cnt: usize,
+            original_len: usize,
+        }
+
+        impl<T, const N: usize> Drop for BackshiftOnDrop<'_, T, N> {
+            fn drop(&mut self) {
+                if self.deleted_cnt > 0 {
+                    // SAFETY: Trailing unchecked items must be valid since we never touch them.
+                    unsafe {
+                        ptr::copy(
+                            self.v.as_ptr().add(self.processed_len),
+                            self.v
+                                .as_mut_ptr()
+                                .add(self.processed_len - self.deleted_cnt),
+                            self.original_len - self.processed_len,
+                        );
+                    }
+                }
+                // SAFETY: After filling holes, all items are in contiguous memory.
+                unsafe {
+                    self.v.set_len(self.original_len - self.deleted_cnt);
+                }
+            }
+        }
+
+        let mut g = BackshiftOnDrop {
+            v: self,
+            processed_len: 0,
+            deleted_cnt: 0,
+            original_len,
+        };
+
+        fn process_loop<F, T, const N: usize, const DELETED: bool>(
+            original_len: usize,
+            f: &mut F,
+            g: &mut BackshiftOnDrop<'_, T, N>,
+        ) where
+            F: FnMut(&mut T) -> bool,
+        {
+            while g.processed_len != original_len {
+                let p = g.v.as_mut_ptr();
+                // SAFETY: Unchecked element must be valid.
+                let cur = unsafe { &mut *p.add(g.processed_len) };
+                if !f(cur) {
+                    // Advance early to avoid double drop if `drop_in_place` panicked.
+                    g.processed_len += 1;
+                    g.deleted_cnt += 1;
+                    // SAFETY: We never touch this element again after dropped.
+                    unsafe { ptr::drop_in_place(cur) };
+                    // We already advanced the counter.
+                    if DELETED {
+                        continue;
+                    } else {
+                        break;
+                    }
+                }
+                if DELETED {
+                    // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
+                    // We use copy for move, and never touch this element again.
+                    unsafe {
+                        let hole_slot = p.add(g.processed_len - g.deleted_cnt);
+                        ptr::copy_nonoverlapping(cur, hole_slot, 1);
+                    }
+                }
+                g.processed_len += 1;
+            }
+        }
+
+        // Stage 1: Nothing was deleted.
+        process_loop::<F, T, N, false>(original_len, &mut f, &mut g);
+
+        // Stage 2: Some elements were deleted.
+        process_loop::<F, T, N, true>(original_len, &mut f, &mut g);
+
+        // All item are processed. This can be optimized to `set_len` by LLVM.
+        drop(g);
+    }
+}
+
+// Trait implementations
+
+impl<T, const N: usize> Default for Vec<T, N> {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl<T, const N: usize> fmt::Debug for Vec<T, N>
+where
+    T: fmt::Debug,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        <[T] as fmt::Debug>::fmt(self, f)
+    }
+}
+
+impl<const N: usize> fmt::Write for Vec<u8, N> {
+    fn write_str(&mut self, s: &str) -> fmt::Result {
+        match self.extend_from_slice(s.as_bytes()) {
+            Ok(()) => Ok(()),
+            Err(_) => Err(fmt::Error),
+        }
+    }
+}
+
+impl<T, const N: usize> Drop for Vec<T, N> {
+    fn drop(&mut self) {
+        // We drop each element used in the vector by turning into a &mut[T]
+        unsafe {
+            ptr::drop_in_place(self.as_mut_slice());
+        }
+    }
+}
+
+impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec<T, N> {
+    type Error = ();
+
+    fn try_from(slice: &'a [T]) -> Result<Self, Self::Error> {
+        Vec::from_slice(slice)
+    }
+}
+
+impl<T, const N: usize> Extend<T> for Vec<T, N> {
+    fn extend<I>(&mut self, iter: I)
+    where
+        I: IntoIterator<Item = T>,
+    {
+        self.extend(iter)
+    }
+}
+
+impl<'a, T, const N: usize> Extend<&'a T> for Vec<T, N>
+where
+    T: 'a + Copy,
+{
+    fn extend<I>(&mut self, iter: I)
+    where
+        I: IntoIterator<Item = &'a T>,
+    {
+        self.extend(iter.into_iter().cloned())
+    }
+}
+
+impl<T, const N: usize> hash::Hash for Vec<T, N>
+where
+    T: core::hash::Hash,
+{
+    fn hash<H: hash::Hasher>(&self, state: &mut H) {
+        <[T] as hash::Hash>::hash(self, state)
+    }
+}
+
+impl<T, const N: usize> hash32::Hash for Vec<T, N>
+where
+    T: hash32::Hash,
+{
+    fn hash<H: hash32::Hasher>(&self, state: &mut H) {
+        <[T] as hash32::Hash>::hash(self, state)
+    }
+}
+
+impl<'a, T, const N: usize> IntoIterator for &'a Vec<T, N> {
+    type Item = &'a T;
+    type IntoIter = slice::Iter<'a, T>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter()
+    }
+}
+
+impl<'a, T, const N: usize> IntoIterator for &'a mut Vec<T, N> {
+    type Item = &'a mut T;
+    type IntoIter = slice::IterMut<'a, T>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.iter_mut()
+    }
+}
+
+impl<T, const N: usize> FromIterator<T> for Vec<T, N> {
+    fn from_iter<I>(iter: I) -> Self
+    where
+        I: IntoIterator<Item = T>,
+    {
+        let mut vec = Vec::new();
+        for i in iter {
+            vec.push(i).ok().expect("Vec::from_iter overflow");
+        }
+        vec
+    }
+}
+
+/// An iterator that moves out of an [`Vec`][`Vec`].
+///
+/// This struct is created by calling the `into_iter` method on [`Vec`][`Vec`].
+///
+/// [`Vec`]: (https://doc.rust-lang.org/std/vec/struct.Vec.html)
+///
+pub struct IntoIter<T, const N: usize> {
+    vec: Vec<T, N>,
+    next: usize,
+}
+
+impl<T, const N: usize> Iterator for IntoIter<T, N> {
+    type Item = T;
+    fn next(&mut self) -> Option<Self::Item> {
+        if self.next < self.vec.len() {
+            let item = unsafe {
+                (self.vec.buffer.get_unchecked_mut(self.next).as_ptr() as *const T).read()
+            };
+            self.next += 1;
+            Some(item)
+        } else {
+            None
+        }
+    }
+}
+
+impl<T, const N: usize> Clone for IntoIter<T, N>
+where
+    T: Clone,
+{
+    fn clone(&self) -> Self {
+        let mut vec = Vec::new();
+
+        if self.next < self.vec.len() {
+            let s = unsafe {
+                slice::from_raw_parts(
+                    (self.vec.buffer.as_ptr() as *const T).add(self.next),
+                    self.vec.len() - self.next,
+                )
+            };
+            vec.extend_from_slice(s).ok();
+        }
+
+        Self { vec, next: 0 }
+    }
+}
+
+impl<T, const N: usize> Drop for IntoIter<T, N> {
+    fn drop(&mut self) {
+        unsafe {
+            // Drop all the elements that have not been moved out of vec
+            ptr::drop_in_place(&mut self.vec.as_mut_slice()[self.next..]);
+            // Prevent dropping of other elements
+            self.vec.len = 0;
+        }
+    }
+}
+
+impl<T, const N: usize> IntoIterator for Vec<T, N> {
+    type Item = T;
+    type IntoIter = IntoIter<T, N>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        IntoIter { vec: self, next: 0 }
+    }
+}
+
+impl<A, B, const N1: usize, const N2: usize> PartialEq<Vec<B, N2>> for Vec<A, N1>
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &Vec<B, N2>) -> bool {
+        <[A]>::eq(self, &**other)
+    }
+}
+
+// Vec<A, N> == [B]
+impl<A, B, const N: usize> PartialEq<[B]> for Vec<A, N>
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &[B]) -> bool {
+        <[A]>::eq(self, &other[..])
+    }
+}
+
+// [B] == Vec<A, N>
+impl<A, B, const N: usize> PartialEq<Vec<A, N>> for [B]
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &Vec<A, N>) -> bool {
+        <[A]>::eq(other, &self[..])
+    }
+}
+
+// Vec<A, N> == &[B]
+impl<A, B, const N: usize> PartialEq<&[B]> for Vec<A, N>
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &&[B]) -> bool {
+        <[A]>::eq(self, &other[..])
+    }
+}
+
+// &[B] == Vec<A, N>
+impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &[B]
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &Vec<A, N>) -> bool {
+        <[A]>::eq(other, &self[..])
+    }
+}
+
+// Vec<A, N> == &mut [B]
+impl<A, B, const N: usize> PartialEq<&mut [B]> for Vec<A, N>
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &&mut [B]) -> bool {
+        <[A]>::eq(self, &other[..])
+    }
+}
+
+// &mut [B] == Vec<A, N>
+impl<A, B, const N: usize> PartialEq<Vec<A, N>> for &mut [B]
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &Vec<A, N>) -> bool {
+        <[A]>::eq(other, &self[..])
+    }
+}
+
+// Vec<A, N> == [B; M]
+// Equality does not require equal capacity
+impl<A, B, const N: usize, const M: usize> PartialEq<[B; M]> for Vec<A, N>
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &[B; M]) -> bool {
+        <[A]>::eq(self, &other[..])
+    }
+}
+
+// [B; M] == Vec<A, N>
+// Equality does not require equal capacity
+impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for [B; M]
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &Vec<A, N>) -> bool {
+        <[A]>::eq(other, &self[..])
+    }
+}
+
+// Vec<A, N> == &[B; M]
+// Equality does not require equal capacity
+impl<A, B, const N: usize, const M: usize> PartialEq<&[B; M]> for Vec<A, N>
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &&[B; M]) -> bool {
+        <[A]>::eq(self, &other[..])
+    }
+}
+
+// &[B; M] == Vec<A, N>
+// Equality does not require equal capacity
+impl<A, B, const N: usize, const M: usize> PartialEq<Vec<A, N>> for &[B; M]
+where
+    A: PartialEq<B>,
+{
+    fn eq(&self, other: &Vec<A, N>) -> bool {
+        <[A]>::eq(other, &self[..])
+    }
+}
+
+// Implements Eq if underlying data is Eq
+impl<T, const N: usize> Eq for Vec<T, N> where T: Eq {}
+
+impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>
+where
+    T: PartialOrd,
+{
+    fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering> {
+        PartialOrd::partial_cmp(&**self, &**other)
+    }
+}
+
+impl<T, const N: usize> Ord for Vec<T, N>
+where
+    T: Ord,
+{
+    #[inline]
+    fn cmp(&self, other: &Self) -> Ordering {
+        Ord::cmp(&**self, &**other)
+    }
+}
+
+impl<T, const N: usize> ops::Deref for Vec<T, N> {
+    type Target = [T];
+
+    fn deref(&self) -> &[T] {
+        self.as_slice()
+    }
+}
+
+impl<T, const N: usize> ops::DerefMut for Vec<T, N> {
+    fn deref_mut(&mut self) -> &mut [T] {
+        self.as_mut_slice()
+    }
+}
+
+impl<T, const N: usize> AsRef<Vec<T, N>> for Vec<T, N> {
+    #[inline]
+    fn as_ref(&self) -> &Self {
+        self
+    }
+}
+
+impl<T, const N: usize> AsMut<Vec<T, N>> for Vec<T, N> {
+    #[inline]
+    fn as_mut(&mut self) -> &mut Self {
+        self
+    }
+}
+
+impl<T, const N: usize> AsRef<[T]> for Vec<T, N> {
+    #[inline]
+    fn as_ref(&self) -> &[T] {
+        self
+    }
+}
+
+impl<T, const N: usize> AsMut<[T]> for Vec<T, N> {
+    #[inline]
+    fn as_mut(&mut self) -> &mut [T] {
+        self
+    }
+}
+
+impl<T, const N: usize> Clone for Vec<T, N>
+where
+    T: Clone,
+{
+    fn clone(&self) -> Self {
+        self.clone()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::Vec;
+    use core::fmt::Write;
+
+    #[test]
+    fn static_new() {
+        static mut _V: Vec<i32, 4> = Vec::new();
+    }
+
+    #[test]
+    fn stack_new() {
+        let mut _v: Vec<i32, 4> = Vec::new();
+    }
+
+    #[test]
+    fn is_full_empty() {
+        let mut v: Vec<i32, 4> = Vec::new();
+
+        assert!(v.is_empty());
+        assert!(!v.is_full());
+
+        v.push(1).unwrap();
+        assert!(!v.is_empty());
+        assert!(!v.is_full());
+
+        v.push(1).unwrap();
+        assert!(!v.is_empty());
+        assert!(!v.is_full());
+
+        v.push(1).unwrap();
+        assert!(!v.is_empty());
+        assert!(!v.is_full());
+
+        v.push(1).unwrap();
+        assert!(!v.is_empty());
+        assert!(v.is_full());
+    }
+
+    #[test]
+    fn drop() {
+        droppable!();
+
+        {
+            let mut v: Vec<Droppable, 2> = Vec::new();
+            v.push(Droppable::new()).ok().unwrap();
+            v.push(Droppable::new()).ok().unwrap();
+            v.pop().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut v: Vec<Droppable, 2> = Vec::new();
+            v.push(Droppable::new()).ok().unwrap();
+            v.push(Droppable::new()).ok().unwrap();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+    }
+
+    #[test]
+    fn eq() {
+        let mut xs: Vec<i32, 4> = Vec::new();
+        let mut ys: Vec<i32, 8> = Vec::new();
+
+        assert_eq!(xs, ys);
+
+        xs.push(1).unwrap();
+        ys.push(1).unwrap();
+
+        assert_eq!(xs, ys);
+    }
+
+    #[test]
+    fn cmp() {
+        let mut xs: Vec<i32, 4> = Vec::new();
+        let mut ys: Vec<i32, 4> = Vec::new();
+
+        assert_eq!(xs, ys);
+
+        xs.push(1).unwrap();
+        ys.push(2).unwrap();
+
+        assert!(xs < ys);
+    }
+
+    #[test]
+    fn cmp_heterogenous_size() {
+        let mut xs: Vec<i32, 4> = Vec::new();
+        let mut ys: Vec<i32, 8> = Vec::new();
+
+        assert_eq!(xs, ys);
+
+        xs.push(1).unwrap();
+        ys.push(2).unwrap();
+
+        assert!(xs < ys);
+    }
+
+    #[test]
+    fn cmp_with_arrays_and_slices() {
+        let mut xs: Vec<i32, 12> = Vec::new();
+        xs.push(1).unwrap();
+
+        let array = [1];
+
+        assert_eq!(xs, array);
+        assert_eq!(array, xs);
+
+        assert_eq!(xs, array.as_slice());
+        assert_eq!(array.as_slice(), xs);
+
+        assert_eq!(xs, &array);
+        assert_eq!(&array, xs);
+
+        let longer_array = [1; 20];
+
+        assert_ne!(xs, longer_array);
+        assert_ne!(longer_array, xs);
+    }
+
+    #[test]
+    fn full() {
+        let mut v: Vec<i32, 4> = Vec::new();
+
+        v.push(0).unwrap();
+        v.push(1).unwrap();
+        v.push(2).unwrap();
+        v.push(3).unwrap();
+
+        assert!(v.push(4).is_err());
+    }
+
+    #[test]
+    fn iter() {
+        let mut v: Vec<i32, 4> = Vec::new();
+
+        v.push(0).unwrap();
+        v.push(1).unwrap();
+        v.push(2).unwrap();
+        v.push(3).unwrap();
+
+        let mut items = v.iter();
+
+        assert_eq!(items.next(), Some(&0));
+        assert_eq!(items.next(), Some(&1));
+        assert_eq!(items.next(), Some(&2));
+        assert_eq!(items.next(), Some(&3));
+        assert_eq!(items.next(), None);
+    }
+
+    #[test]
+    fn iter_mut() {
+        let mut v: Vec<i32, 4> = Vec::new();
+
+        v.push(0).unwrap();
+        v.push(1).unwrap();
+        v.push(2).unwrap();
+        v.push(3).unwrap();
+
+        let mut items = v.iter_mut();
+
+        assert_eq!(items.next(), Some(&mut 0));
+        assert_eq!(items.next(), Some(&mut 1));
+        assert_eq!(items.next(), Some(&mut 2));
+        assert_eq!(items.next(), Some(&mut 3));
+        assert_eq!(items.next(), None);
+    }
+
+    #[test]
+    fn collect_from_iter() {
+        let slice = &[1, 2, 3];
+        let vec: Vec<i32, 4> = slice.iter().cloned().collect();
+        assert_eq!(&vec, slice);
+    }
+
+    #[test]
+    #[should_panic]
+    fn collect_from_iter_overfull() {
+        let slice = &[1, 2, 3];
+        let _vec = slice.iter().cloned().collect::<Vec<_, 2>>();
+    }
+
+    #[test]
+    fn iter_move() {
+        let mut v: Vec<i32, 4> = Vec::new();
+        v.push(0).unwrap();
+        v.push(1).unwrap();
+        v.push(2).unwrap();
+        v.push(3).unwrap();
+
+        let mut items = v.into_iter();
+
+        assert_eq!(items.next(), Some(0));
+        assert_eq!(items.next(), Some(1));
+        assert_eq!(items.next(), Some(2));
+        assert_eq!(items.next(), Some(3));
+        assert_eq!(items.next(), None);
+    }
+
+    #[test]
+    fn iter_move_drop() {
+        droppable!();
+
+        {
+            let mut vec: Vec<Droppable, 2> = Vec::new();
+            vec.push(Droppable::new()).ok().unwrap();
+            vec.push(Droppable::new()).ok().unwrap();
+            let mut items = vec.into_iter();
+            // Move all
+            let _ = items.next();
+            let _ = items.next();
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut vec: Vec<Droppable, 2> = Vec::new();
+            vec.push(Droppable::new()).ok().unwrap();
+            vec.push(Droppable::new()).ok().unwrap();
+            let _items = vec.into_iter();
+            // Move none
+        }
+
+        assert_eq!(Droppable::count(), 0);
+
+        {
+            let mut vec: Vec<Droppable, 2> = Vec::new();
+            vec.push(Droppable::new()).ok().unwrap();
+            vec.push(Droppable::new()).ok().unwrap();
+            let mut items = vec.into_iter();
+            let _ = items.next(); // Move partly
+        }
+
+        assert_eq!(Droppable::count(), 0);
+    }
+
+    #[test]
+    fn push_and_pop() {
+        let mut v: Vec<i32, 4> = Vec::new();
+        assert_eq!(v.len(), 0);
+
+        assert_eq!(v.pop(), None);
+        assert_eq!(v.len(), 0);
+
+        v.push(0).unwrap();
+        assert_eq!(v.len(), 1);
+
+        assert_eq!(v.pop(), Some(0));
+        assert_eq!(v.len(), 0);
+
+        assert_eq!(v.pop(), None);
+        assert_eq!(v.len(), 0);
+    }
+
+    #[test]
+    fn resize_size_limit() {
+        let mut v: Vec<u8, 4> = Vec::new();
+
+        v.resize(0, 0).unwrap();
+        v.resize(4, 0).unwrap();
+        v.resize(5, 0).err().expect("full");
+    }
+
+    #[test]
+    fn resize_length_cases() {
+        let mut v: Vec<u8, 4> = Vec::new();
+
+        assert_eq!(v.len(), 0);
+
+        // Grow by 1
+        v.resize(1, 0).unwrap();
+        assert_eq!(v.len(), 1);
+
+        // Grow by 2
+        v.resize(3, 0).unwrap();
+        assert_eq!(v.len(), 3);
+
+        // Resize to current size
+        v.resize(3, 0).unwrap();
+        assert_eq!(v.len(), 3);
+
+        // Shrink by 1
+        v.resize(2, 0).unwrap();
+        assert_eq!(v.len(), 2);
+
+        // Shrink by 2
+        v.resize(0, 0).unwrap();
+        assert_eq!(v.len(), 0);
+    }
+
+    #[test]
+    fn resize_contents() {
+        let mut v: Vec<u8, 4> = Vec::new();
+
+        // New entries take supplied value when growing
+        v.resize(1, 17).unwrap();
+        assert_eq!(v[0], 17);
+
+        // Old values aren't changed when growing
+        v.resize(2, 18).unwrap();
+        assert_eq!(v[0], 17);
+        assert_eq!(v[1], 18);
+
+        // Old values aren't changed when length unchanged
+        v.resize(2, 0).unwrap();
+        assert_eq!(v[0], 17);
+        assert_eq!(v[1], 18);
+
+        // Old values aren't changed when shrinking
+        v.resize(1, 0).unwrap();
+        assert_eq!(v[0], 17);
+    }
+
+    #[test]
+    fn resize_default() {
+        let mut v: Vec<u8, 4> = Vec::new();
+
+        // resize_default is implemented using resize, so just check the
+        // correct value is being written.
+        v.resize_default(1).unwrap();
+        assert_eq!(v[0], 0);
+    }
+
+    #[test]
+    fn write() {
+        let mut v: Vec<u8, 4> = Vec::new();
+        write!(v, "{:x}", 1234).unwrap();
+        assert_eq!(&v[..], b"4d2");
+    }
+
+    #[test]
+    fn extend_from_slice() {
+        let mut v: Vec<u8, 4> = Vec::new();
+        assert_eq!(v.len(), 0);
+        v.extend_from_slice(&[1, 2]).unwrap();
+        assert_eq!(v.len(), 2);
+        assert_eq!(v.as_slice(), &[1, 2]);
+        v.extend_from_slice(&[3]).unwrap();
+        assert_eq!(v.len(), 3);
+        assert_eq!(v.as_slice(), &[1, 2, 3]);
+        assert!(v.extend_from_slice(&[4, 5]).is_err());
+        assert_eq!(v.len(), 3);
+        assert_eq!(v.as_slice(), &[1, 2, 3]);
+    }
+
+    #[test]
+    fn from_slice() {
+        // Successful construction
+        let v: Vec<u8, 4> = Vec::from_slice(&[1, 2, 3]).unwrap();
+        assert_eq!(v.len(), 3);
+        assert_eq!(v.as_slice(), &[1, 2, 3]);
+
+        // Slice too large
+        assert!(Vec::<u8, 2>::from_slice(&[1, 2, 3]).is_err());
+    }
+
+    #[test]
+    fn starts_with() {
+        let v: Vec<_, 8> = Vec::from_slice(b"ab").unwrap();
+        assert!(v.starts_with(&[]));
+        assert!(v.starts_with(b""));
+        assert!(v.starts_with(b"a"));
+        assert!(v.starts_with(b"ab"));
+        assert!(!v.starts_with(b"abc"));
+        assert!(!v.starts_with(b"ba"));
+        assert!(!v.starts_with(b"b"));
+    }
+
+    #[test]
+    fn ends_with() {
+        let v: Vec<_, 8> = Vec::from_slice(b"ab").unwrap();
+        assert!(v.ends_with(&[]));
+        assert!(v.ends_with(b""));
+        assert!(v.ends_with(b"b"));
+        assert!(v.ends_with(b"ab"));
+        assert!(!v.ends_with(b"abc"));
+        assert!(!v.ends_with(b"ba"));
+        assert!(!v.ends_with(b"a"));
+    }
+
+    #[test]
+    fn zero_capacity() {
+        let mut v: Vec<u8, 0> = Vec::new();
+        // Validate capacity
+        assert_eq!(v.capacity(), 0);
+
+        // Make sure there is no capacity
+        assert!(v.push(1).is_err());
+
+        // Validate length
+        assert_eq!(v.len(), 0);
+
+        // Validate pop
+        assert_eq!(v.pop(), None);
+
+        // Validate slice
+        assert_eq!(v.as_slice(), &[]);
+
+        // Validate empty
+        assert!(v.is_empty());
+
+        // Validate full
+        assert!(v.is_full());
+    }
+}
+
\ No newline at end of file diff --git a/docs/doc/src/stable_deref_trait/lib.rs.html b/docs/doc/src/stable_deref_trait/lib.rs.html new file mode 100644 index 0000000..b4894a3 --- /dev/null +++ b/docs/doc/src/stable_deref_trait/lib.rs.html @@ -0,0 +1,379 @@ +lib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+
// Copyright 2017 Robert Grosse
+
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+/*!
+This module defines an unsafe marker trait, StableDeref, for container types that deref to a fixed address which is valid even when the containing type is moved. For example, Box, Vec, Rc, Arc and String implement this trait. Additionally, it defines CloneStableDeref for types like Rc where clones deref to the same address.
+
+It is intended to be used by crates such as [owning_ref](https://crates.io/crates/owning_ref) and [rental](https://crates.io/crates/rental), as well as library authors who wish to make their code interoperable with such crates. For example, if you write a custom Vec type, you can implement StableDeref, and then users will be able to use your custom type together with owning_ref and rental.
+
+no_std support can be enabled by disabling default features (specifically "std"). In this case, the trait will not be implemented for the std types mentioned above, but you can still use it for your own types.
+*/
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+#[cfg(feature = "std")]
+extern crate core;
+
+#[cfg(feature = "alloc")]
+extern crate alloc;
+
+use core::ops::Deref;
+
+
+/**
+An unsafe marker trait for types that deref to a stable address, even when moved. For example, this is implemented by Box, Vec, Rc, Arc and String, among others. Even when a Box is moved, the underlying storage remains at a fixed location.
+
+More specifically, implementors must ensure that the result of calling deref() is valid for the lifetime of the object, not just the lifetime of the borrow, and that the deref is valid even if the object is moved. Also, it must be valid even after invoking arbitrary &self methods or doing anything transitively accessible from &Self. If Self also implements DerefMut, the same restrictions apply to deref_mut() and it must remain valid if anything transitively accessible from the result of deref_mut() is mutated/called. Additionally, multiple calls to deref, (and deref_mut if implemented) must return the same address. No requirements are placed on &mut self methods other than deref_mut() and drop(), if applicable.
+
+Basically, it must be valid to convert the result of deref() to a pointer, and later dereference that pointer, as long as the original object is still live, even if it has been moved or &self methods have been called on it. If DerefMut is also implemented, it must be valid to get pointers from deref() and deref_mut() and dereference them while the object is live, as long as you don't simultaneously dereference both of them.
+
+Additionally, Deref and DerefMut implementations must not panic, but users of the trait are not allowed to rely on this fact (so that this restriction can be removed later without breaking backwards compatibility, should the need arise).
+
+Here are some examples to help illustrate the requirements for implementing this trait:
+
+```
+# use std::ops::Deref;
+struct Foo(u8);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &self.0 }
+}
+```
+
+Foo cannot implement StableDeref because the int will move when Foo is moved, invalidating the result of deref().
+
+```
+# use std::ops::Deref;
+struct Foo(Box<u8>);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &*self.0 }
+}
+```
+
+Foo can safely implement StableDeref, due to the use of Box.
+
+
+```
+# use std::ops::Deref;
+# use std::ops::DerefMut;
+# use std::rc::Rc;
+#[derive(Clone)]
+struct Foo(Rc<u8>);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &*self.0 }
+}
+impl DerefMut for Foo {
+    fn deref_mut(&mut self) -> &mut Self::Target { Rc::make_mut(&mut self.0) }
+}
+```
+
+This is a simple implementation of copy-on-write: Foo's deref_mut will copy the underlying int if it is not uniquely owned, ensuring unique access at the point where deref_mut() returns. However, Foo cannot implement StableDeref because calling deref_mut(), followed by clone().deref() will result in mutable and immutable references to the same location. Note that if the DerefMut implementation were removed, Foo could safely implement StableDeref. Likewise, if the Clone implementation were removed, it would be safe to implement StableDeref, although Foo would not be very useful in that case, (without clones, the rc will always be uniquely owned).
+
+
+```
+# use std::ops::Deref;
+struct Foo;
+impl Deref for Foo {
+    type Target = str;
+    fn deref(&self) -> &Self::Target { &"Hello" }
+}
+```
+Foo can safely implement StableDeref. It doesn't own the data being derefed, but the data is gaurenteed to live long enough, due to it being 'static.
+
+```
+# use std::ops::Deref;
+# use std::cell::Cell;
+struct Foo(Cell<bool>);
+impl Deref for Foo {
+    type Target = str;
+    fn deref(&self) -> &Self::Target {
+        let b = self.0.get();
+        self.0.set(!b);
+        if b { &"Hello" } else { &"World" }
+    }
+}
+```
+Foo cannot safely implement StableDeref, even though every possible result of deref lives long enough. In order to safely implement StableAddress, multiple calls to deref must return the same result.
+
+```
+# use std::ops::Deref;
+# use std::ops::DerefMut;
+struct Foo(Box<(u8, u8)>);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &self.0.deref().0 }
+}
+impl DerefMut for Foo {
+    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0.deref_mut().1 }
+}
+```
+
+Foo cannot implement StableDeref because deref and deref_mut return different addresses.
+
+
+*/
+pub unsafe trait StableDeref: Deref {}
+
+/**
+An unsafe marker trait for types where clones deref to the same address. This has all the requirements of StableDeref, and additionally requires that after calling clone(), both the old and new value deref to the same address. For example, Rc and Arc implement CloneStableDeref, but Box and Vec do not.
+
+Note that a single type should never implement both DerefMut and CloneStableDeref. If it did, this would let you get two mutable references to the same location, by cloning and then calling deref_mut() on both values.
+*/
+pub unsafe trait CloneStableDeref: StableDeref + Clone {}
+
+/////////////////////////////////////////////////////////////////////////////
+// std types integration
+/////////////////////////////////////////////////////////////////////////////
+
+#[cfg(feature = "alloc")]
+use alloc::boxed::Box;
+#[cfg(feature = "alloc")]
+use alloc::rc::Rc;
+#[cfg(feature = "alloc")]
+use alloc::sync::Arc;
+#[cfg(feature = "alloc")]
+use alloc::vec::Vec;
+#[cfg(feature = "alloc")]
+use alloc::string::String;
+
+#[cfg(feature = "std")]
+use std::ffi::{CString, OsString};
+#[cfg(feature = "std")]
+use std::path::PathBuf;
+#[cfg(feature = "std")]
+use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
+
+use core::cell::{Ref, RefMut};
+
+
+#[cfg(feature = "alloc")]
+unsafe impl<T: ?Sized> StableDeref for Box<T> {}
+#[cfg(feature = "alloc")]
+unsafe impl<T> StableDeref for Vec<T> {}
+#[cfg(feature = "alloc")]
+unsafe impl StableDeref for String {}
+#[cfg(feature = "std")]
+unsafe impl StableDeref for CString {}
+#[cfg(feature = "std")]
+unsafe impl StableDeref for OsString {}
+#[cfg(feature = "std")]
+unsafe impl StableDeref for PathBuf {}
+
+#[cfg(feature = "alloc")]
+unsafe impl<T: ?Sized> StableDeref for Rc<T> {}
+#[cfg(feature = "alloc")]
+unsafe impl<T: ?Sized> CloneStableDeref for Rc<T> {}
+#[cfg(feature = "alloc")]
+unsafe impl<T: ?Sized> StableDeref for Arc<T> {}
+#[cfg(feature = "alloc")]
+unsafe impl<T: ?Sized> CloneStableDeref for Arc<T> {}
+
+unsafe impl<'a, T: ?Sized> StableDeref for Ref<'a, T> {}
+unsafe impl<'a, T: ?Sized> StableDeref for RefMut<'a, T> {}
+#[cfg(feature = "std")]
+unsafe impl<'a, T: ?Sized> StableDeref for MutexGuard<'a, T> {}
+#[cfg(feature = "std")]
+unsafe impl<'a, T: ?Sized> StableDeref for RwLockReadGuard<'a, T> {}
+#[cfg(feature = "std")]
+unsafe impl<'a, T: ?Sized> StableDeref for RwLockWriteGuard<'a, T> {}
+
+unsafe impl<'a, T: ?Sized> StableDeref for &'a T {}
+unsafe impl<'a, T: ?Sized> CloneStableDeref for &'a T {}
+unsafe impl<'a, T: ?Sized> StableDeref for &'a mut T {}
+
\ No newline at end of file diff --git a/docs/doc/stable_deref_trait/all.html b/docs/doc/stable_deref_trait/all.html new file mode 100644 index 0000000..5dbbb97 --- /dev/null +++ b/docs/doc/stable_deref_trait/all.html @@ -0,0 +1 @@ +List of all items in this crate

List of all items

Traits

\ No newline at end of file diff --git a/docs/doc/stable_deref_trait/index.html b/docs/doc/stable_deref_trait/index.html new file mode 100644 index 0000000..e377d92 --- /dev/null +++ b/docs/doc/stable_deref_trait/index.html @@ -0,0 +1,4 @@ +stable_deref_trait - Rust
Expand description

This module defines an unsafe marker trait, StableDeref, for container types that deref to a fixed address which is valid even when the containing type is moved. For example, Box, Vec, Rc, Arc and String implement this trait. Additionally, it defines CloneStableDeref for types like Rc where clones deref to the same address.

+

It is intended to be used by crates such as owning_ref and rental, as well as library authors who wish to make their code interoperable with such crates. For example, if you write a custom Vec type, you can implement StableDeref, and then users will be able to use your custom type together with owning_ref and rental.

+

no_std support can be enabled by disabling default features (specifically “std”). In this case, the trait will not be implemented for the std types mentioned above, but you can still use it for your own types.

+

Traits

  • An unsafe marker trait for types where clones deref to the same address. This has all the requirements of StableDeref, and additionally requires that after calling clone(), both the old and new value deref to the same address. For example, Rc and Arc implement CloneStableDeref, but Box and Vec do not.
  • An unsafe marker trait for types that deref to a stable address, even when moved. For example, this is implemented by Box, Vec, Rc, Arc and String, among others. Even when a Box is moved, the underlying storage remains at a fixed location.
\ No newline at end of file diff --git a/docs/doc/stable_deref_trait/sidebar-items.js b/docs/doc/stable_deref_trait/sidebar-items.js new file mode 100644 index 0000000..0bb40f7 --- /dev/null +++ b/docs/doc/stable_deref_trait/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"trait":["CloneStableDeref","StableDeref"]}; \ No newline at end of file diff --git a/docs/doc/stable_deref_trait/trait.CloneStableDeref.html b/docs/doc/stable_deref_trait/trait.CloneStableDeref.html new file mode 100644 index 0000000..728551f --- /dev/null +++ b/docs/doc/stable_deref_trait/trait.CloneStableDeref.html @@ -0,0 +1,3 @@ +CloneStableDeref in stable_deref_trait - Rust
pub unsafe trait CloneStableDeref: StableDeref + Clone { }
Expand description

An unsafe marker trait for types where clones deref to the same address. This has all the requirements of StableDeref, and additionally requires that after calling clone(), both the old and new value deref to the same address. For example, Rc and Arc implement CloneStableDeref, but Box and Vec do not.

+

Note that a single type should never implement both DerefMut and CloneStableDeref. If it did, this would let you get two mutable references to the same location, by cloning and then calling deref_mut() on both values.

+

Implementations on Foreign Types§

source§

impl<'a, T: ?Sized> CloneStableDeref for &'a T

Implementors§

\ No newline at end of file diff --git a/docs/doc/stable_deref_trait/trait.StableDeref.html b/docs/doc/stable_deref_trait/trait.StableDeref.html new file mode 100644 index 0000000..3aedbe8 --- /dev/null +++ b/docs/doc/stable_deref_trait/trait.StableDeref.html @@ -0,0 +1,59 @@ +StableDeref in stable_deref_trait - Rust
pub unsafe trait StableDeref: Deref { }
Expand description

An unsafe marker trait for types that deref to a stable address, even when moved. For example, this is implemented by Box, Vec, Rc, Arc and String, among others. Even when a Box is moved, the underlying storage remains at a fixed location.

+

More specifically, implementors must ensure that the result of calling deref() is valid for the lifetime of the object, not just the lifetime of the borrow, and that the deref is valid even if the object is moved. Also, it must be valid even after invoking arbitrary &self methods or doing anything transitively accessible from &Self. If Self also implements DerefMut, the same restrictions apply to deref_mut() and it must remain valid if anything transitively accessible from the result of deref_mut() is mutated/called. Additionally, multiple calls to deref, (and deref_mut if implemented) must return the same address. No requirements are placed on &mut self methods other than deref_mut() and drop(), if applicable.

+

Basically, it must be valid to convert the result of deref() to a pointer, and later dereference that pointer, as long as the original object is still live, even if it has been moved or &self methods have been called on it. If DerefMut is also implemented, it must be valid to get pointers from deref() and deref_mut() and dereference them while the object is live, as long as you don’t simultaneously dereference both of them.

+

Additionally, Deref and DerefMut implementations must not panic, but users of the trait are not allowed to rely on this fact (so that this restriction can be removed later without breaking backwards compatibility, should the need arise).

+

Here are some examples to help illustrate the requirements for implementing this trait:

+ +
struct Foo(u8);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &self.0 }
+}
+

Foo cannot implement StableDeref because the int will move when Foo is moved, invalidating the result of deref().

+ +
struct Foo(Box<u8>);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &*self.0 }
+}
+

Foo can safely implement StableDeref, due to the use of Box.

+ +
#[derive(Clone)]
+struct Foo(Rc<u8>);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &*self.0 }
+}
+impl DerefMut for Foo {
+    fn deref_mut(&mut self) -> &mut Self::Target { Rc::make_mut(&mut self.0) }
+}
+

This is a simple implementation of copy-on-write: Foo’s deref_mut will copy the underlying int if it is not uniquely owned, ensuring unique access at the point where deref_mut() returns. However, Foo cannot implement StableDeref because calling deref_mut(), followed by clone().deref() will result in mutable and immutable references to the same location. Note that if the DerefMut implementation were removed, Foo could safely implement StableDeref. Likewise, if the Clone implementation were removed, it would be safe to implement StableDeref, although Foo would not be very useful in that case, (without clones, the rc will always be uniquely owned).

+ +
struct Foo;
+impl Deref for Foo {
+    type Target = str;
+    fn deref(&self) -> &Self::Target { &"Hello" }
+}
+

Foo can safely implement StableDeref. It doesn’t own the data being derefed, but the data is gaurenteed to live long enough, due to it being ’static.

+ +
struct Foo(Cell<bool>);
+impl Deref for Foo {
+    type Target = str;
+    fn deref(&self) -> &Self::Target {
+        let b = self.0.get();
+        self.0.set(!b);
+        if b { &"Hello" } else { &"World" }
+    }
+}
+

Foo cannot safely implement StableDeref, even though every possible result of deref lives long enough. In order to safely implement StableAddress, multiple calls to deref must return the same result.

+ +
struct Foo(Box<(u8, u8)>);
+impl Deref for Foo {
+    type Target = u8;
+    fn deref(&self) -> &Self::Target { &self.0.deref().0 }
+}
+impl DerefMut for Foo {
+    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0.deref_mut().1 }
+}
+

Foo cannot implement StableDeref because deref and deref_mut return different addresses.

+

Implementations on Foreign Types§

source§

impl<'a, T: ?Sized> StableDeref for &'a T

source§

impl<'a, T: ?Sized> StableDeref for Ref<'a, T>

source§

impl<'a, T: ?Sized> StableDeref for RefMut<'a, T>

source§

impl<'a, T: ?Sized> StableDeref for &'a mut T

Implementors§

\ No newline at end of file