Skip to content
Myr

impls.rs

This file

Path

serde_core/src/de/impls.rs

3,173 lines · 94.9 KiB · Rust

Last changed by

Resolve mut_mut pedantic clippy lintDavid Tolnaybefore adoptioncfe6692

History of this file

Take it

Merge pull request #2608 from osiewicz/extract_serde_coreDavid Tolnaybefore adoption723fcac

lines 1–6why, one step back
1use crate::lib::*;
23use crate::de::{4 Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, Unexpected, VariantAccess,5 Visitor,6};

Merge pull request #2969 from dtolnay/coreprivateDavid Tolnaybefore adoption0990d97

line 7why, one step back
7use crate::private::{self, InPlaceSeed};

Merge pull request #2608 from osiewicz/extract_serde_coreDavid Tolnaybefore adoption723fcac

lines 8–9why, one step back
8
9#[cfg(any(feature = "std", feature = "alloc"))]

Merge pull request #2969 from dtolnay/coreprivateDavid Tolnaybefore adoption0990d97

line 10why, one step back
10use crate::private::size_hint;

Merge pull request #2608 from osiewicz/extract_serde_coreDavid Tolnaybefore adoption723fcac

lines 11–1049why, one step back
11
12////////////////////////////////////////////////////////////////////////////////1314struct UnitVisitor;1516impl<'de> Visitor<'de> for UnitVisitor {17 type Value = ();1819 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {20 formatter.write_str("unit")21 }2223 fn visit_unit<E>(self) -> Result<Self::Value, E>24 where25 E: Error,26 {27 Ok(())28 }29}3031impl<'de> Deserialize<'de> for () {32 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>33 where34 D: Deserializer<'de>,35 {36 deserializer.deserialize_unit(UnitVisitor)37 }38}3940#[cfg(feature = "unstable")]41#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]42impl<'de> Deserialize<'de> for ! {43 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>44 where45 D: Deserializer<'de>,46 {47 Err(Error::custom("cannot deserialize `!`"))48 }49}5051////////////////////////////////////////////////////////////////////////////////5253struct BoolVisitor;5455impl<'de> Visitor<'de> for BoolVisitor {56 type Value = bool;5758 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {59 formatter.write_str("a boolean")60 }6162 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>63 where64 E: Error,65 {66 Ok(v)67 }68}6970impl<'de> Deserialize<'de> for bool {71 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>72 where73 D: Deserializer<'de>,74 {75 deserializer.deserialize_bool(BoolVisitor)76 }77}7879////////////////////////////////////////////////////////////////////////////////8081macro_rules! impl_deserialize_num {82 ($primitive:ident, $nonzero:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => {83 impl_deserialize_num!($primitive, $deserialize $($method!($($val : $visit)*);)*);8485 impl<'de> Deserialize<'de> for num::$nonzero {86 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>87 where88 D: Deserializer<'de>,89 {90 struct NonZeroVisitor;9192 impl<'de> Visitor<'de> for NonZeroVisitor {93 type Value = num::$nonzero;9495 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {96 formatter.write_str(concat!("a nonzero ", stringify!($primitive)))97 }9899 $($($method!(nonzero $primitive $val : $visit);)*)*100 }101102 deserializer.$deserialize(NonZeroVisitor)103 }104 }105106 #[cfg(not(no_core_num_saturating))]107 impl<'de> Deserialize<'de> for Saturating<$primitive> {108 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>109 where110 D: Deserializer<'de>,111 {112 struct SaturatingVisitor;113114 impl<'de> Visitor<'de> for SaturatingVisitor {115 type Value = Saturating<$primitive>;116117 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {118 formatter.write_str("integer with support for saturating semantics")119 }120121 $($($method!(saturating $primitive $val : $visit);)*)*122 }123124 deserializer.$deserialize(SaturatingVisitor)125 }126 }127 };128129 ($primitive:ident, $deserialize:ident $($method:ident!($($val:ident : $visit:ident)*);)*) => {130 impl<'de> Deserialize<'de> for $primitive {131 #[inline]132 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>133 where134 D: Deserializer<'de>,135 {136 struct PrimitiveVisitor;137138 impl<'de> Visitor<'de> for PrimitiveVisitor {139 type Value = $primitive;140141 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {142 formatter.write_str(stringify!($primitive))143 }144145 $($($method!($val : $visit);)*)*146 }147148 deserializer.$deserialize(PrimitiveVisitor)149 }150 }151 };152}153154macro_rules! num_self {155 ($ty:ident : $visit:ident) => {156 #[inline]157 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>158 where159 E: Error,160 {161 Ok(v)162 }163 };164165 (nonzero $primitive:ident $ty:ident : $visit:ident) => {166 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>167 where168 E: Error,169 {170 if let Some(nonzero) = Self::Value::new(v) {171 Ok(nonzero)172 } else {173 Err(Error::invalid_value(Unexpected::Unsigned(0), &self))174 }175 }176 };177178 (saturating $primitive:ident $ty:ident : $visit:ident) => {179 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>180 where181 E: Error,182 {183 Ok(Saturating(v))184 }185 };186}187188macro_rules! num_as_self {189 ($ty:ident : $visit:ident) => {190 #[inline]191 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>192 where193 E: Error,194 {195 Ok(v as Self::Value)196 }197 };198199 (nonzero $primitive:ident $ty:ident : $visit:ident) => {200 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>201 where202 E: Error,203 {204 if let Some(nonzero) = Self::Value::new(v as $primitive) {205 Ok(nonzero)206 } else {207 Err(Error::invalid_value(Unexpected::Unsigned(0), &self))208 }209 }210 };211212 (saturating $primitive:ident $ty:ident : $visit:ident) => {213 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>214 where215 E: Error,216 {217 Ok(Saturating(v as $primitive))218 }219 };220}221222macro_rules! num_as_copysign_self {223 ($ty:ident : $visit:ident) => {224 #[inline]225 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>226 where227 E: Error,228 {229 #[cfg(not(feature = "std"))]230 {231 Ok(v as Self::Value)232 }233234 #[cfg(feature = "std")]235 {236 // Preserve sign of NaN. The `as` produces a nondeterministic sign.237 let sign = if v.is_sign_positive() { 1.0 } else { -1.0 };238 Ok((v as Self::Value).copysign(sign))239 }240 }241 };242}243244macro_rules! int_to_int {245 ($ty:ident : $visit:ident) => {246 #[inline]247 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>248 where249 E: Error,250 {251 Self::Value::try_from(v as i64)252 .map_err(|_| Error::invalid_value(Unexpected::Signed(v as i64), &self))253 }254 };255256 (nonzero $primitive:ident $ty:ident : $visit:ident) => {257 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>258 where259 E: Error,260 {261 if let Ok(v) = $primitive::try_from(v as i64) {262 if let Some(nonzero) = Self::Value::new(v) {263 return Ok(nonzero);264 }265 }266 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))267 }268 };269270 (saturating $primitive:ident $ty:ident : $visit:ident) => {271 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>272 where273 E: Error,274 {275 if (v as i64) < $primitive::MIN as i64 {276 Ok(Saturating($primitive::MIN))277 } else if ($primitive::MAX as i64) < v as i64 {278 Ok(Saturating($primitive::MAX))279 } else {280 Ok(Saturating(v as $primitive))281 }282 }283 };284}285286macro_rules! int_to_uint {287 ($ty:ident : $visit:ident) => {288 #[inline]289 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>290 where291 E: Error,292 {293 if 0 <= v {294 #[allow(irrefutable_let_patterns)]295 if let Ok(v) = Self::Value::try_from(v as u64) {296 return Ok(v as Self::Value);297 }298 }299 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))300 }301 };302303 (nonzero $primitive:ident $ty:ident : $visit:ident) => {304 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>305 where306 E: Error,307 {308 if 0 < v {309 #[allow(irrefutable_let_patterns)]310 if let Ok(v) = $primitive::try_from(v as u64) {311 if let Some(nonzero) = Self::Value::new(v) {312 return Ok(nonzero);313 }314 }315 }316 Err(Error::invalid_value(Unexpected::Signed(v as i64), &self))317 }318 };319320 (saturating $primitive:ident $ty:ident : $visit:ident) => {321 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>322 where323 E: Error,324 {325 if v < 0 {326 Ok(Saturating(0))327 } else if ($primitive::MAX as u64) < v as u64 {328 Ok(Saturating($primitive::MAX))329 } else {330 Ok(Saturating(v as $primitive))331 }332 }333 };334}335336macro_rules! uint_to_self {337 ($ty:ident : $visit:ident) => {338 #[inline]339 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>340 where341 E: Error,342 {343 Self::Value::try_from(v as u64)344 .map_err(|_| Error::invalid_value(Unexpected::Unsigned(v as u64), &self))345 }346 };347348 (nonzero $primitive:ident $ty:ident : $visit:ident) => {349 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>350 where351 E: Error,352 {353 if let Ok(v) = $primitive::try_from(v as u64) {354 if let Some(nonzero) = Self::Value::new(v) {355 return Ok(nonzero);356 }357 }358 Err(Error::invalid_value(Unexpected::Unsigned(v as u64), &self))359 }360 };361362 (saturating $primitive:ident $ty:ident : $visit:ident) => {363 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>364 where365 E: Error,366 {367 if let Ok(v) = $primitive::try_from(v as u64) {368 Ok(Saturating(v as $primitive))369 } else {370 Ok(Saturating($primitive::MAX))371 }372 }373 };374}375376impl_deserialize_num! {377 i8, NonZeroI8, deserialize_i8378 num_self!(i8:visit_i8);379 int_to_int!(i16:visit_i16 i32:visit_i32 i64:visit_i64);380 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);381}382383impl_deserialize_num! {384 i16, NonZeroI16, deserialize_i16385 num_self!(i16:visit_i16);386 num_as_self!(i8:visit_i8);387 int_to_int!(i32:visit_i32 i64:visit_i64);388 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);389}390391impl_deserialize_num! {392 i32, NonZeroI32, deserialize_i32393 num_self!(i32:visit_i32);394 num_as_self!(i8:visit_i8 i16:visit_i16);395 int_to_int!(i64:visit_i64);396 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);397}398399impl_deserialize_num! {400 i64, NonZeroI64, deserialize_i64401 num_self!(i64:visit_i64);402 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32);403 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);404}405406impl_deserialize_num! {407 isize, NonZeroIsize, deserialize_i64408 num_as_self!(i8:visit_i8 i16:visit_i16);409 int_to_int!(i32:visit_i32 i64:visit_i64);410 uint_to_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);411}412413impl_deserialize_num! {414 u8, NonZeroU8, deserialize_u8415 num_self!(u8:visit_u8);416 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);417 uint_to_self!(u16:visit_u16 u32:visit_u32 u64:visit_u64);418}419420impl_deserialize_num! {421 u16, NonZeroU16, deserialize_u16422 num_self!(u16:visit_u16);423 num_as_self!(u8:visit_u8);424 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);425 uint_to_self!(u32:visit_u32 u64:visit_u64);426}427428impl_deserialize_num! {429 u32, NonZeroU32, deserialize_u32430 num_self!(u32:visit_u32);431 num_as_self!(u8:visit_u8 u16:visit_u16);432 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);433 uint_to_self!(u64:visit_u64);434}435436impl_deserialize_num! {437 u64, NonZeroU64, deserialize_u64438 num_self!(u64:visit_u64);439 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32);440 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);441}442443impl_deserialize_num! {444 usize, NonZeroUsize, deserialize_u64445 num_as_self!(u8:visit_u8 u16:visit_u16);446 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);447 uint_to_self!(u32:visit_u32 u64:visit_u64);448}449450impl_deserialize_num! {451 f32, deserialize_f32452 num_self!(f32:visit_f32);453 num_as_copysign_self!(f64:visit_f64);454 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);455 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);456}457458impl_deserialize_num! {459 f64, deserialize_f64460 num_self!(f64:visit_f64);461 num_as_copysign_self!(f32:visit_f32);462 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);463 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);464}465466macro_rules! num_128 {467 ($ty:ident : $visit:ident) => {468 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>469 where470 E: Error,471 {472 if v as i128 >= Self::Value::MIN as i128 && v as u128 <= Self::Value::MAX as u128 {473 Ok(v as Self::Value)474 } else {475 Err(Error::invalid_value(476 Unexpected::Other(stringify!($ty)),477 &self,478 ))479 }480 }481 };482483 (nonzero $primitive:ident $ty:ident : $visit:ident) => {484 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>485 where486 E: Error,487 {488 if v as i128 >= $primitive::MIN as i128 && v as u128 <= $primitive::MAX as u128 {489 if let Some(nonzero) = Self::Value::new(v as $primitive) {490 Ok(nonzero)491 } else {492 Err(Error::invalid_value(Unexpected::Unsigned(0), &self))493 }494 } else {495 Err(Error::invalid_value(496 Unexpected::Other(stringify!($ty)),497 &self,498 ))499 }500 }501 };502503 (saturating $primitive:ident $ty:ident : $visit:ident) => {504 fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>505 where506 E: Error,507 {508 if (v as i128) < $primitive::MIN as i128 {509 Ok(Saturating($primitive::MIN))510 } else if ($primitive::MAX as u128) < v as u128 {511 Ok(Saturating($primitive::MAX))512 } else {513 Ok(Saturating(v as $primitive))514 }515 }516 };517}518519impl_deserialize_num! {520 i128, NonZeroI128, deserialize_i128521 num_self!(i128:visit_i128);522 num_as_self!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);523 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);524 num_128!(u128:visit_u128);525}526527impl_deserialize_num! {528 u128, NonZeroU128, deserialize_u128529 num_self!(u128:visit_u128);530 num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);531 int_to_uint!(i8:visit_i8 i16:visit_i16 i32:visit_i32 i64:visit_i64);532 num_128!(i128:visit_i128);533}534535////////////////////////////////////////////////////////////////////////////////536537struct CharVisitor;538539impl<'de> Visitor<'de> for CharVisitor {540 type Value = char;541542 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {543 formatter.write_str("a character")544 }545546 #[inline]547 fn visit_char<E>(self, v: char) -> Result<Self::Value, E>548 where549 E: Error,550 {551 Ok(v)552 }553554 #[inline]555 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>556 where557 E: Error,558 {559 let mut iter = v.chars();560 match (iter.next(), iter.next()) {561 (Some(c), None) => Ok(c),562 _ => Err(Error::invalid_value(Unexpected::Str(v), &self)),563 }564 }565}566567impl<'de> Deserialize<'de> for char {568 #[inline]569 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>570 where571 D: Deserializer<'de>,572 {573 deserializer.deserialize_char(CharVisitor)574 }575}576577////////////////////////////////////////////////////////////////////////////////578579#[cfg(any(feature = "std", feature = "alloc"))]580struct StringVisitor;581#[cfg(any(feature = "std", feature = "alloc"))]582struct StringInPlaceVisitor<'a>(&'a mut String);583584#[cfg(any(feature = "std", feature = "alloc"))]585impl<'de> Visitor<'de> for StringVisitor {586 type Value = String;587588 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {589 formatter.write_str("a string")590 }591592 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>593 where594 E: Error,595 {596 Ok(v.to_owned())597 }598599 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>600 where601 E: Error,602 {603 Ok(v)604 }605606 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>607 where608 E: Error,609 {610 match str::from_utf8(v) {611 Ok(s) => Ok(s.to_owned()),612 Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),613 }614 }615616 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>617 where618 E: Error,619 {620 match String::from_utf8(v) {621 Ok(s) => Ok(s),622 Err(e) => Err(Error::invalid_value(623 Unexpected::Bytes(&e.into_bytes()),624 &self,625 )),626 }627 }628}629630#[cfg(any(feature = "std", feature = "alloc"))]631impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> {632 type Value = ();633634 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {635 formatter.write_str("a string")636 }637638 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>639 where640 E: Error,641 {642 self.0.clear();643 self.0.push_str(v);644 Ok(())645 }646647 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>648 where649 E: Error,650 {651 *self.0 = v;652 Ok(())653 }654655 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>656 where657 E: Error,658 {659 match str::from_utf8(v) {660 Ok(s) => {661 self.0.clear();662 self.0.push_str(s);663 Ok(())664 }665 Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),666 }667 }668669 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>670 where671 E: Error,672 {673 match String::from_utf8(v) {674 Ok(s) => {675 *self.0 = s;676 Ok(())677 }678 Err(e) => Err(Error::invalid_value(679 Unexpected::Bytes(&e.into_bytes()),680 &self,681 )),682 }683 }684}685686#[cfg(any(feature = "std", feature = "alloc"))]687#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]688impl<'de> Deserialize<'de> for String {689 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>690 where691 D: Deserializer<'de>,692 {693 deserializer.deserialize_string(StringVisitor)694 }695696 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>697 where698 D: Deserializer<'de>,699 {700 deserializer.deserialize_string(StringInPlaceVisitor(place))701 }702}703704////////////////////////////////////////////////////////////////////////////////705706struct StrVisitor;707708impl<'a> Visitor<'a> for StrVisitor {709 type Value = &'a str;710711 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {712 formatter.write_str("a borrowed string")713 }714715 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>716 where717 E: Error,718 {719 Ok(v) // so easy720 }721722 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>723 where724 E: Error,725 {726 str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))727 }728}729730impl<'de: 'a, 'a> Deserialize<'de> for &'a str {731 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>732 where733 D: Deserializer<'de>,734 {735 deserializer.deserialize_str(StrVisitor)736 }737}738739////////////////////////////////////////////////////////////////////////////////740741struct BytesVisitor;742743impl<'a> Visitor<'a> for BytesVisitor {744 type Value = &'a [u8];745746 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {747 formatter.write_str("a borrowed byte array")748 }749750 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>751 where752 E: Error,753 {754 Ok(v)755 }756757 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>758 where759 E: Error,760 {761 Ok(v.as_bytes())762 }763}764765impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {766 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>767 where768 D: Deserializer<'de>,769 {770 deserializer.deserialize_bytes(BytesVisitor)771 }772}773774////////////////////////////////////////////////////////////////////////////////775776#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]777struct CStringVisitor;778779#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]780impl<'de> Visitor<'de> for CStringVisitor {781 type Value = CString;782783 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {784 formatter.write_str("byte array")785 }786787 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>788 where789 A: SeqAccess<'de>,790 {791 let capacity = size_hint::cautious::<u8>(seq.size_hint());792 let mut values = Vec::<u8>::with_capacity(capacity);793794 while let Some(value) = tri!(seq.next_element()) {795 values.push(value);796 }797798 CString::new(values).map_err(Error::custom)799 }800801 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>802 where803 E: Error,804 {805 CString::new(v).map_err(Error::custom)806 }807808 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>809 where810 E: Error,811 {812 CString::new(v).map_err(Error::custom)813 }814815 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>816 where817 E: Error,818 {819 CString::new(v).map_err(Error::custom)820 }821822 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>823 where824 E: Error,825 {826 CString::new(v).map_err(Error::custom)827 }828}829830#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]831#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]832impl<'de> Deserialize<'de> for CString {833 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>834 where835 D: Deserializer<'de>,836 {837 deserializer.deserialize_byte_buf(CStringVisitor)838 }839}840841macro_rules! forwarded_impl {842 (843 $(#[$attr:meta])*844 ($($id:ident),*), $ty:ty, $func:expr845 ) => {846 $(#[$attr])*847 impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {848 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>849 where850 D: Deserializer<'de>,851 {852 Deserialize::deserialize(deserializer).map($func)853 }854 }855 }856}857858forwarded_impl! {859 #[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]860 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]861 (), Box<CStr>, CString::into_boxed_c_str862}863864forwarded_impl! {865 (T), Reverse<T>, Reverse866}867868////////////////////////////////////////////////////////////////////////////////869870struct OptionVisitor<T> {871 marker: PhantomData<T>,872}873874impl<'de, T> Visitor<'de> for OptionVisitor<T>875where876 T: Deserialize<'de>,877{878 type Value = Option<T>;879880 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {881 formatter.write_str("option")882 }883884 #[inline]885 fn visit_unit<E>(self) -> Result<Self::Value, E>886 where887 E: Error,888 {889 Ok(None)890 }891892 #[inline]893 fn visit_none<E>(self) -> Result<Self::Value, E>894 where895 E: Error,896 {897 Ok(None)898 }899900 #[inline]901 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>902 where903 D: Deserializer<'de>,904 {905 T::deserialize(deserializer).map(Some)906 }907908 fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()>909 where910 D: Deserializer<'de>,911 {912 Ok(T::deserialize(deserializer).ok())913 }914}915916impl<'de, T> Deserialize<'de> for Option<T>917where918 T: Deserialize<'de>,919{920 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>921 where922 D: Deserializer<'de>,923 {924 deserializer.deserialize_option(OptionVisitor {925 marker: PhantomData,926 })927 }928929 // The Some variant's repr is opaque, so we can't play cute tricks with its930 // tag to have deserialize_in_place build the content in place unconditionally.931 //932 // FIXME: investigate whether branching on the old value being Some to933 // deserialize_in_place the value is profitable (probably data-dependent?)934}935936////////////////////////////////////////////////////////////////////////////////937938struct PhantomDataVisitor<T: ?Sized> {939 marker: PhantomData<T>,940}941942impl<'de, T> Visitor<'de> for PhantomDataVisitor<T>943where944 T: ?Sized,945{946 type Value = PhantomData<T>;947948 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {949 formatter.write_str("unit")950 }951952 #[inline]953 fn visit_unit<E>(self) -> Result<Self::Value, E>954 where955 E: Error,956 {957 Ok(PhantomData)958 }959}960961impl<'de, T> Deserialize<'de> for PhantomData<T>962where963 T: ?Sized,964{965 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>966 where967 D: Deserializer<'de>,968 {969 let visitor = PhantomDataVisitor {970 marker: PhantomData,971 };972 deserializer.deserialize_unit_struct("PhantomData", visitor)973 }974}975976////////////////////////////////////////////////////////////////////////////////977978macro_rules! seq_impl {979 (980 $(#[$attr:meta])*981 $ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>,982 $access:ident,983 $clear:expr,984 $with_capacity:expr,985 $reserve:expr,986 $insert:expr987 ) => {988 $(#[$attr])*989 impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty<T $(, $typaram)*>990 where991 T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,992 $($typaram: $bound1 $(+ $bound2)*,)*993 {994 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>995 where996 D: Deserializer<'de>,997 {998 struct SeqVisitor<T $(, $typaram)*> {999 marker: PhantomData<$ty<T $(, $typaram)*>>,1000 }10011002 impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor<T $(, $typaram)*>1003 where1004 T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,1005 $($typaram: $bound1 $(+ $bound2)*,)*1006 {1007 type Value = $ty<T $(, $typaram)*>;10081009 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1010 formatter.write_str("a sequence")1011 }10121013 #[inline]1014 fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error>1015 where1016 A: SeqAccess<'de>,1017 {1018 let mut values = $with_capacity;10191020 while let Some(value) = tri!($access.next_element()) {1021 $insert(&mut values, value);1022 }10231024 Ok(values)1025 }1026 }10271028 let visitor = SeqVisitor { marker: PhantomData };1029 deserializer.deserialize_seq(visitor)1030 }10311032 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>1033 where1034 D: Deserializer<'de>,1035 {1036 struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty<T $(, $typaram)*>);10371038 impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*>1039 where1040 T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*,1041 $($typaram: $bound1 $(+ $bound2)*,)*1042 {1043 type Value = ();10441045 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1046 formatter.write_str("a sequence")1047 }10481049 #[inline]

