List of all items
Structs
Enums
Traits
Functions
- cbor_deserialize
- cbor_serialize
- cbor_serialize_bytes
- cbor_serialize_extending_bytes
- de::from_bytes
- de::take_from_bytes
diff --git a/cbor_smol/all.html b/cbor_smol/all.html index 1bd6b8f..1e84895 100644 --- a/cbor_smol/all.html +++ b/cbor_smol/all.html @@ -1 +1 @@ -
T from a byte slice. The unused portion (if any)
+T from a byte slice. The unused portion (if any)
of the byte slice is returned for further usageT from a byte slice. The unused portion (if any)
of the byte slice is returned for further usagepub struct Deserializer<'de> { /* private fields */ }A structure for deserializing a cbor-smol message.
Obtain a Deserializer from a slice of bytes
-Deserializer to figure out how to drive the visitor based
on what data type is in the input. Read moreDeserialize type is expecting an enum value with a
-particular name and possible variants.Deserialize type is expecting the name of a struct
-field or the discriminant of an enum variant.Deserialize type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moreSerde Serialization Error
Serde Deserialization Error
Serde Missing required value
-Deserialize struct type expected to receive a required
field with a particular name but that field was not present in the
input.Deserialize receives a type different from what it was
@@ -53,9 +55,7 @@ is wrong for some other reason. Read moreDeserialize enum type received a variant with an
unrecognized name.Deserialize struct type received a field with an
unrecognized name.Deserialize struct type received more than one of the
-same field.pub type Result<T> = Result<T, Error>;This is the Result type used by cbor-smol.
-enum Result<T> {
+Result in cbor_smol::error - Rust
\ No newline at end of file
diff --git a/cbor_smol/fn.cbor_deserialize.html b/cbor_smol/fn.cbor_deserialize.html
index 1cd35ca..be9fe59 100644
--- a/cbor_smol/fn.cbor_deserialize.html
+++ b/cbor_smol/fn.cbor_deserialize.html
@@ -1,3 +1,3 @@
-cbor_deserialize in cbor_smol - Rust Function cbor_smol::cbor_deserialize
source · pub fn cbor_deserialize<'de, T: Deserialize<'de>>(
+cbor_deserialize in cbor_smol - Rust Function cbor_smol::cbor_deserialize
source · pub fn cbor_deserialize<'de, T: Deserialize<'de>>(
buffer: &'de [u8],
) -> Result<T>
\ No newline at end of file
diff --git a/cbor_smol/fn.cbor_serialize.html b/cbor_smol/fn.cbor_serialize.html
index 4958cd4..c9a4d70 100644
--- a/cbor_smol/fn.cbor_serialize.html
+++ b/cbor_smol/fn.cbor_serialize.html
@@ -1,4 +1,4 @@
-cbor_serialize in cbor_smol - Rust Function cbor_smol::cbor_serialize
source · pub fn cbor_serialize<'a, T: ?Sized + Serialize>(
+cbor_serialize in cbor_smol - Rust
\ No newline at end of file
diff --git a/cbor_smol/fn.cbor_serialize_bytes.html b/cbor_smol/fn.cbor_serialize_bytes.html
index 05fd052..5156c89 100644
--- a/cbor_smol/fn.cbor_serialize_bytes.html
+++ b/cbor_smol/fn.cbor_serialize_bytes.html
@@ -1,4 +1,4 @@
-cbor_serialize_bytes in cbor_smol - Rust Function cbor_smol::cbor_serialize_bytes
source · pub fn cbor_serialize_bytes<T: ?Sized + Serialize, const N: usize>(
+cbor_serialize_bytes in cbor_smol - Rust Function cbor_smol::cbor_serialize_bytes
source · pub fn cbor_serialize_bytes<T: ?Sized + Serialize, const N: usize>(
object: &T,
-) -> Result<Bytes<N>>
Expand description
Serialize object into newly allocated Bytes.
+) -> Result<Bytes<N>>Expand description
Serialize object into newly allocated Bytes.
\ No newline at end of file
diff --git a/cbor_smol/fn.cbor_serialize_extending_bytes.html b/cbor_smol/fn.cbor_serialize_extending_bytes.html
index c126759..81f232a 100644
--- a/cbor_smol/fn.cbor_serialize_extending_bytes.html
+++ b/cbor_smol/fn.cbor_serialize_extending_bytes.html
@@ -1,5 +1,5 @@
-cbor_serialize_extending_bytes in cbor_smol - Rust Function cbor_smol::cbor_serialize_extending_bytes
source · pub fn cbor_serialize_extending_bytes<T: ?Sized + Serialize, const N: usize>(
+cbor_serialize_extending_bytes in cbor_smol - Rust Function cbor_smol::cbor_serialize_extending_bytes
source · pub fn cbor_serialize_extending_bytes<T: ?Sized + Serialize, const N: usize>(
object: &T,
- bytes: &mut Bytes<N>,
-) -> Result<usize>
Expand description
Append serialization of object to existing bytes, returning length of serialized object.
+ bytes: &mut Bytes<N>,
+) -> Result<usize>👎Deprecated: use cbor_serialize_to insteadExpand description
Append serialization of object to existing bytes, returning length of serialized object.
\ No newline at end of file
diff --git a/cbor_smol/fn.cbor_serialize_to.html b/cbor_smol/fn.cbor_serialize_to.html
new file mode 100644
index 0000000..f46707e
--- /dev/null
+++ b/cbor_smol/fn.cbor_serialize_to.html
@@ -0,0 +1,6 @@
+cbor_serialize_to in cbor_smol - Rust
\ No newline at end of file
diff --git a/cbor_smol/index.html b/cbor_smol/index.html
index cde90cf..80ac7b2 100644
--- a/cbor_smol/index.html
+++ b/cbor_smol/index.html
@@ -1 +1 @@
-cbor_smol - Rust
\ No newline at end of file
+cbor_smol - Rust Re-exports§
Modules§
Functions§
- Serialize object into newly allocated Bytes.
- cbor_serialize_extending_bytesDeprecatedAppend serialization of object to existing bytes, returning length of serialized object.
- Serialize an object to a
Writer
\ No newline at end of file
diff --git a/cbor_smol/ser/index.html b/cbor_smol/ser/index.html
index 3483d8b..1139bd0 100644
--- a/cbor_smol/ser/index.html
+++ b/cbor_smol/ser/index.html
@@ -1 +1 @@
-cbor_smol::ser - Rust
\ No newline at end of file
+cbor_smol::ser - Rust
\ No newline at end of file
diff --git a/cbor_smol/ser/sidebar-items.js b/cbor_smol/ser/sidebar-items.js
index fa57b5d..8e48ec0 100644
--- a/cbor_smol/ser/sidebar-items.js
+++ b/cbor_smol/ser/sidebar-items.js
@@ -1 +1 @@
-window.SIDEBAR_ITEMS = {"struct":["Serializer","SliceWriter"],"trait":["Writer"]};
\ No newline at end of file
+window.SIDEBAR_ITEMS = {"struct":["Serializer"],"trait":["Writer"]};
\ No newline at end of file
diff --git a/cbor_smol/ser/struct.Serializer.html b/cbor_smol/ser/struct.Serializer.html
index f7bf36c..6a6dbfa 100644
--- a/cbor_smol/ser/struct.Serializer.html
+++ b/cbor_smol/ser/struct.Serializer.html
@@ -1,87 +1,85 @@
-Serializer in cbor_smol::ser - Rust Struct cbor_smol::ser::Serializer
source · pub struct Serializer<W> {
- pub writer: W,
-}
Fields§
§writer: WImplementations§
source§impl<W: Writer> Serializer<W>
sourcepub fn new(writer: W) -> Self
sourcepub fn into_inner(self) -> W
Unwrap the Writer from the Serializer.
-Trait Implementations§
source§impl<'a, W> SerializeStruct for &'a mut Serializer<W>where
- W: Writer,
source§impl<'a, W> SerializeStructVariant for &'a mut Serializer<W>where
- W: Writer,
source§impl<'a, W> SerializeTuple for &'a mut Serializer<W>where
- W: Writer,
source§impl<'a, W> SerializeTupleStruct for &'a mut Serializer<W>where
- W: Writer,
source§impl<'a, W> SerializeTupleVariant for &'a mut Serializer<W>where
- W: Writer,
source§impl<'a, W> Serializer for &'a mut Serializer<W>where
- W: Writer,
§type Ok = ()
The output type produced by this Serializer during successful
+Serializer in cbor_smol::ser - Rust Struct cbor_smol::ser::Serializer
source · pub struct Serializer<W> { /* private fields */ }
Implementations§
Trait Implementations§
source§impl<'a, W> SerializeStruct for &'a mut Serializer<W>where
+ W: Writer,
source§impl<'a, W> SerializeStructVariant for &'a mut Serializer<W>where
+ W: Writer,
source§impl<'a, W> SerializeTuple for &'a mut Serializer<W>where
+ W: Writer,
source§impl<'a, W> SerializeTupleStruct for &'a mut Serializer<W>where
+ W: Writer,
source§impl<'a, W> SerializeTupleVariant for &'a mut Serializer<W>where
+ W: Writer,
source§impl<'a, W> Serializer for &'a mut Serializer<W>where
+ W: Writer,
§type Ok = ()
The output type produced by this Serializer during successful
serialization. Most serializers that produce text or binary output
should set Ok = () and serialize into an io::Write or buffer
contained within the Serializer instance. Serializers that build
in-memory data structures may be simplified by using Ok to propagate
-the data structure around.§type SerializeSeq = CollectionSerializer<'a, W>
Type returned from serialize_seq for serializing the content of the
+the data structure around.§type SerializeSeq = CollectionSerializer<'a, W>
Type returned from serialize_seq for serializing the content of the
sequence.§type SerializeTuple = &'a mut Serializer<W>
Type returned from serialize_tuple for serializing the content of
the tuple.§type SerializeTupleStruct = &'a mut Serializer<W>
Type returned from serialize_tuple_struct for serializing the
content of the tuple struct.§type SerializeTupleVariant = &'a mut Serializer<W>
Type returned from serialize_tuple_variant for serializing the
content of the tuple variant.§type SerializeMap = CollectionSerializer<'a, W>
Type returned from serialize_map for serializing the content of the
map.§type SerializeStruct = &'a mut Serializer<W>
Type returned from serialize_struct for serializing the content of
the struct.§type SerializeStructVariant = &'a mut Serializer<W>
Type returned from serialize_struct_variant for serializing the
-content of the struct variant.source§fn serialize_bytes(self, value: &[u8]) -> Result<()>
Serialize a chunk of raw byte data. Read moresource§fn serialize_unit_variant(
+content of the struct variant.
source§fn serialize_bytes(self, value: &[u8]) -> Result<()>
Serialize a chunk of raw byte data. Read moresource§fn serialize_unit_variant(
self,
_name: &'static str,
variant_index: u32,
_variant: &'static str,
-) -> Result<()>
source§fn serialize_newtype_struct<T>(
+) -> Result<()>
source§fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<()>
Serialize a newtype struct like struct Millimeters(u8). Read moresource§fn serialize_newtype_variant<T>(
+ T: ?Sized + Serialize,
Serialize a newtype struct like struct Millimeters(u8). Read moresource§fn serialize_newtype_variant<T>(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<()>
source§fn serialize_seq(
+ T: ?Sized + Serialize,
source§fn serialize_seq(
self,
len: Option<usize>,
) -> Result<CollectionSerializer<'a, W>>
Begin to serialize a variably sized sequence. This call must be
followed by zero or more calls to serialize_element, then a call to
-end. Read moresource§fn serialize_tuple(self, len: usize) -> Result<&'a mut Serializer<W>>
Begin to serialize a statically sized sequence whose length will be
+end. Read moresource§fn serialize_tuple(self, len: usize) -> Result<&'a mut Serializer<W>>
Begin to serialize a statically sized sequence whose length will be
known at deserialization time without looking at the serialized data.
This call must be followed by zero or more calls to serialize_element,
-then a call to end. Read moresource§fn serialize_tuple_struct(
+then a call to end. Read more
source§fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<&'a mut Serializer<W>>
Begin to serialize a tuple struct like struct Rgb(u8, u8, u8). This
call must be followed by zero or more calls to serialize_field, then a
-call to end. Read moresource§fn serialize_tuple_variant(
+call to end. Read more
source§fn serialize_tuple_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<&'a mut Serializer<W>>
Begin to serialize a tuple variant like E::T in enum E { T(u8, u8) }. This call must be followed by zero or more calls to
-serialize_field, then a call to end. Read moresource§fn serialize_map(
+serialize_field, then a call to end. Read more
source§fn serialize_map(
self,
len: Option<usize>,
) -> Result<CollectionSerializer<'a, W>>
Begin to serialize a map. This call must be followed by zero or more
-calls to serialize_key and serialize_value, then a call to end. Read moresource§fn serialize_struct(
+calls to serialize_key and serialize_value, then a call to end. Read more
source§fn serialize_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct>
Begin to serialize a struct like struct Rgb { r: u8, g: u8, b: u8 }.
This call must be followed by zero or more calls to serialize_field,
-then a call to end. Read moresource§fn serialize_struct_variant(
+then a call to end. Read more
source§fn serialize_struct_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeStruct>
Begin to serialize a struct variant like E::S in enum E { S { r: u8, g: u8, b: u8 } }. This call must be followed by zero or more calls to
-serialize_field, then a call to end. Read moresource§fn collect_str<T>(self, _value: &T) -> Result<Self::Ok>
Serialize a string produced by an implementation of Display. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Serialize implementations should serialize in
+serialize_field, then a call to end. Read moresource§fn collect_str<T>(self, _value: &T) -> Result<Self::Ok>
Serialize a string produced by an implementation of Display. Read moresource§fn is_human_readable(&self) -> bool
Determine whether Serialize implementations should serialize in
human-readable form. Read moresource§fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error>
Serialize an i128 value. Read moresource§fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error>
Serialize a u128 value. Read moresource§fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
Collect an iterator as a sequence. Read moresource§fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>where
diff --git a/cbor_smol/ser/struct.SliceWriter.html b/cbor_smol/ser/struct.SliceWriter.html
deleted file mode 100644
index b2ce67d..0000000
--- a/cbor_smol/ser/struct.SliceWriter.html
+++ /dev/null
@@ -1,14 +0,0 @@
-SliceWriter in cbor_smol::ser - Rust Struct cbor_smol::ser::SliceWriter
source · pub struct SliceWriter<'a> { /* private fields */ }
Implementations§
source§impl<'a> SliceWriter<'a>
sourcepub fn new(slice: &'a mut [u8]) -> SliceWriter<'a>
Wraps a mutable slice so it can be used as a Writer.
-sourcepub fn bytes_written(&self) -> usize
Returns the number of bytes written to the underlying slice.
-sourcepub fn into_inner(self) -> &'a mut [u8]
Returns the underlying slice.
-Trait Implementations§
source§impl<'a> Debug for SliceWriter<'a>
Auto Trait Implementations§
§impl<'a> Freeze for SliceWriter<'a>
§impl<'a> RefUnwindSafe for SliceWriter<'a>
§impl<'a> Send for SliceWriter<'a>
§impl<'a> Sync for SliceWriter<'a>
§impl<'a> Unpin for SliceWriter<'a>
§impl<'a> !UnwindSafe for SliceWriter<'a>
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
- T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
\ No newline at end of file
diff --git a/cbor_smol/ser/trait.Writer.html b/cbor_smol/ser/trait.Writer.html
index 15031fb..0c5d68c 100644
--- a/cbor_smol/ser/trait.Writer.html
+++ b/cbor_smol/ser/trait.Writer.html
@@ -1,8 +1,8 @@
-Writer in cbor_smol::ser - Rust pub trait Writer {
+Writer in cbor_smol::ser - Rust
\ No newline at end of file
+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
+}
Required Associated Types§
Required Methods§
Implementations on Foreign Types§
Implementors§
\ No newline at end of file
diff --git a/cbor_smol/sidebar-items.js b/cbor_smol/sidebar-items.js
index de50002..e51cd0f 100644
--- a/cbor_smol/sidebar-items.js
+++ b/cbor_smol/sidebar-items.js
@@ -1 +1 @@
-window.SIDEBAR_ITEMS = {"fn":["cbor_deserialize","cbor_serialize","cbor_serialize_bytes","cbor_serialize_extending_bytes"],"mod":["de","error","ser"],"struct":["Bytes"]};
\ No newline at end of file
+window.SIDEBAR_ITEMS = {"fn":["cbor_deserialize","cbor_serialize","cbor_serialize_bytes","cbor_serialize_extending_bytes","cbor_serialize_to"],"mod":["de","error","ser"]};
\ No newline at end of file
diff --git a/cbor_smol/struct.Bytes.html b/cbor_smol/struct.Bytes.html
deleted file mode 100644
index 4fdaeb0..0000000
--- a/cbor_smol/struct.Bytes.html
+++ /dev/null
@@ -1,2494 +0,0 @@
-Bytes in cbor_smol - Rust pub struct Bytes<const N: usize> { /* private fields */ }
Implementations§
§impl<const N: usize> Bytes<N>
pub fn into_inner(self) -> Vec<u8, N>
Unwraps the Vec<u8, N>, same as into_vec.
-pub fn as_mut_slice(&mut self) -> &mut [u8]
Returns a mutable slice view.
-pub fn try_convert_into<const M: usize>(&self) -> Result<Bytes<M>, ()>
Low-noise conversion between lengths.
-We can’t implement TryInto since it would clash with blanket implementations.
-pub fn from_slice(slice: &[u8]) -> Result<Bytes<N>, ()>
pub fn try_from<E>(
- f: impl FnOnce(&mut [u8]) -> Result<usize, E>,
-) -> Result<Bytes<N>, E>
Some APIs offer an interface of the form f(&mut [u8]) -> Result<usize, E>,
-with the contract that the Ok-value signals how many bytes were written.
-This constructor allows wrapping such interfaces in a more ergonomic way,
-returning a Bytes willed using f.
-It seems it’s not possible to do this as an actual TryFrom implementation.
-pub fn insert_slice_at(&mut self, slice: &[u8], at: usize) -> Result<(), ()>
pub fn insert(&mut self, index: usize, item: u8) -> Result<(), u8>
pub fn remove(&mut self, index: usize) -> Result<u8, ()>
pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>
pub fn resize_to_capacity(&mut self)
Methods from Deref<Target = Vec<u8, N>>§
pub fn as_mut_ptr(&mut self) -> *mut T
Returns a raw pointer to the vector’s buffer, which may be mutated through.
-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]);
-pub fn clear(&mut self)
Clears the vector, removing all values.
-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.
-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]);
-pub fn pop(&mut self) -> Option<T>
Removes the last element from a vector and returns it, or None if it’s empty
-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
-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.
-pub unsafe fn push_unchecked(&mut self, item: T)
pub fn truncate(&mut self, len: usize)
Shortens the vector, keeping the first len elements and dropping the rest.
-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.
-pub fn resize_default(&mut self, new_len: usize) -> Result<(), ()>
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.
-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.
-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"]);
-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"]);
-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);
-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);
-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]);
-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]);
-pub fn retain<F>(&mut self, f: F)
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_mut<F>(&mut self, f: F)
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.0.0 · sourcepub 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 · sourcepub 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());
-
-let b: &[i32] = &[];
-assert!(b.is_empty());
-1.0.0 · sourcepub 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 · sourcepub 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]);
-
-let y: &mut [i32] = &mut [];
-assert_eq!(None, y.first_mut());
-1.5.0 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub fn last_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the last item in the slice, or None if it is empty.
-§Examples
-let x = &mut [0, 1, 2];
-
-if let Some(last) = x.last_mut() {
- *last = 10;
-}
-assert_eq!(x, &[0, 1, 10]);
-
-let y: &mut [i32] = &mut [];
-assert_eq!(None, y.last_mut());
-1.77.0 · sourcepub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
Return an array reference to the first N items in the slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-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>());
-1.77.0 · sourcepub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Return a mutable array reference to the first N items in the slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-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]);
-
-assert_eq!(None, x.first_chunk_mut::<4>());
-1.77.0 · sourcepub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
Return an array reference to the first N items in the slice and the remaining slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-let x = &[0, 1, 2];
-
-if let Some((first, elements)) = x.split_first_chunk::<2>() {
- assert_eq!(first, &[0, 1]);
- assert_eq!(elements, &[2]);
-}
-
-assert_eq!(None, x.split_first_chunk::<4>());
-1.77.0 · sourcepub fn split_first_chunk_mut<const N: usize>(
- &mut self,
-) -> Option<(&mut [T; N], &mut [T])>
Return a mutable array reference to the first N items in the slice and the remaining
-slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-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]);
-
-assert_eq!(None, x.split_first_chunk_mut::<4>());
-1.77.0 · sourcepub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>
Return an array reference to the last N items in the slice and the remaining slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-let x = &[0, 1, 2];
-
-if let Some((elements, last)) = x.split_last_chunk::<2>() {
- assert_eq!(elements, &[0]);
- assert_eq!(last, &[1, 2]);
-}
-
-assert_eq!(None, x.split_last_chunk::<4>());
-1.77.0 · sourcepub fn split_last_chunk_mut<const N: usize>(
- &mut self,
-) -> Option<(&mut [T], &mut [T; N])>
Return a mutable array reference to the last N items in the slice and the remaining
-slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-let x = &mut [0, 1, 2];
-
-if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {
- last[0] = 3;
- last[1] = 4;
- elements[0] = 5;
-}
-assert_eq!(x, &[5, 3, 4]);
-
-assert_eq!(None, x.split_last_chunk_mut::<4>());
-1.77.0 · sourcepub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
Return an array reference to the last N items in the slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-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.77.0 · sourcepub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Return a mutable array reference to the last N items in the slice.
-If the slice is not at least N in length, this will return None.
-§Examples
-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]);
-
-assert_eq!(None, x.last_chunk_mut::<4>());
-1.0.0 · sourcepub 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 · sourcepub fn get_mut<I>(
- &mut self,
- index: I,
-) -> Option<&mut <I as SliceIndex<[T]>>::Output>where
- I: SliceIndex<[T]>,
1.0.0 · sourcepub 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.
-You can think of this like .get(index).unwrap_unchecked(). It’s UB
-to call .get_unchecked(len), even if you immediately convert to a
-pointer. And it’s UB to call .get_unchecked(..len + 1),
-.get_unchecked(..=len), or similar.
-§Examples
-let x = &[1, 2, 4];
-
-unsafe {
- assert_eq!(x.get_unchecked(1), &2);
-}
-1.0.0 · sourcepub 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.
-You can think of this like .get_mut(index).unwrap_unchecked(). It’s
-UB to call .get_unchecked_mut(len), even if you immediately convert
-to a pointer. And it’s UB to call .get_unchecked_mut(..len + 1),
-.get_unchecked_mut(..=len), or similar.
-§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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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"]);
-sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 = ['l', 'o', 'r', 'e', 'm'];
-let mut iter = slice.windows(3);
-assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
-assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
-assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
-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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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]);
-sourcepub 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
-sourcepub 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']]);
-sourcepub 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']]);
-sourcepub 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']);
-sourcepub 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
-sourcepub 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]);
-sourcepub 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]);
-sourcepub 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]);
-sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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]);
-1.77.0 · sourcepub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
Returns an iterator over the slice producing non-overlapping runs
-of elements using the predicate to separate them.
-The predicate is called for every pair of consecutive elements,
-meaning that it is called on slice[0] and slice[1],
-followed by slice[1] and slice[2], and so on.
-§Examples
-let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
-
-let mut iter = slice.chunk_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:
-
-let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
-
-let mut iter = slice.chunk_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.77.0 · sourcepub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
Returns an iterator over the slice producing non-overlapping mutable
-runs of elements using the predicate to separate them.
-The predicate is called for every pair of consecutive elements,
-meaning that it is called on slice[0] and slice[1],
-followed by slice[1] and slice[2], and so on.
-§Examples
-let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
-
-let mut iter = slice.chunk_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:
-
-let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
-
-let mut iter = slice.chunk_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 · sourcepub 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. For a non-panicking alternative see
-split_at_checked.
-§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 · sourcepub 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. For a non-panicking alternative see
-split_at_mut_checked.
-§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]);
-1.79.0 · sourcepub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
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
-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, []);
-}
-1.79.0 · sourcepub unsafe fn split_at_mut_unchecked(
- &mut self,
- mid: usize,
-) -> (&mut [T], &mut [T])
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
-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]);
-1.80.0 · sourcepub fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
Divides one slice into two at an index, returning None if the slice is
-too short.
-If mid ≤ len returns a pair of slices where 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).
-Otherwise, if mid > len, returns None.
-§Examples
-let v = [1, -2, 3, -4, 5, -6];
-
-{
- let (left, right) = v.split_at_checked(0).unwrap();
- assert_eq!(left, []);
- assert_eq!(right, [1, -2, 3, -4, 5, -6]);
-}
-
-{
- let (left, right) = v.split_at_checked(2).unwrap();
- assert_eq!(left, [1, -2]);
- assert_eq!(right, [3, -4, 5, -6]);
-}
-
-{
- let (left, right) = v.split_at_checked(6).unwrap();
- assert_eq!(left, [1, -2, 3, -4, 5, -6]);
- assert_eq!(right, []);
-}
-
-assert_eq!(None, v.split_at_checked(7));
-1.80.0 · sourcepub fn split_at_mut_checked(
- &mut self,
- mid: usize,
-) -> Option<(&mut [T], &mut [T])>
Divides one mutable slice into two at an index, returning None if the
-slice is too short.
-If mid ≤ len returns a pair of slices where 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).
-Otherwise, if mid > len, returns None.
-§Examples
-let mut v = [1, 0, 3, 0, 5, 6];
-
-if let Some((left, right)) = v.split_at_mut_checked(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]);
-
-assert_eq!(None, v.split_at_mut_checked(7));
-1.0.0 · sourcepub fn split<F>(&self, pred: F) -> Split<'_, T, F>
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 · sourcepub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
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 · sourcepub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
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 · sourcepub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
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 · sourcepub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
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 · sourcepub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
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 · sourcepub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
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 · sourcepub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
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 · sourcepub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
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 · sourcepub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
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]);
-sourcepub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
🔬This is a nightly-only experimental API. (slice_split_once)
Splits the slice on the first element that matches the specified
-predicate.
-If any matching elements are present in the slice, returns the prefix
-before the match and suffix after. The matching element itself is not
-included. If no elements match, returns None.
-§Examples
-#![feature(slice_split_once)]
-let s = [1, 2, 3, 2, 4];
-assert_eq!(s.split_once(|&x| x == 2), Some((
- &[1][..],
- &[3, 2, 4][..]
-)));
-assert_eq!(s.split_once(|&x| x == 0), None);
-sourcepub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
🔬This is a nightly-only experimental API. (slice_split_once)
Splits the slice on the last element that matches the specified
-predicate.
-If any matching elements are present in the slice, returns the prefix
-before the match and suffix after. The matching element itself is not
-included. If no elements match, returns None.
-§Examples
-#![feature(slice_split_once)]
-let s = [1, 2, 3, 2, 4];
-assert_eq!(s.rsplit_once(|&x| x == 2), Some((
- &[1, 2, 3][..],
- &[4][..]
-)));
-assert_eq!(s.rsplit_once(|&x| x == 0), None);
-1.0.0 · sourcepub fn contains(&self, x: &T) -> boolwhere
- T: PartialEq,
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 · sourcepub fn starts_with(&self, needle: &[T]) -> boolwhere
- T: PartialEq,
Returns true if needle is a prefix of the slice or equal to the slice.
-§Examples
-let v = [10, 40, 30];
-assert!(v.starts_with(&[10]));
-assert!(v.starts_with(&[10, 40]));
-assert!(v.starts_with(&v));
-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 · sourcepub fn ends_with(&self, needle: &[T]) -> boolwhere
- T: PartialEq,
Returns true if needle is a suffix of the slice or equal to the slice.
-§Examples
-let v = [10, 40, 30];
-assert!(v.ends_with(&[30]));
-assert!(v.ends_with(&[40, 30]));
-assert!(v.ends_with(&v));
-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 · sourcepub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[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 prefix is equal to the
-original slice, returns an empty 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(&[10, 40, 30]), Some(&[][..]));
-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 · sourcepub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[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 suffix is equal to the
-original slice, returns an empty 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(&[10, 40, 30]), Some(&[][..]));
-assert_eq!(v.strip_suffix(&[50]), None);
-assert_eq!(v.strip_suffix(&[50, 30]), None);
-1.0.0 · sourcepub fn binary_search(&self, x: &T) -> Result<usize, usize>where
- T: Ord,
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);
-// If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
-// `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
-// to shift less elements.
-s.insert(idx, num);
-assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
-1.0.0 · sourcepub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
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 · sourcepub fn binary_search_by_key<'a, B, F>(
- &'a self,
- b: &B,
- f: F,
-) -> Result<usize, usize>
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 · sourcepub fn sort_unstable(&mut self)where
- T: Ord,
Sorts the slice without preserving the initial 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.
-If the implementation of Ord for T does not implement a total order the resulting
-order of elements in the slice is unspecified. All original elements will remain in the
-slice and any possible modifications via interior mutability are observed in the input. Same
-is true if the implementation of Ord for T panics.
-Sorting types that only implement PartialOrd such as f32 and f64 require
-additional precautions. For example, f32::NAN != f32::NAN, which doesn’t fulfill the
-reflexivity requirement of Ord. By using an alternative comparison function with
-slice::sort_unstable_by such as f32::total_cmp or f64::total_cmp that defines a
-total order users can sort slices containing floating-point values. Alternatively, if all
-values in the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp
-forms a total order, it’s possible to sort the slice with sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()).
-§Current implementation
-The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which
-combines the fast average case of quicksort with the fast worst case of heapsort, achieving
-linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
-expected time to sort the data is O(n * log(k)).
-It is typically faster than stable sorting, except in a few special cases, e.g., when the
-slice is partially sorted.
-§Panics
-May panic if the implementation of Ord for T does not implement a total order.
-§Examples
-let mut v = [4, -5, 1, -3, 2];
-
-v.sort_unstable();
-assert_eq!(v, [-5, -3, 1, 2, 4]);
-1.20.0 · sourcepub fn sort_unstable_by<F>(&mut self, compare: F)
Sorts the slice with a comparison function, without preserving the initial 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.
-If the comparison function compare does not implement a total order the resulting order
-of elements in the slice is unspecified. All original elements will remain in the slice and
-any possible modifications via interior mutability are observed in the input. Same is true
-if compare panics.
-For example |a, b| (a - b).cmp(a) is a comparison function that is neither transitive nor
-reflexive nor total, a < b < c < a with a = 1, b = 2, c = 3. For more information and
-examples see the Ord documentation.
-§Current implementation
-The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which
-combines the fast average case of quicksort with the fast worst case of heapsort, achieving
-linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
-expected time to sort the data is O(n * log(k)).
-It is typically faster than stable sorting, except in a few special cases, e.g., when the
-slice is partially sorted.
-§Panics
-May panic if compare does not implement a total order.
-§Examples
-let mut v = [4, -5, 1, -3, 2];
-v.sort_unstable_by(|a, b| a.cmp(b));
-assert_eq!(v, [-5, -3, 1, 2, 4]);
-
-// reverse sorting
-v.sort_unstable_by(|a, b| b.cmp(a));
-assert_eq!(v, [4, 2, 1, -3, -5]);
-1.20.0 · sourcepub fn sort_unstable_by_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, without preserving the initial 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.
-If the implementation of Ord for K does not implement a total order the resulting
-order of elements in the slice is unspecified. All original elements will remain in the
-slice and any possible modifications via interior mutability are observed in the input. Same
-is true if the implementation of Ord for K panics.
-§Current implementation
-The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which
-combines the fast average case of quicksort with the fast worst case of heapsort, achieving
-linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
-expected time to sort the data is O(n * log(k)).
-It is typically faster than stable sorting, except in a few special cases, e.g., when the
-slice is partially sorted.
-§Panics
-May panic if the implementation of Ord for K does not implement a total order.
-§Examples
-let mut v = [4i32, -5, 1, -3, 2];
-
-v.sort_unstable_by_key(|k| k.abs());
-assert_eq!(v, [1, 2, -3, 4, -5]);
-1.49.0 · sourcepub 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 after the reordering 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 ipnsort by Lukas Bergdoll
-and Orson Peters, 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.
-May panic if the implementation of Ord for T does not implement a total order.
-§Examples
-let mut v = [-5i32, 4, 2, -3, 1];
-
-// Find the items less than or equal to the median, the median, and greater than or equal to
-// the median.
-let (lesser, median, greater) = v.select_nth_unstable(2);
-
-assert!(lesser == [-3, -5] || lesser == [-5, -3]);
-assert_eq!(median, &mut 1);
-assert!(greater == [4, 2] || greater == [2, 4]);
-
-// 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 · sourcepub fn select_nth_unstable_by<F>(
- &mut self,
- index: usize,
- compare: F,
-) -> (&mut [T], &mut T, &mut [T])
Reorder the slice with a comparator function such that the element at index after the
-reordering 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 ipnsort by Lukas Bergdoll
-and Orson Peters, 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.
-May panic if compare does not implement a total order.
-§Examples
-let mut v = [-5i32, 4, 2, -3, 1];
-
-// Find the items less than or equal to the median, the median, and greater than or equal to
-// the median as if the slice were sorted in descending order.
-let (lesser, median, greater) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
-
-assert!(lesser == [4, 2] || lesser == [2, 4]);
-assert_eq!(median, &mut 1);
-assert!(greater == [-3, -5] || greater == [-5, -3]);
-
-// 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 · sourcepub fn select_nth_unstable_by_key<K, F>(
- &mut self,
- index: usize,
- f: F,
-) -> (&mut [T], &mut T, &mut [T])
Reorder the slice with a key extraction function such that the element at index after the
-reordering 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 ipnsort by Lukas Bergdoll
-and Orson Peters, 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.
-May panic if K: Ord does not implement a total order.
-§Examples
-let mut v = [-5i32, 4, 1, -3, 2];
-
-// Find the items less than or equal to the median, the median, and greater than or equal to
-// the median as if the slice were sorted according to absolute value.
-let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
-
-assert!(lesser == [1, 2] || lesser == [2, 1]);
-assert_eq!(median, &mut -3);
-assert!(greater == [4, -5] || greater == [-5, 4]);
-
-// 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]);
-sourcepub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where
- T: PartialEq,
🔬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]);
-sourcepub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
🔬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"]);
-sourcepub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
🔬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 · sourcepub 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 · sourcepub 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']);
-Rotating 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub fn copy_within<R>(&mut self, src: R, dest: usize)
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 · sourcepub 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 · sourcepub 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. The middle part will be as big as possible under
-the given alignment constraint and element size.
-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 · sourcepub 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. The middle part will be as big as possible under
-the given alignment constraint and element size.
-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);
-}
-sourcepub 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 inherits the same
-guarantees as that method.
-§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::prelude::*;
-
-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;
- 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);
-sourcepub 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 inherits the same
-guarantees as that method.
-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.
-sourcepub fn is_sorted(&self) -> boolwhere
- T: PartialOrd,
🔬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());
-sourcepub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
🔬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 whether two elements are to be considered in sorted order.
-§Examples
-#![feature(is_sorted)]
-
-assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
-assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
-
-assert!([0].is_sorted_by(|a, b| true));
-assert!([0].is_sorted_by(|a, b| false));
-
-let empty: [i32; 0] = [];
-assert!(empty.is_sorted_by(|a, b| false));
-assert!(empty.is_sorted_by(|a, b| true));
-sourcepub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
🔬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 · sourcepub fn partition_point<P>(&self, pred: P) -> usize
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]);
-sourcepub fn take<'a, R>(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));
-sourcepub fn take_mut<'a, R>(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));
-sourcepub 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');
-sourcepub 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');
-sourcepub 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');
-sourcepub 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');
-sourcepub 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]);
-sourcepub 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]);
-1.79.0 · sourcepub fn utf8_chunks(&self) -> Utf8Chunks<'_>
Creates an iterator over the contiguous valid UTF-8 ranges of this
-slice, and the non-UTF-8 fragments in between.
-§Examples
-This function formats arbitrary but mostly-UTF-8 bytes into Rust source
-code in the form of a C-string literal (c"...").
-
-use std::fmt::Write as _;
-
-pub fn cstr_literal(bytes: &[u8]) -> String {
- let mut repr = String::new();
- repr.push_str("c\"");
- for chunk in bytes.utf8_chunks() {
- for ch in chunk.valid().chars() {
- // Escapes \0, \t, \r, \n, \\, \', \", and uses \u{...} for non-printable characters.
- write!(repr, "{}", ch.escape_debug()).unwrap();
- }
- for byte in chunk.invalid() {
- write!(repr, "\\x{:02X}", byte).unwrap();
- }
- }
- repr.push('"');
- repr
-}
-
-fn main() {
- let lit = cstr_literal(b"\xferris the \xf0\x9f\xa6\x80\x07");
- let expected = stringify!(c"\xFErris the 🦀\u{7}");
- assert_eq!(lit, expected);
-}
-1.23.0 · sourcepub fn is_ascii(&self) -> bool
Checks if all bytes in this slice are within the ASCII range.
-sourcepub 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.
-sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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 · sourcepub 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");
-1.80.0 · sourcepub fn trim_ascii_start(&self) -> &[u8]
Returns a byte slice with leading ASCII whitespace bytes removed.
-‘Whitespace’ refers to the definition used by
-u8::is_ascii_whitespace.
-§Examples
-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"");
-1.80.0 · sourcepub fn trim_ascii_end(&self) -> &[u8]
Returns a byte slice with trailing ASCII whitespace bytes removed.
-‘Whitespace’ refers to the definition used by
-u8::is_ascii_whitespace.
-§Examples
-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"");
-1.80.0 · sourcepub fn trim_ascii(&self) -> &[u8]
Returns a byte slice with leading and trailing ASCII whitespace bytes
-removed.
-‘Whitespace’ refers to the definition used by
-u8::is_ascii_whitespace.
-§Examples
-assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
-assert_eq!(b" ".trim_ascii(), b"");
-assert_eq!(b"".trim_ascii(), b"");
-1.80.0 · sourcepub fn as_flattened(&self) -> &[T]
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
-assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);
-
-assert_eq!(
- [[1, 2, 3], [4, 5, 6]].as_flattened(),
- [[1, 2], [3, 4], [5, 6]].as_flattened(),
-);
-
-let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
-assert!(slice_of_empty_arrays.as_flattened().is_empty());
-
-let empty_slice_of_arrays: &[[u32; 10]] = &[];
-assert!(empty_slice_of_arrays.as_flattened().is_empty());
-1.80.0 · sourcepub fn as_flattened_mut(&mut self) -> &mut [T]
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
-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.as_flattened_mut());
-assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
-sourcepub 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());
-sourcepub 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.
-sourcepub 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.
-sourcepub 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§
§impl<'de, const N: usize> Deserialize<'de> for Bytes<N>
§fn deserialize<D>(
- deserializer: D,
-) -> Result<Bytes<N>, <D as Deserializer<'de>>::Error>where
- D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more§impl<'a, const N: usize> IntoIterator for &'a Bytes<N>
§impl<'a, const N: usize> IntoIterator for &'a mut Bytes<N>
§impl<const N: usize> IntoIterator for Bytes<N>
§impl<Rhs, const N: usize> PartialOrd<Rhs> for Bytes<N>
§fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>
1.0.0 · source§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§impl<const N: usize> Serialize for Bytes<N>
§fn serialize<S>(
- &self,
- serializer: S,
-) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
- S: Serializer,
Serialize this value into the given Serde serializer. Read more§impl<const N: usize> Eq for Bytes<N>
Auto Trait Implementations§
§impl<const N: usize> Freeze for Bytes<N>
§impl<const N: usize> RefUnwindSafe for Bytes<N>
§impl<const N: usize> Send for Bytes<N>
§impl<const N: usize> Sync for Bytes<N>
§impl<const N: usize> Unpin for Bytes<N>
§impl<const N: usize> UnwindSafe for Bytes<N>
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
- T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read moresource§impl<T> CloneToUninit for Twhere
- T: Clone,
source§default unsafe fn clone_to_uninit(&self, dst: *mut T)
🔬This is a nightly-only experimental API. (clone_to_uninit)source§impl<T> DeserializeOwned for Twhere
- T: for<'de> Deserialize<'de>,
\ No newline at end of file
diff --git a/search-index.js b/search-index.js
index 6e9fdc8..30c4ec6 100644
--- a/search-index.js
+++ b/search-index.js
@@ -1,5 +1,5 @@
var searchIndex = new Map(JSON.parse('[\
-["cbor_smol",{"t":"FEENNNNNNHHHHNNCNNNNNCNNNNNNNNNNNNNNNNNNNCNNNNNNNNFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNHNNNPPPPPPPPPPPPPPPPGPPPIPPPPPNNNNNNNNNNNNNNNNRFFKNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNO","n":["Bytes","Error","Result","as_mut","as_mut_slice","as_ref","as_slice","borrow","borrow_mut","cbor_deserialize","cbor_serialize","cbor_serialize_bytes","cbor_serialize_extending_bytes","clone","clone_to_uninit","de","default","deref","deref_mut","deserialize","eq","error","fmt","from","from","from","from_slice","hash","insert","insert_slice_at","into","into_inner","into_iter","into_iter","into_iter","into_vec","new","partial_cmp","remove","resize_default","resize_to_capacity","ser","serialize","to_bytes","try_convert_into","try_from","try_from","try_into","type_id","write_all","Deserializer","borrow","borrow_mut","deserialize_any","deserialize_bool","deserialize_byte_buf","deserialize_bytes","deserialize_char","deserialize_enum","deserialize_f32","deserialize_f64","deserialize_i16","deserialize_i32","deserialize_i64","deserialize_i8","deserialize_identifier","deserialize_ignored_any","deserialize_map","deserialize_newtype_struct","deserialize_option","deserialize_seq","deserialize_str","deserialize_string","deserialize_struct","deserialize_tuple","deserialize_tuple_struct","deserialize_u16","deserialize_u32","deserialize_u64","deserialize_u8","deserialize_unit","deserialize_unit_struct","from","from_bytes","from_bytes","into","take_from_bytes","try_from","try_into","type_id","DeserializeBadBool","DeserializeBadEnum","DeserializeBadI16","DeserializeBadI32","DeserializeBadI64","DeserializeBadI8","DeserializeBadMajor","DeserializeBadU16","DeserializeBadU32","DeserializeBadU64","DeserializeBadU8","DeserializeBadUtf8","DeserializeExpectedNull","DeserializeNonMinimal","DeserializeUnexpectedEnd","Err","Error","InexistentSliceToArrayError","NotYetImplemented","Ok","Result","SerdeDeCustom","SerdeMissingField","SerdeSerCustom","SerializeBufferFull","WontImplement","borrow","borrow_mut","clone","clone_to_uninit","clone_to_uninit","custom","custom","eq","fmt","fmt","from","into","missing_field","try_from","try_into","type_id","Error","Serializer","SliceWriter","Writer","borrow","borrow","borrow_mut","borrow_mut","bytes_written","collect_str","end","end","end","end","end","fmt","from","from","into","into","into_inner","into_inner","is_human_readable","new","new","serialize_bool","serialize_bytes","serialize_char","serialize_element","serialize_f32","serialize_f64","serialize_field","serialize_field","serialize_field","serialize_field","serialize_i16","serialize_i32","serialize_i64","serialize_i8","serialize_map","serialize_newtype_struct","serialize_newtype_variant","serialize_none","serialize_seq","serialize_some","serialize_str","serialize_struct","serialize_struct_variant","serialize_tuple","serialize_tuple_struct","serialize_tuple_variant","serialize_u16","serialize_u32","serialize_u64","serialize_u8","serialize_unit","serialize_unit_struct","serialize_unit_variant","try_from","try_from","try_into","try_into","type_id","type_id","write_all","write_all","writer"],"q":[[0,"cbor_smol"],[50,"cbor_smol::de"],[90,"cbor_smol::error"],[132,"cbor_smol::ser"],[199,"heapless_bytes"],[200,"serde::de"],[201,"core::marker"],[202,"serde::ser"],[203,"core::result"],[204,"core::convert"],[205,"core::fmt"],[206,"heapless::vec"],[207,"core::hash"],[208,"core::cmp"],[209,"core::option"],[210,"core::ops::function"],[211,"core::any"]],"i":[0,0,0,2,2,2,2,2,2,0,0,0,0,2,2,0,2,2,2,2,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,2,2,2,2,2,2,2,0,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,0,27,27,0,27,27,27,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,6,0,31,31,6,0,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,36,0,0,0,35,34,35,34,34,35,35,35,35,35,35,34,35,34,35,34,35,34,35,35,34,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,35,34,35,34,35,34,36,34,35],"f":"```{{{f{bd}}}{{f{b{j{h}}}}}}0{{{f{d}}}{{f{{j{h}}}}}}0{{{f{c}}}{{f{e}}}{}{}}{{{f{bc}}}{{f{be}}}{}{}}{{{f{{j{h}}}}}{{l{c}}}n}{{{f{c}}{f{b{j{h}}}}}{{l{{f{{j{h}}}}}}}{A`Ab}}{{{f{c}}}{{l{d}}}{A`Ab}}{{{f{c}}{f{bd}}}{{l{Ad}}}{A`Ab}}{{{f{d}}}d}{{{f{c}}}Af{}}`{{}d}{{{f{d}}}f}{{{f{bd}}}{{f{b}}}}{c{{Ah{d}}}Aj}{{{f{d}}{f{c}}}Al{{An{{j{h}}}}A`}}`{{{f{d}}{f{bB`}}}{{Ah{AfBb}}}}{cd{{Bf{{Bd{h}}}}}}{{{Bd{h}}}d}{cc{}}{{{f{{j{h}}}}}{{Ah{dAf}}}}{{{f{d}}{f{bc}}}AfBh}{{{f{bd}}Adh}{{Ah{Afh}}}}{{{f{bd}}{f{{j{h}}}}Ad}{{Ah{AfAf}}}}{ce{}{}}{d{{Bd{h}}}}{d}{{{f{bd}}}}{{{f{d}}}}3{{}d}{{{f{d}}{f{c}}}{{Bl{Bj}}}{{An{{j{h}}}}A`}}{{{f{bd}}Ad}{{Ah{hAf}}}}{{{f{bd}}Ad}{{Ah{AfAf}}}}{{{f{bd}}}Af}`{{{f{d}}c}AhBn}{{{f{d}}}{{Ah{dAf}}}}0{e{{Ah{dc}}}{}{{Cb{{f{b{j{h}}}}}{{C`{{Ah{Adc}}}}}}}}{c{{Ah{e}}}{}{}}0{{{f{c}}}Cd{}}{{{f{b{f{bd}}}}{f{{j{h}}}}}{{l{Af}}}}`{{{f{c}}}{{f{e}}}{}{}}{{{f{bc}}}{{f{be}}}{}{}}{{{f{bCf}}c}lCh}0000{{{f{bCf}}{f{Cj}}{f{{j{{f{Cj}}}}}}c}lCh}111111111{{{f{bCf}}{f{Cj}}c}lCh}22221{{{f{bCf}}Adc}lCh}{{{f{bCf}}{f{Cj}}Adc}lCh}444442{cc{}}{{{f{{j{h}}}}}{{l{c}}}n}{{{f{{j{h}}}}}Cf}{ce{}{}}{{{f{{j{h}}}}}{{l{{Cl{c{f{{j{h}}}}}}}}}n}>>=``````````````````````````;:{{{f{Cn}}}Cn}{{{f{c}}}Af{}}0{cCnD`}0{{{f{Cn}}{f{Cn}}}Al}{{{f{Cn}}{f{bB`}}}Db}096{{{f{Cj}}}Cn}{c{{Ah{e}}}{}{}}0{{{f{c}}}Cd{}}````{{{f{c}}}{{f{e}}}{}{}}0{{{f{bc}}}{{f{be}}}{}{}}0{{{f{Dd}}}Ad}{{{f{b{Df{c}}}}{f{e}}}{{l{g}}}Dh{D`A`}{}}{{{f{b{Df{c}}}}}{{l{Af}}}Dh}0000{{{f{Dd}}{f{bB`}}}Db}{cc{}}0{ce{}{}}0{{{Df{c}}}cDh}{Dd{{f{b{j{h}}}}}}{{{f{{f{b{Df{c}}}}}}}AlDh}{c{{Df{c}}}Dh}{{{f{b{j{h}}}}}Dd}{{{f{b{Df{c}}}}Al}{{l{Af}}}Dh}{{{f{b{Df{c}}}}{f{{j{h}}}}}{{l{Af}}}Dh}{{{f{b{Df{c}}}}Dj}{{l{Af}}}Dh}{{{f{b{f{b{Df{c}}}}}}{f{e}}}{{l{Af}}}Dh{A`Ab}}{{{f{b{Df{c}}}}Dl}{{l{Af}}}Dh}{{{f{b{Df{c}}}}Dn}{{l{Af}}}Dh}22{{{f{b{f{b{Df{c}}}}}}{f{Cj}}{f{e}}}{{l{Af}}}Dh{A`Ab}}0{{{f{b{Df{c}}}}E`}{{l{Af}}}Dh}{{{f{b{Df{c}}}}Eb}{{l{Af}}}Dh}{{{f{b{Df{c}}}}Ed}{{l{Af}}}Dh}{{{f{b{Df{c}}}}Ef}{{l{Af}}}Dh}{{{f{b{Df{c}}}}{Bl{Ad}}}{{l{{`{c}}}}}Dh}{{{f{b{Df{c}}}}{f{Cj}}{f{e}}}{{l{Af}}}Dh{A`Ab}}{{{f{b{Df{c}}}}{f{Cj}}Eh{f{Cj}}{f{e}}}{{l{Af}}}Dh{A`Ab}}{{{f{b{Df{c}}}}}{{l{Af}}}Dh}3{{{f{b{Df{c}}}}{f{e}}}{{l{Af}}}Dh{A`Ab}}{{{f{b{Df{c}}}}{f{Cj}}}{{l{Af}}}Dh}{{{f{b{Df{c}}}}{f{Cj}}Ad}{{l{e}}}Dh{}}{{{f{b{Df{c}}}}{f{Cj}}Eh{f{Cj}}Ad}{{l{e}}}Dh{}}{{{f{b{Df{c}}}}Ad}{{l{{f{b{Df{c}}}}}}}Dh}{{{f{b{Df{c}}}}{f{Cj}}Ad}{{l{{f{b{Df{c}}}}}}}Dh}{{{f{b{Df{c}}}}{f{Cj}}Eh{f{Cj}}Ad}{{l{{f{b{Df{c}}}}}}}Dh}{{{f{b{Df{c}}}}Ej}{{l{Af}}}Dh}{{{f{b{Df{c}}}}Eh}{{l{Af}}}Dh}{{{f{b{Df{c}}}}El}{{l{Af}}}Dh}{{{f{b{Df{c}}}}h}{{l{Af}}}Dh};9{{{f{b{Df{c}}}}{f{Cj}}Eh{f{Cj}}}{{l{Af}}}Dh}{c{{Ah{e}}}{}{}}000{{{f{c}}}Cd{}}0{{{f{b{Dh{}{{En{c}}}}}}{f{{j{h}}}}}{{Ah{Afc}}}{{Bf{Cn}}}}{{{f{bDd}}{f{{j{h}}}}}{{l{Af}}}}`","D":"Gb","p":[[0,"mut"],[5,"Bytes",0,199],[1,"reference"],[1,"u8"],[1,"slice"],[8,"Result",90],[10,"Deserialize",200],[10,"Sized",201],[10,"Serialize",202],[1,"usize"],[1,"unit"],[6,"Result",203],[10,"Deserializer",200],[1,"bool"],[10,"AsRef",204],[5,"Formatter",205],[5,"Error",205],[5,"Vec",206],[10,"Into",204],[10,"Hasher",207],[6,"Ordering",208],[6,"Option",209],[10,"Serializer",202],[17,"Output"],[10,"FnOnce",210],[5,"TypeId",211],[5,"Deserializer",50],[10,"Visitor",200],[1,"str"],[1,"tuple"],[6,"Error",90],[10,"Display",205],[8,"Result",205],[5,"SliceWriter",132],[5,"Serializer",132],[10,"Writer",132],[1,"char"],[1,"f32"],[1,"f64"],[1,"i16"],[1,"i32"],[1,"i64"],[1,"i8"],[1,"u32"],[1,"u16"],[1,"u64"],[17,"Error"]],"r":[[0,199],[1,90],[2,90]],"b":[[23,"impl-Bytes%3CN%3E"],[24,"impl-From%3CVec%3Cu8,+N%3E%3E-for-Bytes%3CN%3E"],[32,"impl-IntoIterator-for-Bytes%3CN%3E"],[33,"impl-IntoIterator-for-%26mut+Bytes%3CN%3E"],[34,"impl-IntoIterator-for-%26Bytes%3CN%3E"],[121,"impl-Error-for-Error"],[122,"impl-Error-for-Error"],[124,"impl-Display-for-Error"],[125,"impl-Debug-for-Error"],[142,"impl-SerializeStructVariant-for-%26mut+Serializer%3CW%3E"],[143,"impl-SerializeTupleVariant-for-%26mut+Serializer%3CW%3E"],[144,"impl-SerializeTupleStruct-for-%26mut+Serializer%3CW%3E"],[145,"impl-SerializeTuple-for-%26mut+Serializer%3CW%3E"],[146,"impl-SerializeStruct-for-%26mut+Serializer%3CW%3E"],[163,"impl-SerializeTupleVariant-for-%26mut+Serializer%3CW%3E"],[164,"impl-SerializeTupleStruct-for-%26mut+Serializer%3CW%3E"],[165,"impl-SerializeStruct-for-%26mut+Serializer%3CW%3E"],[166,"impl-SerializeStructVariant-for-%26mut+Serializer%3CW%3E"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAI4AEgAAAAQABgAAAAgAAwAOAAkAGQAAABsAAwAhAAIAJgAFAC8AAwA0AB4AWAACAHUACQCBAAMAhgAGAI4ABgCbAAEAngAmAMYAAQA="}]\
+["cbor_smol",{"t":"EEHHHHHCCCFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNHNNNPPPPPPPPPPPPPPPPGPPPIPPPPPNNNNNNNNNNNNNNNNRFKNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMN","n":["Error","Result","cbor_deserialize","cbor_serialize","cbor_serialize_bytes","cbor_serialize_extending_bytes","cbor_serialize_to","de","error","ser","Deserializer","borrow","borrow_mut","deserialize_any","deserialize_bool","deserialize_byte_buf","deserialize_bytes","deserialize_char","deserialize_enum","deserialize_f32","deserialize_f64","deserialize_i16","deserialize_i32","deserialize_i64","deserialize_i8","deserialize_identifier","deserialize_ignored_any","deserialize_map","deserialize_newtype_struct","deserialize_option","deserialize_seq","deserialize_str","deserialize_string","deserialize_struct","deserialize_tuple","deserialize_tuple_struct","deserialize_u16","deserialize_u32","deserialize_u64","deserialize_u8","deserialize_unit","deserialize_unit_struct","from","from_bytes","from_bytes","into","take_from_bytes","try_from","try_into","type_id","DeserializeBadBool","DeserializeBadEnum","DeserializeBadI16","DeserializeBadI32","DeserializeBadI64","DeserializeBadI8","DeserializeBadMajor","DeserializeBadU16","DeserializeBadU32","DeserializeBadU64","DeserializeBadU8","DeserializeBadUtf8","DeserializeExpectedNull","DeserializeNonMinimal","DeserializeUnexpectedEnd","Err","Error","InexistentSliceToArrayError","NotYetImplemented","Ok","Result","SerdeDeCustom","SerdeMissingField","SerdeSerCustom","SerializeBufferFull","WontImplement","borrow","borrow_mut","clone","clone_to_uninit","clone_to_uninit","custom","custom","eq","fmt","fmt","from","into","missing_field","try_from","try_into","type_id","Error","Serializer","Writer","borrow","borrow_mut","collect_str","end","end","end","end","end","from","into","into_inner","is_human_readable","new","serialize_bool","serialize_bytes","serialize_char","serialize_element","serialize_f32","serialize_f64","serialize_field","serialize_field","serialize_field","serialize_field","serialize_i16","serialize_i32","serialize_i64","serialize_i8","serialize_map","serialize_newtype_struct","serialize_newtype_variant","serialize_none","serialize_seq","serialize_some","serialize_str","serialize_struct","serialize_struct_variant","serialize_tuple","serialize_tuple_struct","serialize_tuple_variant","serialize_u16","serialize_u32","serialize_u64","serialize_u8","serialize_unit","serialize_unit_struct","serialize_unit_variant","try_from","try_into","type_id","write_all","written"],"q":[[0,"cbor_smol"],[10,"cbor_smol::de"],[50,"cbor_smol::error"],[92,"cbor_smol::ser"],[146,"serde::de"],[147,"core::marker"],[148,"serde::ser"],[149,"heapless_bytes"],[150,"core::result"],[151,"core::any"],[152,"core::fmt"],[153,"core::option"],[154,"core::convert"]],"i":[0,0,0,0,0,0,0,0,0,0,0,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,0,12,12,0,12,12,12,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,4,0,18,18,4,0,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,11,0,0,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,11,24],"f":"``{{{f{{d{b}}}}}{{h{c}}}j}{{{f{c}}{f{l{d{b}}}}}{{h{{f{{d{b}}}}}}}{nA`}}{{{f{c}}}{{h{Ab}}}{nA`}}{{{f{c}}{f{lAb}}}{{h{Ad}}}{nA`}}{{{f{c}}e}{{h{Ad}}}{nA`}Af}````{{{f{c}}}{{f{e}}}{}{}}{{{f{lc}}}{{f{le}}}{}{}}{{{f{lAh}}c}hAj}0000{{{f{lAh}}{f{Al}}{f{{d{{f{Al}}}}}}c}hAj}111111111{{{f{lAh}}{f{Al}}c}hAj}22221{{{f{lAh}}Adc}hAj}{{{f{lAh}}{f{Al}}Adc}hAj}444442{cc{}}<{{{f{{d{b}}}}}Ah}{ce{}{}}{{{f{{d{b}}}}}{{h{{An{c{f{{d{b}}}}}}}}}j}{c{{B`{e}}}{}{}}0{{{f{c}}}Bb{}}``````````````````````````<;{{{f{Bd}}}Bd}{{{f{c}}}Bf{}}0{cBdBh}0{{{f{Bd}}{f{Bd}}}Bj}{{{f{Bd}}{f{lBl}}}Bn}0:8{{{f{Al}}}Bd}776```{{{f{c}}}{{f{e}}}{}{}}{{{f{lc}}}{{f{le}}}{}{}}{{{f{l{C`{c}}}}{f{e}}}{{h{g}}}Af{Bhn}{}}{{{f{l{C`{c}}}}}{{h{Bf}}}Af}0000?={{{C`{c}}}cAf}{{{f{{f{l{C`{c}}}}}}}BjAf}{c{{C`{c}}}Af}{{{f{l{C`{c}}}}Bj}{{h{Bf}}}Af}{{{f{l{C`{c}}}}{f{{d{b}}}}}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Cb}{{h{Bf}}}Af}{{{f{l{f{l{C`{c}}}}}}{f{e}}}{{h{Bf}}}Af{nA`}}{{{f{l{C`{c}}}}Cd}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Cf}{{h{Bf}}}Af}{{{f{l{f{l{C`{c}}}}}}{f{Al}}{f{e}}}{{h{Bf}}}Af{nA`}}303{{{f{l{C`{c}}}}Ch}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Cj}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Cl}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Cn}{{h{Bf}}}Af}{{{f{l{C`{c}}}}{D`{Ad}}}{{h{{`{c}}}}}Af}{{{f{l{C`{c}}}}{f{Al}}{f{e}}}{{h{Bf}}}Af{nA`}}{{{f{l{C`{c}}}}{f{Al}}Db{f{Al}}{f{e}}}{{h{Bf}}}Af{nA`}}{{{f{l{C`{c}}}}}{{h{Bf}}}Af}3{{{f{l{C`{c}}}}{f{e}}}{{h{Bf}}}Af{nA`}}{{{f{l{C`{c}}}}{f{Al}}}{{h{Bf}}}Af}{{{f{l{C`{c}}}}{f{Al}}Ad}{{h{e}}}Af{}}{{{f{l{C`{c}}}}{f{Al}}Db{f{Al}}Ad}{{h{e}}}Af{}}{{{f{l{C`{c}}}}Ad}{{h{{f{l{C`{c}}}}}}}Af}{{{f{l{C`{c}}}}{f{Al}}Ad}{{h{{f{l{C`{c}}}}}}}Af}{{{f{l{C`{c}}}}{f{Al}}Db{f{Al}}Ad}{{h{{f{l{C`{c}}}}}}}Af}{{{f{l{C`{c}}}}Dd}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Db}{{h{Bf}}}Af}{{{f{l{C`{c}}}}Df}{{h{Bf}}}Af}{{{f{l{C`{c}}}}b}{{h{Bf}}}Af};9{{{f{l{C`{c}}}}{f{Al}}Db{f{Al}}}{{h{Bf}}}Af}{c{{B`{e}}}{}{}}0{{{f{c}}}Bb{}}{{{f{l{Af{}{{Dh{c}}}}}}{f{{d{b}}}}}{{h{Bfc}}}{{Dj{Bd}}}}{{{f{{C`{c}}}}}AdAf}","D":"Ed","p":[[1,"u8"],[1,"slice"],[1,"reference"],[8,"Result",50],[10,"Deserialize",146],[0,"mut"],[10,"Sized",147],[10,"Serialize",148],[5,"Bytes",149],[1,"usize"],[10,"Writer",92],[5,"Deserializer",10],[10,"Visitor",146],[1,"str"],[1,"tuple"],[6,"Result",150],[5,"TypeId",151],[6,"Error",50],[1,"unit"],[10,"Display",152],[1,"bool"],[5,"Formatter",152],[8,"Result",152],[5,"Serializer",92],[1,"char"],[1,"f32"],[1,"f64"],[1,"i16"],[1,"i32"],[1,"i64"],[1,"i8"],[6,"Option",153],[1,"u32"],[1,"u16"],[1,"u64"],[17,"Error"],[10,"Into",154]],"r":[[0,50],[1,50]],"b":[[81,"impl-Error-for-Error"],[82,"impl-Error-for-Error"],[84,"impl-Debug-for-Error"],[85,"impl-Display-for-Error"],[98,"impl-SerializeTuple-for-%26mut+Serializer%3CW%3E"],[99,"impl-SerializeTupleStruct-for-%26mut+Serializer%3CW%3E"],[100,"impl-SerializeStruct-for-%26mut+Serializer%3CW%3E"],[101,"impl-SerializeTupleVariant-for-%26mut+Serializer%3CW%3E"],[102,"impl-SerializeStructVariant-for-%26mut+Serializer%3CW%3E"],[114,"impl-SerializeStruct-for-%26mut+Serializer%3CW%3E"],[115,"impl-SerializeTupleVariant-for-%26mut+Serializer%3CW%3E"],[116,"impl-SerializeStructVariant-for-%26mut+Serializer%3CW%3E"],[117,"impl-SerializeTupleStruct-for-%26mut+Serializer%3CW%3E"]],"c":"OjAAAAEAAAAAAAAAEAAAAAYA","e":"OzAAAAEAAGgACQAAAAQACAACAAwAHgAwAAIATQAJAFkAAwBeAAkAawAlAJIAAAA="}]\
]'));
if (typeof exports !== 'undefined') exports.searchIndex = searchIndex;
else if (window.initSearch) window.initSearch(searchIndex);
diff --git a/search.desc/cbor_smol/cbor_smol-desc-0-.js b/search.desc/cbor_smol/cbor_smol-desc-0-.js
index daff7a1..d944a5e 100644
--- a/search.desc/cbor_smol/cbor_smol-desc-0-.js
+++ b/search.desc/cbor_smol/cbor_smol-desc-0-.js
@@ -1 +1 @@
-searchState.loadedDescShard("cbor_smol", 0, "Returns a mutable slice view.\nReturns an immutable slice view.\nSerialize object into newly allocated Bytes.\nAppend serialization of object to existing bytes, …\nWrap existing bytes in a Bytes<N>.\nReturns the argument unchanged.\nCalls U::from(self).\nUnwraps the Vec<u8, N>, same as into_vec.\nUnwraps the Vec<u8, N>, same as into_inner.\nConstruct a new, empty Bytes<N>.\nFallible conversion into differently sized byte buffer.\nLow-noise conversion between lengths.\nSome APIs offer an interface of the form …\nA structure for deserializing a cbor-smol message.\nReturns the argument unchanged.\nDeserialize a message of type T from a byte slice. The …\nObtain a Deserializer from a slice of bytes\nCalls U::from(self).\nDeserialize a message of type T from a byte slice. The …\nFound a bool that wasn’t 0xf4 or 0xf5\nCould not parse an enum\nExpected a i16, was too large\nExpected a i32, was too large\nExpected a i64, was too large\nExpected a i8, was too large\nExpected a different major type\nExpected a u16\nExpected a u32\nExpected a u64\nExpected a u8\nTried to parse invalid utf-8\nExpected a NULL marker\nValue may be valid, but not encoded in minimal way\nHit the end of buffer, expected more data\nContains the error value\nThis is the error type used by cbor-smol\nInexistent slice-to-array cast error. Used here to avoid …\nThis is a feature that cbor-smol intends to support, but …\nContains the success value\nThis is the Result type used by cbor-smol.\nSerde Deserialization Error\nSerde Missing required value\nSerde Serialization Error\nThe serialize buffer is full\nThis is a feature that cbor-smol will never implement\nReturns the argument unchanged.\nCalls U::from(self).\nThe type of error returned when a write operation fails.\nReturns the number of bytes written to the underlying …\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nUnwrap the Writer from the Serializer.\nReturns the underlying slice.\nWraps a mutable slice so it can be used as a Writer.\nAttempts to write an entire buffer into this write.")
\ No newline at end of file
+searchState.loadedDescShard("cbor_smol", 0, "Serialize object into newly allocated Bytes.\nAppend serialization of object to existing bytes, …\nSerialize an object to a Writer\nA structure for deserializing a cbor-smol message.\nReturns the argument unchanged.\nDeserialize a message of type T from a byte slice. The …\nObtain a Deserializer from a slice of bytes\nCalls U::from(self).\nDeserialize a message of type T from a byte slice. The …\nFound a bool that wasn’t 0xf4 or 0xf5\nCould not parse an enum\nExpected a i16, was too large\nExpected a i32, was too large\nExpected a i64, was too large\nExpected a i8, was too large\nExpected a different major type\nExpected a u16\nExpected a u32\nExpected a u64\nExpected a u8\nTried to parse invalid utf-8\nExpected a NULL marker\nValue may be valid, but not encoded in minimal way\nHit the end of buffer, expected more data\nContains the error value\nThis is the error type used by cbor-smol\nInexistent slice-to-array cast error. Used here to avoid …\nThis is a feature that cbor-smol intends to support, but …\nContains the success value\nThis is the Result type used by cbor-smol.\nSerde Deserialization Error\nSerde Missing required value\nSerde Serialization Error\nThe serialize buffer is full\nThis is a feature that cbor-smol will never implement\nReturns the argument unchanged.\nCalls U::from(self).\nThe type of error returned when a write operation fails.\nReturns the argument unchanged.\nCalls U::from(self).\nUnwrap the Writer from the Serializer.\nAttempts to write an entire buffer into this write.")
\ No newline at end of file
diff --git a/src/cbor_smol/de.rs.html b/src/cbor_smol/de.rs.html
index 2014905..278f906 100644
--- a/src/cbor_smol/de.rs.html
+++ b/src/cbor_smol/de.rs.html
@@ -1292,6 +1292,18 @@
1292
1293
1294
+1295
+1296
+1297
+1298
+1299
+1300
+1301
+1302
+1303
+1304
+1305
+1306
use serde::Deserialize;
use serde::de::IntoDeserializer;
@@ -1409,7 +1421,7 @@
fn raw_deserialize_u16(&mut self, major: u8) -> Result<u16> {
let number = self.raw_deserialize_u32(major)?;
- if number <= u16::max_value() as u32 {
+ if number <= u16::MAX as u32 {
Ok(number as u16)
} else {
Err(Error::DeserializeBadU16)
@@ -1739,7 +1751,7 @@
match self.peek_major()? {
MAJOR_POSINT => {
let raw_u8 = self.raw_deserialize_u8(0)?;
- if raw_u8 <= i8::max_value() as u8 {
+ if raw_u8 <= i8::MAX as u8 {
visitor.visit_i8(raw_u8 as i8)
} else {
Err(Error::DeserializeBadI8)
@@ -1747,7 +1759,7 @@
}
MAJOR_NEGINT => {
let raw_u8 = self.raw_deserialize_u8(1)?;
- // if raw_u8 <= 1 + i8::max_value() as u8 {
+ // if raw_u8 <= 1 + i8::MAX as u8 {
if raw_u8 <= 128 {
visitor.visit_i8(-1 - (raw_u8 as i16) as i8)
} else {
@@ -1765,7 +1777,7 @@
match self.peek_major()? {
MAJOR_POSINT => {
let raw = self.raw_deserialize_u16(0)?;
- if raw <= i16::max_value() as u16 {
+ if raw <= i16::MAX as u16 {
visitor.visit_i16(raw as i16)
} else {
Err(Error::DeserializeBadI16)
@@ -1773,7 +1785,7 @@
}
MAJOR_NEGINT => {
let raw = self.raw_deserialize_u16(1)?;
- if raw <= i16::max_value() as u16 {
+ if raw <= i16::MAX as u16 {
visitor.visit_i16(-1 - (raw as i16))
} else {
Err(Error::DeserializeBadI16)
@@ -1791,7 +1803,7 @@
// TODO: figure out if this is BAAAAD for size or speed
major @ 0..=1 => {
let raw = self.raw_deserialize_u32(major)?;
- if raw <= i32::max_value() as u32 {
+ if raw <= i32::MAX as u32 {
if major == MAJOR_POSINT {
visitor.visit_i32(raw as i32)
} else {
@@ -1813,7 +1825,7 @@
// TODO: figure out if this is BAAAAD for size or speed
major @ 0..=1 => {
let raw = self.raw_deserialize_u64(major)?;
- if raw <= i64::max_value() as u64 {
+ if raw <= i64::MAX as u64 {
if major == MAJOR_POSINT {
visitor.visit_i64(raw as i64)
} else {
@@ -1856,7 +1868,7 @@
V: Visitor<'de>,
{
let raw = self.raw_deserialize_u64(MAJOR_POSINT)?;
- visitor.visit_u64(raw as u64)
+ visitor.visit_u64(raw)
}
fn deserialize_f32<V>(self, _visitor: V) -> Result<V::Value>
@@ -2106,7 +2118,8 @@
// strings to fields (and the mapping from bytes to fields can be optimized out).
let length = self.raw_deserialize_u32(major)? as usize;
let bytes: &'de [u8] = self.try_take_n(length)?;
- let string_slice = core::str::from_utf8(bytes).map_err(|_| Error::DeserializeBadUtf8)?;
+ let string_slice =
+ core::str::from_utf8(bytes).map_err(|_| Error::DeserializeBadUtf8)?;
visitor.visit_borrowed_str(string_slice)
}
MAJOR_POSINT => self.deserialize_u64(visitor),
@@ -2264,7 +2277,7 @@
fn de_i16() {
let mut buf = [0u8; 64];
- for number in i16::min_value()..=i16::max_value() {
+ for number in i16::min_value()..=i16::MAX {
println!("testing {}", number);
let _n = cbor_serialize(&number, &mut buf).unwrap();
let de: i16 = from_bytes(&buf).unwrap();
@@ -2276,14 +2289,14 @@
fn de_u32() {
let mut buf = [0u8; 64];
- for number in 0..=3 * (u16::max_value() as u32) {
+ for number in 0..=3 * (u16::MAX as u32) {
println!("testing {}", number);
let _n = cbor_serialize(&number, &mut buf).unwrap();
let de: u32 = from_bytes(&buf).unwrap();
assert_eq!(de, number);
}
- for number in (u32::max_value() - u16::max_value() as u32)..=u32::max_value() {
+ for number in (u32::MAX - u16::MAX as u32)..=u32::MAX {
println!("testing {}", number);
let _n = cbor_serialize(&number, &mut buf).unwrap();
let de: u32 = from_bytes(&buf).unwrap();
@@ -2326,14 +2339,14 @@
let de: i32 = from_bytes(ser).unwrap();
assert_eq!(de, number);
- for number in (3 * i16::min_value() as i32)..=3 * (i16::max_value() as i32) {
+ for number in (3 * i16::min_value() as i32)..=3 * (i16::MAX as i32) {
println!("testing {}", number);
let ser = cbor_serialize(&number, &mut buf).unwrap();
let de: i32 = from_bytes(ser).unwrap();
assert_eq!(de, number);
}
- for number in (i32::max_value() - i16::max_value() as i32)..=i32::max_value() {
+ for number in (i32::MAX - i16::MAX as i32)..=i32::MAX {
println!("testing {}", number);
let ser = cbor_serialize(&number, &mut buf).unwrap();
let de: i32 = from_bytes(ser).unwrap();
@@ -2348,17 +2361,28 @@
}
}
- #[test]
+ #[cfg_attr(
+ not(feature = "heapless-bytes-v0-4"),
+ ignore = "Enable heapless-bytes-v0-4 feature"
+ )]
+ #[test]
fn de_bytes() {
- let mut buf = [0u8; 64];
+ #[cfg(feature = "heapless-bytes-v0-4")]
+ {
+ let mut buf = [0u8; 64];
- let slice = b"thank you postcard!";
- let bytes = crate::Bytes::<64>::from_slice(slice).unwrap();
- let ser = cbor_serialize(&bytes, &mut buf).unwrap();
- println!("serialized bytes = {:?}", ser);
- let de: crate::Bytes<64> = from_bytes(&buf).unwrap();
- println!("deserialized bytes = {:?}", &de);
- assert_eq!(&de, slice);
+ let slice = b"thank you postcard!";
+ let bytes = heapless_bytes_v0_4::Bytes::<64>::try_from(slice).unwrap();
+ let ser = cbor_serialize(&bytes, &mut buf).unwrap();
+ println!("serialized bytes = {:?}", ser);
+ let de: heapless_bytes_v0_4::Bytes<64> = from_bytes(&buf).unwrap();
+ println!("deserialized bytes = {:?}", &de);
+ assert_eq!(&de, slice);
+ }
+ #[cfg(not(feature = "heapless-bytes-v0-4"))]
+ {
+ panic!("This test must be run with the heapless-v0-4 feature")
+ }
}
#[test]
@@ -2366,10 +2390,10 @@
let mut buf = [0u8; 64];
let string_slice = "thank you postcard, for blazing the path 🐝";
- let mut string = heapless::String::<64>::new();
+ let mut string = heapless_v0_8::String::<64>::new();
string.push_str(string_slice).unwrap();
let _n = cbor_serialize(&string, &mut buf);
- let de: heapless::String<64> = from_bytes(&buf).unwrap();
+ let de: heapless_v0_8::String<64> = from_bytes(&buf).unwrap();
assert_eq!(de, string_slice);
}
diff --git a/src/cbor_smol/error.rs.html b/src/cbor_smol/error.rs.html
index 21423cc..5051f8e 100644
--- a/src/cbor_smol/error.rs.html
+++ b/src/cbor_smol/error.rs.html
@@ -153,7 +153,7 @@
use core::fmt::{Display, Formatter};
/// This is the Result type used by cbor-smol.
-pub type Result<T> = core::result::Result<T, Error>;
+pub type Result<T, Err = Error> = core::result::Result<T, Err>;
/// This is the error type used by cbor-smol
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
diff --git a/src/cbor_smol/lib.rs.html b/src/cbor_smol/lib.rs.html
index 2faa4fc..801b8ee 100644
--- a/src/cbor_smol/lib.rs.html
+++ b/src/cbor_smol/lib.rs.html
@@ -58,59 +58,73 @@
58
59
60
+61
+62
+63
+64
+65
+66
+67
#![cfg_attr(not(test), no_std)]
#[macro_use]
extern crate delog;
generate_macros!();
-pub use heapless_bytes::Bytes;
-
pub(crate) mod consts;
pub mod de;
pub mod error;
pub mod ser;
pub use error::{Error, Result};
+use ser::Writer;
-// pub use de::from_bytes;
-// pub use de::take_from_bytes;
+/// Serialize an object to a `Writer`
+///
+/// Returns the amount of bytes written to the writer
+pub fn cbor_serialize_to<T: ?Sized + serde::Serialize, W: Writer>(
+ object: &T,
+ writer: W,
+) -> Result<usize> {
+ let mut serializer = ser::Serializer::new(writer);
+ object.serialize(&mut serializer)?;
+ Ok(serializer.written())
+}
-// kudos to postcard, this is much nicer than returning size
+// kudos to postcard, this is much nicer than returning size
pub fn cbor_serialize<'a, T: ?Sized + serde::Serialize>(
object: &T,
buffer: &'a mut [u8],
) -> Result<&'a [u8]> {
- let writer = ser::SliceWriter::new(buffer);
- let mut ser = ser::Serializer::new(writer);
-
- object.serialize(&mut ser)?;
-
- let writer = ser.into_inner();
- let size = writer.bytes_written();
-
- Ok(&buffer[..size])
+ let mut buf = &mut *buffer;
+ let written = cbor_serialize_to(object, &mut buf)?;
+ Ok(&buffer[..written])
}
-/// Append serialization of object to existing bytes, returning length of serialized object.
+#[cfg(feature = "heapless-bytes-v0-3")]
+#[deprecated(note = "use `cbor_serialize_to` instead")]
+/// Append serialization of object to existing bytes, returning length of serialized object.
pub fn cbor_serialize_extending_bytes<T: ?Sized + serde::Serialize, const N: usize>(
object: &T,
- bytes: &mut Bytes<N>,
+ bytes: &mut heapless_bytes_v0_3::Bytes<N>,
) -> Result<usize> {
let len_before = bytes.len();
- let mut ser = ser::Serializer::new(bytes);
+ let vec: &mut heapless_v0_7::Vec<u8, N> = bytes;
+ let mut ser = ser::Serializer::new(vec);
object.serialize(&mut ser)?;
Ok(ser.into_inner().len() - len_before)
}
-/// Serialize object into newly allocated Bytes.
+#[cfg(feature = "heapless-bytes-v0-3")]
+/// Serialize object into newly allocated Bytes.
pub fn cbor_serialize_bytes<T: ?Sized + serde::Serialize, const N: usize>(
object: &T,
-) -> Result<Bytes<N>> {
- let mut data = Bytes::<N>::new();
- cbor_serialize_extending_bytes(object, &mut data)?;
+) -> Result<heapless_bytes_v0_3::Bytes<N>> {
+ let mut data = heapless_bytes_v0_3::Bytes::<N>::new();
+ #[allow(deprecated)]
+ cbor_serialize_extending_bytes(object, &mut data)?;
Ok(data)
}
diff --git a/src/cbor_smol/ser.rs.html b/src/cbor_smol/ser.rs.html
index 32d8cca..c875b48 100644
--- a/src/cbor_smol/ser.rs.html
+++ b/src/cbor_smol/ser.rs.html
@@ -608,173 +608,157 @@
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
use super::error::{Error, Result};
use serde::ser;
use serde::Serialize;
+use core::mem;
+
use crate::consts::*;
-// pub fn to_slice<'a, 'b, T>(value: &'a T, buf: &'b mut [u8]) -> Result<&'b mut [u8]>
-// where
-// T: Serialize + ?Sized,
-// {
-// serialize_with_flavor::<T, Slice<'a>, &'a mut [u8]>(value, Slice::new(buf))
-// }
-
-pub trait Writer {
+pub trait Writer {
/// The type of error returned when a write operation fails.
type Error: Into<Error>;
/// Attempts to write an entire buffer into this write.
- fn write_all(&mut self, buf: &[u8]) -> core::result::Result<(), Self::Error>;
+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
}
-#[derive(Debug)]
-pub struct SliceWriter<'a> {
- slice: &'a mut [u8],
- index: usize,
-}
-
-impl<'a> SliceWriter<'a> {
- /// Wraps a mutable slice so it can be used as a `Writer`.
- pub fn new(slice: &'a mut [u8]) -> SliceWriter<'a> {
- SliceWriter { slice, index: 0 }
- }
-
- /// Returns the number of bytes written to the underlying slice.
- pub fn bytes_written(&self) -> usize {
- self.index
- }
-
- /// Returns the underlying slice.
- pub fn into_inner(self) -> &'a mut [u8] {
- self.slice
- }
-}
-
-impl<'a> Writer for SliceWriter<'a> {
+impl<'a> Writer for &'a mut [u8] {
type Error = Error;
-
fn write_all(&mut self, buf: &[u8]) -> Result<()> {
let l = buf.len();
- if self.slice.len() - self.index < l {
+ if self.len() < l {
// This buffer will not fit in our slice
- return Err(Error::SerializeBufferFull(self.index));
+ return Err(Error::SerializeBufferFull(0));
}
- self.slice[self.index..][..l].copy_from_slice(buf);
- self.index += l;
+ let (current, rem) = mem::take(self).split_at_mut(l);
+ current.copy_from_slice(buf);
+ *self = rem;
Ok(())
}
}
-impl<'a, const N: usize> Writer for &'a mut crate::Bytes<N> {
+#[cfg(feature = "heapless-bytes-v0-3")]
+impl<const N: usize> Writer for heapless_bytes_v0_3::Bytes<N> {
type Error = Error;
-
fn write_all(&mut self, buf: &[u8]) -> Result<()> {
self.extend_from_slice(buf)
- .map_err(|_| Error::SerializeBufferFull(buf.len()))
+ .or(Err(Error::SerializeBufferFull(self.len())))
}
}
-pub struct Serializer<W>
-// where
-// W: Writer,
-{
- pub writer: W,
+#[cfg(feature = "heapless-bytes-v0-4")]
+impl<const N: usize> Writer for heapless_bytes_v0_4::Bytes<N> {
+ type Error = Error;
+ fn write_all(&mut self, buf: &[u8]) -> Result<()> {
+ self.extend_from_slice(buf)
+ .or(Err(Error::SerializeBufferFull(self.len())))
+ }
+}
+
+#[cfg(feature = "heapless-v0-7")]
+impl<const N: usize> Writer for heapless_v0_7::Vec<u8, N> {
+ type Error = Error;
+ fn write_all(&mut self, buf: &[u8]) -> Result<()> {
+ self.extend_from_slice(buf)
+ .or(Err(Error::SerializeBufferFull(self.len())))
+ }
+}
+
+#[cfg(feature = "heapless-v0-8")]
+impl<const N: usize> Writer for heapless_v0_8::Vec<u8, N> {
+ type Error = Error;
+ fn write_all(&mut self, buf: &[u8]) -> Result<()> {
+ self.extend_from_slice(buf)
+ .or(Err(Error::SerializeBufferFull(self.len())))
+ }
+}
+
+impl<'a, T: Writer> Writer for &'a mut T {
+ type Error = T::Error;
+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
+ (**self).write_all(buf)
+ }
+}
+
+struct WrittenWriter<W> {
+ writer: W,
+ written: usize,
+}
+
+impl<W: Writer> Writer for WrittenWriter<W> {
+ type Error = W::Error;
+
+ fn write_all(&mut self, buf: &[u8]) -> core::result::Result<(), Self::Error> {
+ self.written += buf.len();
+ self.writer.write_all(buf)
+ }
+}
+
+pub struct Serializer<W> {
+ inner: WrittenWriter<W>,
}
impl<W: Writer> Serializer<W> {
#[inline]
pub fn new(writer: W) -> Self {
Serializer {
- writer,
- // packed: false,
- // enum_as_map: true,
- }
+ inner: WrittenWriter { writer, written: 0 },
+ }
+ }
+
+ pub fn written(&self) -> usize {
+ self.inner.written
}
/// Unwrap the `Writer` from the `Serializer`.
#[inline]
pub fn into_inner(self) -> W {
- self.writer
+ self.inner.writer
}
#[inline]
fn write_u8(&mut self, major: u8, value: u8) -> Result<()> {
if value <= 0x17 {
- self.writer.write_all(&[major << MAJOR_OFFSET | value])
+ self.inner.write_all(&[major << MAJOR_OFFSET | value])
} else {
let buf = [major << MAJOR_OFFSET | 24, value];
- self.writer.write_all(&buf)
+ self.inner.write_all(&buf)
}
.map_err(|e| e.into())
}
#[inline]
fn write_u16(&mut self, major: u8, value: u16) -> Result<()> {
- if value <= u16::from(u8::max_value()) {
+ if value <= u16::from(u8::MAX) {
self.write_u8(major, value as u8)
} else {
let mut buf = [major << MAJOR_OFFSET | 25, 0, 0];
buf[1..].copy_from_slice(&value.to_be_bytes());
- self.writer.write_all(&buf).map_err(|e| e.into())
+ self.inner.write_all(&buf).map_err(|e| e.into())
}
}
#[inline]
fn write_u32(&mut self, major: u8, value: u32) -> Result<()> {
- if value <= u32::from(u16::max_value()) {
+ if value <= u32::from(u16::MAX) {
self.write_u16(major, value as u16)
} else {
let mut buf = [major << MAJOR_OFFSET | 26, 0, 0, 0, 0];
buf[1..].copy_from_slice(&value.to_be_bytes());
- self.writer.write_all(&buf).map_err(|e| e.into())
+ self.inner.write_all(&buf).map_err(|e| e.into())
}
}
#[inline]
fn write_u64(&mut self, major: u8, value: u64) -> Result<()> {
- if value <= u64::from(u32::max_value()) {
+ if value <= u64::from(u32::MAX) {
self.write_u32(major, value as u32)
} else {
let mut buf = [major << MAJOR_OFFSET | 27, 0, 0, 0, 0, 0, 0, 0, 0];
buf[1..].copy_from_slice(&value.to_be_bytes());
- self.writer.write_all(&buf).map_err(|e| e.into())
+ self.inner.write_all(&buf).map_err(|e| e.into())
}
}
@@ -790,7 +774,7 @@
false
}
None => {
- self.writer
+ self.inner
.write_all(&[major << MAJOR_OFFSET | 31])
.map_err(|e| e.into())?;
true
@@ -812,15 +796,7 @@
type Error = Error;
- // type SerializeSeq = Self;
- // type SerializeTuple = Self;
- // type SerializeTupleStruct = Self;
- // type SerializeTupleVariant = Self;
- // type SerializeMap = Self;
- // type SerializeStruct = Self;
- // type SerializeStructVariant = Self;
-
- type SerializeSeq = CollectionSerializer<'a, W>;
+ type SerializeSeq = CollectionSerializer<'a, W>;
type SerializeTuple = &'a mut Serializer<W>;
type SerializeTupleStruct = &'a mut Serializer<W>;
type SerializeTupleVariant = &'a mut Serializer<W>;
@@ -831,7 +807,7 @@
#[inline]
fn serialize_bool(self, value: bool) -> Result<()> {
let value = if value { VALUE_TRUE } else { VALUE_FALSE };
- self.writer.write_all(&[value]).map_err(|e| e.into())
+ self.inner.write_all(&[value]).map_err(|e| e.into())
}
#[inline]
@@ -904,20 +880,18 @@
#[inline]
fn serialize_str(self, value: &str) -> Result<()> {
self.write_u64(MAJOR_STR, value.len() as u64)?;
- self.writer
- .write_all(value.as_bytes())
- .map_err(|e| e.into())
+ self.inner.write_all(value.as_bytes()).map_err(|e| e.into())
}
#[inline]
fn serialize_bytes(self, value: &[u8]) -> Result<()> {
self.write_u64(MAJOR_BYTES, value.len() as u64)?;
- self.writer.write_all(value).map_err(|e| e.into())
+ self.inner.write_all(value).map_err(|e| e.into())
}
#[inline]
fn serialize_none(self) -> Result<()> {
- self.writer.write_all(&[VALUE_NULL]).map_err(|e| e.into())
+ self.inner.write_all(&[VALUE_NULL]).map_err(|e| e.into())
}
#[inline]
@@ -1030,20 +1004,7 @@
self.serialize_collection(MAJOR_MAP, len)
}
- // #[cfg(not(feature = "std"))]
- // fn collect_str<T: ?Sized>(self, value: &T) -> Result<()>
- // where
- // T: core::fmt::Display,
- // {
- // use crate::write::FmtWrite;
- // use core::fmt::Write;
-
- // let mut w = FmtWrite::new(&mut self.writer);
- // write!(w, "{}", value)?;
- // Ok(())
- // }
-
- #[inline]
+ #[inline]
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
self.write_u64(MAJOR_MAP, len as u64)?;
Ok(self)
@@ -1066,9 +1027,9 @@
self.serialize_struct(name, len)
}
- fn collect_str<T: ?Sized>(self, _value: &T) -> Result<Self::Ok>
+ fn collect_str<T>(self, _value: &T) -> Result<Self::Ok>
where
- T: core::fmt::Display,
+ T: core::fmt::Display + ?Sized,
{
unreachable!()
}
@@ -1079,28 +1040,7 @@
}
}
-// impl<'a, W> ser::SerializeSeq for CollectionSerializer<'a, W>
-// where
-// W: Writer,
-// {
-// type Ok = ();
-// type Error = Error;
-
-// #[inline]
-// fn serialize_element<T>(&mut self, value: &T) -> Result<()>
-// where
-// T: ?Sized + ser::Serialize,
-// {
-// value.serialize(&mut *self.ser)
-// }
-
-// #[inline]
-// fn end(self) -> Result<()> {
-// self.end_inner()
-// }
-// }
-
-impl<'a, W> ser::SerializeTuple for &'a mut Serializer<W>
+impl<'a, W> ser::SerializeTuple for &'a mut Serializer<W>
where
W: Writer,
{
@@ -1180,12 +1120,7 @@
Ok(())
}
- // #[inline]
- // fn skip_field(&mut self, key: &'static str) -> Result<()> {
- // Ok(())
- // }
-
- #[inline]
+ #[inline]
fn end(self) -> Result<()> {
Ok(())
}
@@ -1208,12 +1143,7 @@
Ok(())
}
- // #[inline]
- // fn skip_field(&mut self, key: &'static str) -> Result<()> {
- // Ok(())
- // }
-
- #[inline]
+ #[inline]
fn end(self) -> Result<()> {
Ok(())
}
@@ -1232,7 +1162,7 @@
#[inline]
fn end_inner(self) -> Result<()> {
if self.needs_eof {
- self.ser.writer.write_all(&[0xff]).map_err(|e| e.into())
+ self.ser.inner.write_all(&[0xff]).map_err(|e| e.into())
} else {
Ok(())
}
diff --git a/trait.impl/core/fmt/trait.Debug.js b/trait.impl/core/fmt/trait.Debug.js
index a7f97d6..f2ac6fd 100644
--- a/trait.impl/core/fmt/trait.Debug.js
+++ b/trait.impl/core/fmt/trait.Debug.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl Debug for Error"],["impl<'a> Debug for SliceWriter<'a>"]]
+"cbor_smol":[["impl Debug for Error"]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file
diff --git a/trait.impl/core/marker/trait.Freeze.js b/trait.impl/core/marker/trait.Freeze.js
index 3814eb4..739d65d 100644
--- a/trait.impl/core/marker/trait.Freeze.js
+++ b/trait.impl/core/marker/trait.Freeze.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl Freeze for Error",1,["cbor_smol::error::Error"]],["impl<'a> Freeze for SliceWriter<'a>",1,["cbor_smol::ser::SliceWriter"]],["impl<'de> Freeze for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Freeze for Serializer<W>where\n W: Freeze,",1,["cbor_smol::ser::Serializer"]]]
+"cbor_smol":[["impl Freeze for Error",1,["cbor_smol::error::Error"]],["impl<'de> Freeze for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Freeze for Serializer<W>where\n W: Freeze,",1,["cbor_smol::ser::Serializer"]]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file
diff --git a/trait.impl/core/marker/trait.Send.js b/trait.impl/core/marker/trait.Send.js
index 456b4b2..61d39aa 100644
--- a/trait.impl/core/marker/trait.Send.js
+++ b/trait.impl/core/marker/trait.Send.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl Send for Error",1,["cbor_smol::error::Error"]],["impl<'a> Send for SliceWriter<'a>",1,["cbor_smol::ser::SliceWriter"]],["impl<'de> Send for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Send for Serializer<W>where\n W: Send,",1,["cbor_smol::ser::Serializer"]]]
+"cbor_smol":[["impl Send for Error",1,["cbor_smol::error::Error"]],["impl<'de> Send for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Send for Serializer<W>where\n W: Send,",1,["cbor_smol::ser::Serializer"]]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file
diff --git a/trait.impl/core/marker/trait.Sync.js b/trait.impl/core/marker/trait.Sync.js
index ca398c6..db74b50 100644
--- a/trait.impl/core/marker/trait.Sync.js
+++ b/trait.impl/core/marker/trait.Sync.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl Sync for Error",1,["cbor_smol::error::Error"]],["impl<'a> Sync for SliceWriter<'a>",1,["cbor_smol::ser::SliceWriter"]],["impl<'de> Sync for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Sync for Serializer<W>where\n W: Sync,",1,["cbor_smol::ser::Serializer"]]]
+"cbor_smol":[["impl Sync for Error",1,["cbor_smol::error::Error"]],["impl<'de> Sync for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Sync for Serializer<W>where\n W: Sync,",1,["cbor_smol::ser::Serializer"]]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file
diff --git a/trait.impl/core/marker/trait.Unpin.js b/trait.impl/core/marker/trait.Unpin.js
index 782dc0e..073d005 100644
--- a/trait.impl/core/marker/trait.Unpin.js
+++ b/trait.impl/core/marker/trait.Unpin.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl Unpin for Error",1,["cbor_smol::error::Error"]],["impl<'a> Unpin for SliceWriter<'a>",1,["cbor_smol::ser::SliceWriter"]],["impl<'de> Unpin for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Unpin for Serializer<W>where\n W: Unpin,",1,["cbor_smol::ser::Serializer"]]]
+"cbor_smol":[["impl Unpin for Error",1,["cbor_smol::error::Error"]],["impl<'de> Unpin for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> Unpin for Serializer<W>where\n W: Unpin,",1,["cbor_smol::ser::Serializer"]]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file
diff --git a/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js
index 5120a68..e67bb06 100644
--- a/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js
+++ b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl RefUnwindSafe for Error",1,["cbor_smol::error::Error"]],["impl<'a> RefUnwindSafe for SliceWriter<'a>",1,["cbor_smol::ser::SliceWriter"]],["impl<'de> RefUnwindSafe for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> RefUnwindSafe for Serializer<W>where\n W: RefUnwindSafe,",1,["cbor_smol::ser::Serializer"]]]
+"cbor_smol":[["impl RefUnwindSafe for Error",1,["cbor_smol::error::Error"]],["impl<'de> RefUnwindSafe for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> RefUnwindSafe for Serializer<W>where\n W: RefUnwindSafe,",1,["cbor_smol::ser::Serializer"]]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file
diff --git a/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js
index f5d83c5..9c0e5ba 100644
--- a/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js
+++ b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js
@@ -1,3 +1,3 @@
(function() {var implementors = {
-"cbor_smol":[["impl UnwindSafe for Error",1,["cbor_smol::error::Error"]],["impl<'a> !UnwindSafe for SliceWriter<'a>",1,["cbor_smol::ser::SliceWriter"]],["impl<'de> UnwindSafe for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> UnwindSafe for Serializer<W>where\n W: UnwindSafe,",1,["cbor_smol::ser::Serializer"]]]
+"cbor_smol":[["impl UnwindSafe for Error",1,["cbor_smol::error::Error"]],["impl<'de> UnwindSafe for Deserializer<'de>",1,["cbor_smol::de::Deserializer"]],["impl<W> UnwindSafe for Serializer<W>where\n W: UnwindSafe,",1,["cbor_smol::ser::Serializer"]]]
};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
\ No newline at end of file