Resolve mut_mut pedantic clippy lintDavid Tolnaybefore adoptioncfe6692

line 1050why, one step back
1050 fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error>

Merge pull request #2608 from osiewicz/extract_serde_coreDavid Tolnaybefore adoption723fcac

lines 1051–1053why, one step back
1051 where
1052 A: SeqAccess<'de>,1053 {

Resolve mut_mut pedantic clippy lintDavid Tolnaybefore adoptioncfe6692

lines 1054–1055why, one step back
1054 $clear(&mut *self.0);
1055 $reserve(&mut *self.0, size_hint::cautious::<T>($access.size_hint()));

Merge pull request #2608 from osiewicz/extract_serde_coreDavid Tolnaybefore adoption723fcac

lines 1056–1058why, one step back
1056
1057 // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList)1058 while let Some(value) = tri!($access.next_element()) {

Resolve mut_mut pedantic clippy lintDavid Tolnaybefore adoptioncfe6692

line 1059why, one step back
1059 $insert(&mut *self.0, value);

Merge pull request #2608 from osiewicz/extract_serde_coreDavid Tolnaybefore adoption723fcac

lines 1060–2175why, one step back
1060 }
10611062 Ok(())1063 }1064 }10651066 deserializer.deserialize_seq(SeqInPlaceVisitor(place))1067 }1068 }1069 }1070}10711072// Dummy impl of reserve1073#[cfg(any(feature = "std", feature = "alloc"))]1074fn nop_reserve<T>(_seq: T, _n: usize) {}10751076seq_impl!(1077 #[cfg(any(feature = "std", feature = "alloc"))]1078 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1079 BinaryHeap<T: Ord>,1080 seq,1081 BinaryHeap::clear,1082 BinaryHeap::with_capacity(size_hint::cautious::<T>(seq.size_hint())),1083 BinaryHeap::reserve,1084 BinaryHeap::push1085);10861087seq_impl!(1088 #[cfg(any(feature = "std", feature = "alloc"))]1089 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1090 BTreeSet<T: Eq + Ord>,1091 seq,1092 BTreeSet::clear,1093 BTreeSet::new(),1094 nop_reserve,1095 BTreeSet::insert1096);10971098seq_impl!(1099 #[cfg(any(feature = "std", feature = "alloc"))]1100 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1101 LinkedList<T>,1102 seq,1103 LinkedList::clear,1104 LinkedList::new(),1105 nop_reserve,1106 LinkedList::push_back1107);11081109seq_impl!(1110 #[cfg(feature = "std")]1111 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]1112 HashSet<T: Eq + Hash, S: BuildHasher + Default>,1113 seq,1114 HashSet::clear,1115 HashSet::with_capacity_and_hasher(size_hint::cautious::<T>(seq.size_hint()), S::default()),1116 HashSet::reserve,1117 HashSet::insert1118);11191120seq_impl!(1121 #[cfg(any(feature = "std", feature = "alloc"))]1122 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1123 VecDeque<T>,1124 seq,1125 VecDeque::clear,1126 VecDeque::with_capacity(size_hint::cautious::<T>(seq.size_hint())),1127 VecDeque::reserve,1128 VecDeque::push_back1129);11301131////////////////////////////////////////////////////////////////////////////////11321133#[cfg(any(feature = "std", feature = "alloc"))]1134#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1135impl<'de, T> Deserialize<'de> for Vec<T>1136where1137 T: Deserialize<'de>,1138{1139 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1140 where1141 D: Deserializer<'de>,1142 {1143 struct VecVisitor<T> {1144 marker: PhantomData<T>,1145 }11461147 impl<'de, T> Visitor<'de> for VecVisitor<T>1148 where1149 T: Deserialize<'de>,1150 {1151 type Value = Vec<T>;11521153 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1154 formatter.write_str("a sequence")1155 }11561157 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>1158 where1159 A: SeqAccess<'de>,1160 {1161 let capacity = size_hint::cautious::<T>(seq.size_hint());1162 let mut values = Vec::<T>::with_capacity(capacity);11631164 while let Some(value) = tri!(seq.next_element()) {1165 values.push(value);1166 }11671168 Ok(values)1169 }1170 }11711172 let visitor = VecVisitor {1173 marker: PhantomData,1174 };1175 deserializer.deserialize_seq(visitor)1176 }11771178 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>1179 where1180 D: Deserializer<'de>,1181 {1182 struct VecInPlaceVisitor<'a, T: 'a>(&'a mut Vec<T>);11831184 impl<'a, 'de, T> Visitor<'de> for VecInPlaceVisitor<'a, T>1185 where1186 T: Deserialize<'de>,1187 {1188 type Value = ();11891190 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1191 formatter.write_str("a sequence")1192 }11931194 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>1195 where1196 A: SeqAccess<'de>,1197 {1198 let hint = size_hint::cautious::<T>(seq.size_hint());1199 if let Some(additional) = hint.checked_sub(self.0.len()) {1200 self.0.reserve(additional);1201 }12021203 for i in 0..self.0.len() {1204 let next = {1205 let next_place = InPlaceSeed(&mut self.0[i]);1206 tri!(seq.next_element_seed(next_place))1207 };1208 if next.is_none() {1209 self.0.truncate(i);1210 return Ok(());1211 }1212 }12131214 while let Some(value) = tri!(seq.next_element()) {1215 self.0.push(value);1216 }12171218 Ok(())1219 }1220 }12211222 deserializer.deserialize_seq(VecInPlaceVisitor(place))1223 }1224}12251226////////////////////////////////////////////////////////////////////////////////12271228struct ArrayVisitor<A> {1229 marker: PhantomData<A>,1230}1231struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A);12321233impl<A> ArrayVisitor<A> {1234 fn new() -> Self {1235 ArrayVisitor {1236 marker: PhantomData,1237 }1238 }1239}12401241impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> {1242 type Value = [T; 0];12431244 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1245 formatter.write_str("an empty array")1246 }12471248 #[inline]1249 fn visit_seq<A>(self, _: A) -> Result<Self::Value, A::Error>1250 where1251 A: SeqAccess<'de>,1252 {1253 Ok([])1254 }1255}12561257// Does not require T: Deserialize<'de>.1258impl<'de, T> Deserialize<'de> for [T; 0] {1259 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1260 where1261 D: Deserializer<'de>,1262 {1263 deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new())1264 }1265}12661267macro_rules! array_impls {1268 ($($len:expr => ($($n:tt)+))+) => {1269 $(1270 impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]>1271 where1272 T: Deserialize<'de>,1273 {1274 type Value = [T; $len];12751276 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1277 formatter.write_str(concat!("an array of length ", $len))1278 }12791280 #[inline]1281 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>1282 where1283 A: SeqAccess<'de>,1284 {1285 Ok([$(1286 match tri!(seq.next_element()) {1287 Some(val) => val,1288 None => return Err(Error::invalid_length($n, &self)),1289 }1290 ),+])1291 }1292 }12931294 impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]>1295 where1296 T: Deserialize<'de>,1297 {1298 type Value = ();12991300 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1301 formatter.write_str(concat!("an array of length ", $len))1302 }13031304 #[inline]1305 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>1306 where1307 A: SeqAccess<'de>,1308 {1309 let mut fail_idx = None;1310 for (idx, dest) in self.0[..].iter_mut().enumerate() {1311 if tri!(seq.next_element_seed(InPlaceSeed(dest))).is_none() {1312 fail_idx = Some(idx);1313 break;1314 }1315 }1316 if let Some(idx) = fail_idx {1317 return Err(Error::invalid_length(idx, &self));1318 }1319 Ok(())1320 }1321 }13221323 impl<'de, T> Deserialize<'de> for [T; $len]1324 where1325 T: Deserialize<'de>,1326 {1327 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1328 where1329 D: Deserializer<'de>,1330 {1331 deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new())1332 }13331334 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>1335 where1336 D: Deserializer<'de>,1337 {1338 deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place))1339 }1340 }1341 )+1342 }1343}13441345array_impls! {1346 1 => (0)1347 2 => (0 1)1348 3 => (0 1 2)1349 4 => (0 1 2 3)1350 5 => (0 1 2 3 4)1351 6 => (0 1 2 3 4 5)1352 7 => (0 1 2 3 4 5 6)1353 8 => (0 1 2 3 4 5 6 7)1354 9 => (0 1 2 3 4 5 6 7 8)1355 10 => (0 1 2 3 4 5 6 7 8 9)1356 11 => (0 1 2 3 4 5 6 7 8 9 10)1357 12 => (0 1 2 3 4 5 6 7 8 9 10 11)1358 13 => (0 1 2 3 4 5 6 7 8 9 10 11 12)1359 14 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13)1360 15 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)1361 16 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)1362 17 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)1363 18 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17)1364 19 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18)1365 20 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)1366 21 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)1367 22 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21)1368 23 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22)1369 24 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23)1370 25 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)1371 26 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25)1372 27 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26)1373 28 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27)1374 29 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28)1375 30 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29)1376 31 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30)1377 32 => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31)1378}13791380////////////////////////////////////////////////////////////////////////////////13811382macro_rules! tuple_impls {1383 ($($len:tt => ($($n:tt $name:ident)+))+) => {1384 $(1385 #[cfg_attr(docsrs, doc(hidden))]1386 impl<'de, $($name),+> Deserialize<'de> for ($($name,)+)1387 where1388 $($name: Deserialize<'de>,)+1389 {1390 tuple_impl_body!($len => ($($n $name)+));1391 }1392 )+1393 };1394}13951396macro_rules! tuple_impl_body {1397 ($len:tt => ($($n:tt $name:ident)+)) => {1398 #[inline]1399 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1400 where1401 D: Deserializer<'de>,1402 {1403 struct TupleVisitor<$($name,)+> {1404 marker: PhantomData<($($name,)+)>,1405 }14061407 impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> {1408 type Value = ($($name,)+);14091410 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1411 formatter.write_str(concat!("a tuple of size ", $len))1412 }14131414 #[inline]1415 #[allow(non_snake_case)]1416 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>1417 where1418 A: SeqAccess<'de>,1419 {1420 $(1421 let $name = match tri!(seq.next_element()) {1422 Some(value) => value,1423 None => return Err(Error::invalid_length($n, &self)),1424 };1425 )+14261427 Ok(($($name,)+))1428 }1429 }14301431 deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData })1432 }14331434 #[inline]1435 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>1436 where1437 D: Deserializer<'de>,1438 {1439 struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+));14401441 impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> {1442 type Value = ();14431444 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1445 formatter.write_str(concat!("a tuple of size ", $len))1446 }14471448 #[inline]1449 #[allow(non_snake_case)]1450 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>1451 where1452 A: SeqAccess<'de>,1453 {1454 $(1455 if tri!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() {1456 return Err(Error::invalid_length($n, &self));1457 }1458 )+14591460 Ok(())1461 }1462 }14631464 deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place))1465 }1466 };1467}14681469#[cfg_attr(docsrs, doc(fake_variadic))]1470#[cfg_attr(1471 docsrs,1472 doc = "This trait is implemented for tuples up to 16 items long."1473)]1474impl<'de, T> Deserialize<'de> for (T,)1475where1476 T: Deserialize<'de>,1477{1478 tuple_impl_body!(1 => (0 T));1479}14801481tuple_impls! {1482 2 => (0 T0 1 T1)1483 3 => (0 T0 1 T1 2 T2)1484 4 => (0 T0 1 T1 2 T2 3 T3)1485 5 => (0 T0 1 T1 2 T2 3 T3 4 T4)1486 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)1487 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)1488 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)1489 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)1490 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)1491 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)1492 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)1493 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)1494 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)1495 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)1496 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)1497}14981499////////////////////////////////////////////////////////////////////////////////15001501macro_rules! map_impl {1502 (1503 $(#[$attr:meta])*1504 $ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>,1505 $access:ident,1506 $with_capacity:expr,1507 ) => {1508 $(#[$attr])*1509 impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty<K, V $(, $typaram)*>1510 where1511 K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,1512 V: Deserialize<'de>,1513 $($typaram: $bound1 $(+ $bound2)*),*1514 {1515 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1516 where1517 D: Deserializer<'de>,1518 {1519 struct MapVisitor<K, V $(, $typaram)*> {1520 marker: PhantomData<$ty<K, V $(, $typaram)*>>,1521 }15221523 impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor<K, V $(, $typaram)*>1524 where1525 K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*,1526 V: Deserialize<'de>,1527 $($typaram: $bound1 $(+ $bound2)*),*1528 {1529 type Value = $ty<K, V $(, $typaram)*>;15301531 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1532 formatter.write_str("a map")1533 }15341535 #[inline]1536 fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error>1537 where1538 A: MapAccess<'de>,1539 {1540 let mut values = $with_capacity;15411542 while let Some((key, value)) = tri!($access.next_entry()) {1543 values.insert(key, value);1544 }15451546 Ok(values)1547 }1548 }15491550 let visitor = MapVisitor { marker: PhantomData };1551 deserializer.deserialize_map(visitor)1552 }1553 }1554 }1555}15561557map_impl! {1558 #[cfg(any(feature = "std", feature = "alloc"))]1559 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1560 BTreeMap<K: Ord, V>,1561 map,1562 BTreeMap::new(),1563}15641565map_impl! {1566 #[cfg(feature = "std")]1567 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]1568 HashMap<K: Eq + Hash, V, S: BuildHasher + Default>,1569 map,1570 HashMap::with_capacity_and_hasher(size_hint::cautious::<(K, V)>(map.size_hint()), S::default()),1571}15721573////////////////////////////////////////////////////////////////////////////////15741575#[cfg(any(feature = "std", not(no_core_net)))]1576macro_rules! parse_ip_impl {1577 ($ty:ty, $expecting:expr, $size:tt) => {1578 impl<'de> Deserialize<'de> for $ty {1579 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1580 where1581 D: Deserializer<'de>,1582 {1583 if deserializer.is_human_readable() {1584 deserializer.deserialize_str(FromStrVisitor::new($expecting))1585 } else {1586 <[u8; $size]>::deserialize(deserializer).map(<$ty>::from)1587 }1588 }1589 }1590 };1591}15921593#[cfg(any(feature = "std", not(no_core_net)))]1594macro_rules! variant_identifier {1595 (1596 $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)1597 $expecting_message:expr,1598 $variants_name:ident1599 ) => {1600 enum $name_kind {1601 $($variant),*1602 }16031604 static $variants_name: &[&str] = &[$(stringify!($variant)),*];16051606 impl<'de> Deserialize<'de> for $name_kind {1607 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1608 where1609 D: Deserializer<'de>,1610 {1611 struct KindVisitor;16121613 impl<'de> Visitor<'de> for KindVisitor {1614 type Value = $name_kind;16151616 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1617 formatter.write_str($expecting_message)1618 }16191620 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>1621 where1622 E: Error,1623 {1624 match value {1625 $(1626 $index => Ok($name_kind :: $variant),1627 )*1628 _ => Err(Error::invalid_value(Unexpected::Unsigned(value), &self),),1629 }1630 }16311632 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>1633 where1634 E: Error,1635 {1636 match value {1637 $(1638 stringify!($variant) => Ok($name_kind :: $variant),1639 )*1640 _ => Err(Error::unknown_variant(value, $variants_name)),1641 }1642 }16431644 fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>1645 where1646 E: Error,1647 {1648 match value {1649 $(1650 $bytes => Ok($name_kind :: $variant),1651 )*1652 _ => {1653 match str::from_utf8(value) {1654 Ok(value) => Err(Error::unknown_variant(value, $variants_name)),1655 Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),1656 }1657 }1658 }1659 }1660 }16611662 deserializer.deserialize_identifier(KindVisitor)1663 }1664 }1665 }1666}16671668#[cfg(any(feature = "std", not(no_core_net)))]1669macro_rules! deserialize_enum {1670 (1671 $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)1672 $expecting_message:expr,1673 $deserializer:expr1674 ) => {1675 variant_identifier! {1676 $name_kind ($($variant; $bytes; $index),*)1677 $expecting_message,1678 VARIANTS1679 }16801681 struct EnumVisitor;1682 impl<'de> Visitor<'de> for EnumVisitor {1683 type Value = $name;16841685 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1686 formatter.write_str(concat!("a ", stringify!($name)))1687 }168816891690 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>1691 where1692 A: EnumAccess<'de>,1693 {1694 match tri!(data.variant()) {1695 $(1696 ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),1697 )*1698 }1699 }1700 }1701 $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)1702 }1703}17041705#[cfg(any(feature = "std", not(no_core_net)))]1706impl<'de> Deserialize<'de> for net::IpAddr {1707 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1708 where1709 D: Deserializer<'de>,1710 {1711 if deserializer.is_human_readable() {1712 deserializer.deserialize_str(FromStrVisitor::new("IP address"))1713 } else {1714 use crate::lib::net::IpAddr;1715 deserialize_enum! {1716 IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)1717 "`V4` or `V6`",1718 deserializer1719 }1720 }1721 }1722}17231724#[cfg(any(feature = "std", not(no_core_net)))]1725parse_ip_impl!(net::Ipv4Addr, "IPv4 address", 4);17261727#[cfg(any(feature = "std", not(no_core_net)))]1728parse_ip_impl!(net::Ipv6Addr, "IPv6 address", 16);17291730#[cfg(any(feature = "std", not(no_core_net)))]1731macro_rules! parse_socket_impl {1732 (1733 $ty:ty, $expecting:tt,1734 $new:expr,1735 ) => {1736 impl<'de> Deserialize<'de> for $ty {1737 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1738 where1739 D: Deserializer<'de>,1740 {1741 if deserializer.is_human_readable() {1742 deserializer.deserialize_str(FromStrVisitor::new($expecting))1743 } else {1744 <(_, u16)>::deserialize(deserializer).map($new)1745 }1746 }1747 }1748 };1749}17501751#[cfg(any(feature = "std", not(no_core_net)))]1752impl<'de> Deserialize<'de> for net::SocketAddr {1753 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1754 where1755 D: Deserializer<'de>,1756 {1757 if deserializer.is_human_readable() {1758 deserializer.deserialize_str(FromStrVisitor::new("socket address"))1759 } else {1760 use crate::lib::net::SocketAddr;1761 deserialize_enum! {1762 SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)1763 "`V4` or `V6`",1764 deserializer1765 }1766 }1767 }1768}17691770#[cfg(any(feature = "std", not(no_core_net)))]1771parse_socket_impl! {1772 net::SocketAddrV4, "IPv4 socket address",1773 |(ip, port)| net::SocketAddrV4::new(ip, port),1774}17751776#[cfg(any(feature = "std", not(no_core_net)))]1777parse_socket_impl! {1778 net::SocketAddrV6, "IPv6 socket address",1779 |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0),1780}17811782////////////////////////////////////////////////////////////////////////////////17831784#[cfg(feature = "std")]1785struct PathVisitor;17861787#[cfg(feature = "std")]1788impl<'a> Visitor<'a> for PathVisitor {1789 type Value = &'a Path;17901791 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1792 formatter.write_str("a borrowed path")1793 }17941795 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>1796 where1797 E: Error,1798 {1799 Ok(v.as_ref())1800 }18011802 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>1803 where1804 E: Error,1805 {1806 str::from_utf8(v)1807 .map(AsRef::as_ref)1808 .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))1809 }1810}18111812#[cfg(feature = "std")]1813#[cfg_attr(docsrs, doc(cfg(feature = "std")))]1814impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {1815 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1816 where1817 D: Deserializer<'de>,1818 {1819 deserializer.deserialize_str(PathVisitor)1820 }1821}18221823#[cfg(feature = "std")]1824struct PathBufVisitor;18251826#[cfg(feature = "std")]1827impl<'de> Visitor<'de> for PathBufVisitor {1828 type Value = PathBuf;18291830 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1831 formatter.write_str("path string")1832 }18331834 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>1835 where1836 E: Error,1837 {1838 Ok(From::from(v))1839 }18401841 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>1842 where1843 E: Error,1844 {1845 Ok(From::from(v))1846 }18471848 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>1849 where1850 E: Error,1851 {1852 str::from_utf8(v)1853 .map(From::from)1854 .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))1855 }18561857 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>1858 where1859 E: Error,1860 {1861 String::from_utf8(v)1862 .map(From::from)1863 .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self))1864 }1865}18661867#[cfg(feature = "std")]1868#[cfg_attr(docsrs, doc(cfg(feature = "std")))]1869impl<'de> Deserialize<'de> for PathBuf {1870 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1871 where1872 D: Deserializer<'de>,1873 {1874 deserializer.deserialize_string(PathBufVisitor)1875 }1876}18771878forwarded_impl! {1879 #[cfg(feature = "std")]1880 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]1881 (), Box<Path>, PathBuf::into_boxed_path1882}18831884////////////////////////////////////////////////////////////////////////////////18851886// If this were outside of the serde crate, it would just use:1887//1888// #[derive(Deserialize)]1889// #[serde(variant_identifier)]1890#[cfg(all(feature = "std", any(unix, windows)))]1891variant_identifier! {1892 OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)1893 "`Unix` or `Windows`",1894 OSSTR_VARIANTS1895}18961897#[cfg(all(feature = "std", any(unix, windows)))]1898struct OsStringVisitor;18991900#[cfg(all(feature = "std", any(unix, windows)))]1901impl<'de> Visitor<'de> for OsStringVisitor {1902 type Value = OsString;19031904 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1905 formatter.write_str("os string")1906 }19071908 #[cfg(unix)]1909 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>1910 where1911 A: EnumAccess<'de>,1912 {1913 use std::os::unix::ffi::OsStringExt;19141915 match tri!(data.variant()) {1916 (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec),1917 (OsStringKind::Windows, _) => Err(Error::custom(1918 "cannot deserialize Windows OS string on Unix",1919 )),1920 }1921 }19221923 #[cfg(windows)]1924 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>1925 where1926 A: EnumAccess<'de>,1927 {1928 use std::os::windows::ffi::OsStringExt;19291930 match tri!(data.variant()) {1931 (OsStringKind::Windows, v) => v1932 .newtype_variant::<Vec<u16>>()1933 .map(|vec| OsString::from_wide(&vec)),1934 (OsStringKind::Unix, _) => Err(Error::custom(1935 "cannot deserialize Unix OS string on Windows",1936 )),1937 }1938 }1939}19401941#[cfg(all(feature = "std", any(unix, windows)))]1942#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]1943impl<'de> Deserialize<'de> for OsString {1944 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1945 where1946 D: Deserializer<'de>,1947 {1948 deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor)1949 }1950}19511952////////////////////////////////////////////////////////////////////////////////19531954forwarded_impl! {1955 #[cfg(any(feature = "std", feature = "alloc"))]1956 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1957 (T), Box<T>, Box::new1958}19591960forwarded_impl! {1961 #[cfg(any(feature = "std", feature = "alloc"))]1962 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1963 (T), Box<[T]>, Vec::into_boxed_slice1964}19651966forwarded_impl! {1967 #[cfg(any(feature = "std", feature = "alloc"))]1968 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1969 (), Box<str>, String::into_boxed_str1970}19711972forwarded_impl! {1973 #[cfg(all(feature = "std", any(unix, windows)))]1974 #[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]1975 (), Box<OsStr>, OsString::into_boxed_os_str1976}19771978#[cfg(any(feature = "std", feature = "alloc"))]1979#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]1980impl<'de, 'a, T> Deserialize<'de> for Cow<'a, T>1981where1982 T: ?Sized + ToOwned,1983 T::Owned: Deserialize<'de>,1984{1985 #[inline]1986 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>1987 where1988 D: Deserializer<'de>,1989 {1990 T::Owned::deserialize(deserializer).map(Cow::Owned)1991 }1992}19931994////////////////////////////////////////////////////////////////////////////////19951996/// This impl requires the [`"rc"`] Cargo feature of Serde. The resulting1997/// `Weak<T>` has a reference count of 0 and cannot be upgraded.1998///1999/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc2000#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]

The first 2,000 of 3,173 lines.