| 1 | //! Definition of a TOML [value][Value] |
| 2 | |
| 3 | use std::collections::{BTreeMap, HashMap}; |
| 4 | use std::fmt; |
| 5 | use std::hash::Hash; |
| 6 | use std::mem::discriminant; |
| 7 | use std::ops; |
| 8 | use std::vec; |
| 9 | |
| 10 | use serde::de; |
| 11 | use serde::de::IntoDeserializer; |
| 12 | use serde::ser; |
| 13 | |
| 14 | use toml_datetime::__unstable as datetime; |
| 15 | pub use toml_datetime::{Date, Datetime, DatetimeParseError, Offset, Time}; |
| 16 | |
| 17 | /// Type representing a TOML array, payload of the `Value::Array` variant |
| 18 | pub type Array = Vec<Value>; |
| 19 | |
| 20 | #[doc (no_inline)] |
| 21 | pub use crate::Table; |
| 22 | |
| 23 | /// Representation of a TOML value. |
| 24 | #[derive (PartialEq, Clone, Debug)] |
| 25 | pub enum Value { |
| 26 | /// Represents a TOML string |
| 27 | String(String), |
| 28 | /// Represents a TOML integer |
| 29 | Integer(i64), |
| 30 | /// Represents a TOML float |
| 31 | Float(f64), |
| 32 | /// Represents a TOML boolean |
| 33 | Boolean(bool), |
| 34 | /// Represents a TOML datetime |
| 35 | Datetime(Datetime), |
| 36 | /// Represents a TOML array |
| 37 | Array(Array), |
| 38 | /// Represents a TOML table |
| 39 | Table(Table), |
| 40 | } |
| 41 | |
| 42 | impl Value { |
| 43 | /// Convert a `T` into `toml::Value` which is an enum that can represent |
| 44 | /// any valid TOML data. |
| 45 | /// |
| 46 | /// This conversion can fail if `T`'s implementation of `Serialize` decides to |
| 47 | /// fail, or if `T` contains a map with non-string keys. |
| 48 | pub fn try_from<T>(value: T) -> Result<Value, crate::ser::Error> |
| 49 | where |
| 50 | T: ser::Serialize, |
| 51 | { |
| 52 | value.serialize(ValueSerializer) |
| 53 | } |
| 54 | |
| 55 | /// Interpret a `toml::Value` as an instance of type `T`. |
| 56 | /// |
| 57 | /// This conversion can fail if the structure of the `Value` does not match the |
| 58 | /// structure expected by `T`, for example if `T` is a struct type but the |
| 59 | /// `Value` contains something other than a TOML table. It can also fail if the |
| 60 | /// structure is correct but `T`'s implementation of `Deserialize` decides that |
| 61 | /// something is wrong with the data, for example required struct fields are |
| 62 | /// missing from the TOML map or some number is too big to fit in the expected |
| 63 | /// primitive type. |
| 64 | pub fn try_into<'de, T>(self) -> Result<T, crate::de::Error> |
| 65 | where |
| 66 | T: de::Deserialize<'de>, |
| 67 | { |
| 68 | de::Deserialize::deserialize(self) |
| 69 | } |
| 70 | |
| 71 | /// Index into a TOML array or map. A string index can be used to access a |
| 72 | /// value in a map, and a usize index can be used to access an element of an |
| 73 | /// array. |
| 74 | /// |
| 75 | /// Returns `None` if the type of `self` does not match the type of the |
| 76 | /// index, for example if the index is a string and `self` is an array or a |
| 77 | /// number. Also returns `None` if the given key does not exist in the map |
| 78 | /// or the given index is not within the bounds of the array. |
| 79 | pub fn get<I: Index>(&self, index: I) -> Option<&Value> { |
| 80 | index.index(self) |
| 81 | } |
| 82 | |
| 83 | /// Mutably index into a TOML array or map. A string index can be used to |
| 84 | /// access a value in a map, and a usize index can be used to access an |
| 85 | /// element of an array. |
| 86 | /// |
| 87 | /// Returns `None` if the type of `self` does not match the type of the |
| 88 | /// index, for example if the index is a string and `self` is an array or a |
| 89 | /// number. Also returns `None` if the given key does not exist in the map |
| 90 | /// or the given index is not within the bounds of the array. |
| 91 | pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { |
| 92 | index.index_mut(self) |
| 93 | } |
| 94 | |
| 95 | /// Extracts the integer value if it is an integer. |
| 96 | pub fn as_integer(&self) -> Option<i64> { |
| 97 | match *self { |
| 98 | Value::Integer(i) => Some(i), |
| 99 | _ => None, |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Tests whether this value is an integer. |
| 104 | pub fn is_integer(&self) -> bool { |
| 105 | self.as_integer().is_some() |
| 106 | } |
| 107 | |
| 108 | /// Extracts the float value if it is a float. |
| 109 | pub fn as_float(&self) -> Option<f64> { |
| 110 | match *self { |
| 111 | Value::Float(f) => Some(f), |
| 112 | _ => None, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// Tests whether this value is a float. |
| 117 | pub fn is_float(&self) -> bool { |
| 118 | self.as_float().is_some() |
| 119 | } |
| 120 | |
| 121 | /// Extracts the boolean value if it is a boolean. |
| 122 | pub fn as_bool(&self) -> Option<bool> { |
| 123 | match *self { |
| 124 | Value::Boolean(b) => Some(b), |
| 125 | _ => None, |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Tests whether this value is a boolean. |
| 130 | pub fn is_bool(&self) -> bool { |
| 131 | self.as_bool().is_some() |
| 132 | } |
| 133 | |
| 134 | /// Extracts the string of this value if it is a string. |
| 135 | pub fn as_str(&self) -> Option<&str> { |
| 136 | match *self { |
| 137 | Value::String(ref s) => Some(&**s), |
| 138 | _ => None, |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// Tests if this value is a string. |
| 143 | pub fn is_str(&self) -> bool { |
| 144 | self.as_str().is_some() |
| 145 | } |
| 146 | |
| 147 | /// Extracts the datetime value if it is a datetime. |
| 148 | /// |
| 149 | /// Note that a parsed TOML value will only contain ISO 8601 dates. An |
| 150 | /// example date is: |
| 151 | /// |
| 152 | /// ```notrust |
| 153 | /// 1979-05-27T07:32:00Z |
| 154 | /// ``` |
| 155 | pub fn as_datetime(&self) -> Option<&Datetime> { |
| 156 | match *self { |
| 157 | Value::Datetime(ref s) => Some(s), |
| 158 | _ => None, |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Tests whether this value is a datetime. |
| 163 | pub fn is_datetime(&self) -> bool { |
| 164 | self.as_datetime().is_some() |
| 165 | } |
| 166 | |
| 167 | /// Extracts the array value if it is an array. |
| 168 | pub fn as_array(&self) -> Option<&Vec<Value>> { |
| 169 | match *self { |
| 170 | Value::Array(ref s) => Some(s), |
| 171 | _ => None, |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /// Extracts the array value if it is an array. |
| 176 | pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { |
| 177 | match *self { |
| 178 | Value::Array(ref mut s) => Some(s), |
| 179 | _ => None, |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// Tests whether this value is an array. |
| 184 | pub fn is_array(&self) -> bool { |
| 185 | self.as_array().is_some() |
| 186 | } |
| 187 | |
| 188 | /// Extracts the table value if it is a table. |
| 189 | pub fn as_table(&self) -> Option<&Table> { |
| 190 | match *self { |
| 191 | Value::Table(ref s) => Some(s), |
| 192 | _ => None, |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// Extracts the table value if it is a table. |
| 197 | pub fn as_table_mut(&mut self) -> Option<&mut Table> { |
| 198 | match *self { |
| 199 | Value::Table(ref mut s) => Some(s), |
| 200 | _ => None, |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /// Tests whether this value is a table. |
| 205 | pub fn is_table(&self) -> bool { |
| 206 | self.as_table().is_some() |
| 207 | } |
| 208 | |
| 209 | /// Tests whether this and another value have the same type. |
| 210 | pub fn same_type(&self, other: &Value) -> bool { |
| 211 | discriminant(self) == discriminant(other) |
| 212 | } |
| 213 | |
| 214 | /// Returns a human-readable representation of the type of this value. |
| 215 | pub fn type_str(&self) -> &'static str { |
| 216 | match *self { |
| 217 | Value::String(..) => "string" , |
| 218 | Value::Integer(..) => "integer" , |
| 219 | Value::Float(..) => "float" , |
| 220 | Value::Boolean(..) => "boolean" , |
| 221 | Value::Datetime(..) => "datetime" , |
| 222 | Value::Array(..) => "array" , |
| 223 | Value::Table(..) => "table" , |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | impl<I> ops::Index<I> for Value |
| 229 | where |
| 230 | I: Index, |
| 231 | { |
| 232 | type Output = Value; |
| 233 | |
| 234 | fn index(&self, index: I) -> &Value { |
| 235 | self.get(index).expect(msg:"index not found" ) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | impl<I> ops::IndexMut<I> for Value |
| 240 | where |
| 241 | I: Index, |
| 242 | { |
| 243 | fn index_mut(&mut self, index: I) -> &mut Value { |
| 244 | self.get_mut(index).expect(msg:"index not found" ) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | impl<'a> From<&'a str> for Value { |
| 249 | #[inline ] |
| 250 | fn from(val: &'a str) -> Value { |
| 251 | Value::String(val.to_string()) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | impl<V: Into<Value>> From<Vec<V>> for Value { |
| 256 | fn from(val: Vec<V>) -> Value { |
| 257 | Value::Array(val.into_iter().map(|v: V| v.into()).collect()) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value { |
| 262 | fn from(val: BTreeMap<S, V>) -> Value { |
| 263 | let table: Map = val.into_iter().map(|(s: S, v: V)| (s.into(), v.into())).collect(); |
| 264 | |
| 265 | Value::Table(table) |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value { |
| 270 | fn from(val: HashMap<S, V>) -> Value { |
| 271 | let table: Map = val.into_iter().map(|(s: S, v: V)| (s.into(), v.into())).collect(); |
| 272 | |
| 273 | Value::Table(table) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | macro_rules! impl_into_value { |
| 278 | ($variant:ident : $T:ty) => { |
| 279 | impl From<$T> for Value { |
| 280 | #[inline] |
| 281 | fn from(val: $T) -> Value { |
| 282 | Value::$variant(val.into()) |
| 283 | } |
| 284 | } |
| 285 | }; |
| 286 | } |
| 287 | |
| 288 | impl_into_value!(String: String); |
| 289 | impl_into_value!(Integer: i64); |
| 290 | impl_into_value!(Integer: i32); |
| 291 | impl_into_value!(Integer: i8); |
| 292 | impl_into_value!(Integer: u8); |
| 293 | impl_into_value!(Integer: u32); |
| 294 | impl_into_value!(Float: f64); |
| 295 | impl_into_value!(Float: f32); |
| 296 | impl_into_value!(Boolean: bool); |
| 297 | impl_into_value!(Datetime: Datetime); |
| 298 | impl_into_value!(Table: Table); |
| 299 | |
| 300 | /// Types that can be used to index a `toml::Value` |
| 301 | /// |
| 302 | /// Currently this is implemented for `usize` to index arrays and `str` to index |
| 303 | /// tables. |
| 304 | /// |
| 305 | /// This trait is sealed and not intended for implementation outside of the |
| 306 | /// `toml` crate. |
| 307 | pub trait Index: Sealed { |
| 308 | #[doc (hidden)] |
| 309 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>; |
| 310 | #[doc (hidden)] |
| 311 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>; |
| 312 | } |
| 313 | |
| 314 | /// An implementation detail that should not be implemented, this will change in |
| 315 | /// the future and break code otherwise. |
| 316 | #[doc (hidden)] |
| 317 | pub trait Sealed {} |
| 318 | impl Sealed for usize {} |
| 319 | impl Sealed for str {} |
| 320 | impl Sealed for String {} |
| 321 | impl<'a, T: Sealed + ?Sized> Sealed for &'a T {} |
| 322 | |
| 323 | impl Index for usize { |
| 324 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
| 325 | match *val { |
| 326 | Value::Array(ref a: &Vec) => a.get(*self), |
| 327 | _ => None, |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
| 332 | match *val { |
| 333 | Value::Array(ref mut a: &mut Vec) => a.get_mut(*self), |
| 334 | _ => None, |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | impl Index for str { |
| 340 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
| 341 | match *val { |
| 342 | Value::Table(ref a: &Map) => a.get(self), |
| 343 | _ => None, |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
| 348 | match *val { |
| 349 | Value::Table(ref mut a: &mut Map) => a.get_mut(self), |
| 350 | _ => None, |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | impl Index for String { |
| 356 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
| 357 | self[..].index(val) |
| 358 | } |
| 359 | |
| 360 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
| 361 | self[..].index_mut(val) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | impl<'s, T: ?Sized> Index for &'s T |
| 366 | where |
| 367 | T: Index, |
| 368 | { |
| 369 | fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { |
| 370 | (**self).index(val) |
| 371 | } |
| 372 | |
| 373 | fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { |
| 374 | (**self).index_mut(val) |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | #[cfg (feature = "display" )] |
| 379 | impl fmt::Display for Value { |
| 380 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 381 | use serde::Serialize as _; |
| 382 | |
| 383 | let mut output: String = String::new(); |
| 384 | let serializer: ValueSerializer<'_> = crate::ser::ValueSerializer::new(&mut output); |
| 385 | self.serialize(serializer).unwrap(); |
| 386 | output.fmt(f) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | #[cfg (feature = "parse" )] |
| 391 | impl std::str::FromStr for Value { |
| 392 | type Err = crate::de::Error; |
| 393 | fn from_str(s: &str) -> Result<Value, Self::Err> { |
| 394 | crate::from_str(s) |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | impl ser::Serialize for Value { |
| 399 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 400 | where |
| 401 | S: ser::Serializer, |
| 402 | { |
| 403 | use serde::ser::SerializeMap; |
| 404 | |
| 405 | match *self { |
| 406 | Value::String(ref s) => serializer.serialize_str(s), |
| 407 | Value::Integer(i) => serializer.serialize_i64(i), |
| 408 | Value::Float(f) => serializer.serialize_f64(f), |
| 409 | Value::Boolean(b) => serializer.serialize_bool(b), |
| 410 | Value::Datetime(ref s) => s.serialize(serializer), |
| 411 | Value::Array(ref a) => a.serialize(serializer), |
| 412 | Value::Table(ref t) => { |
| 413 | let mut map = serializer.serialize_map(Some(t.len()))?; |
| 414 | // Be sure to visit non-tables first (and also non |
| 415 | // array-of-tables) as all keys must be emitted first. |
| 416 | for (k, v) in t { |
| 417 | if !v.is_table() && !v.is_array() |
| 418 | || (v |
| 419 | .as_array() |
| 420 | .map(|a| !a.iter().any(|v| v.is_table())) |
| 421 | .unwrap_or(false)) |
| 422 | { |
| 423 | map.serialize_entry(k, v)?; |
| 424 | } |
| 425 | } |
| 426 | for (k, v) in t { |
| 427 | if v.as_array() |
| 428 | .map(|a| a.iter().any(|v| v.is_table())) |
| 429 | .unwrap_or(false) |
| 430 | { |
| 431 | map.serialize_entry(k, v)?; |
| 432 | } |
| 433 | } |
| 434 | for (k, v) in t { |
| 435 | if v.is_table() { |
| 436 | map.serialize_entry(k, v)?; |
| 437 | } |
| 438 | } |
| 439 | map.end() |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | impl<'de> de::Deserialize<'de> for Value { |
| 446 | fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> |
| 447 | where |
| 448 | D: de::Deserializer<'de>, |
| 449 | { |
| 450 | struct ValueVisitor; |
| 451 | |
| 452 | impl<'de> de::Visitor<'de> for ValueVisitor { |
| 453 | type Value = Value; |
| 454 | |
| 455 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 456 | formatter.write_str("any valid TOML value" ) |
| 457 | } |
| 458 | |
| 459 | fn visit_bool<E>(self, value: bool) -> Result<Value, E> { |
| 460 | Ok(Value::Boolean(value)) |
| 461 | } |
| 462 | |
| 463 | fn visit_i64<E>(self, value: i64) -> Result<Value, E> { |
| 464 | Ok(Value::Integer(value)) |
| 465 | } |
| 466 | |
| 467 | fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> { |
| 468 | if value <= i64::max_value() as u64 { |
| 469 | Ok(Value::Integer(value as i64)) |
| 470 | } else { |
| 471 | Err(de::Error::custom("u64 value was too large" )) |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | fn visit_u32<E>(self, value: u32) -> Result<Value, E> { |
| 476 | Ok(Value::Integer(value.into())) |
| 477 | } |
| 478 | |
| 479 | fn visit_i32<E>(self, value: i32) -> Result<Value, E> { |
| 480 | Ok(Value::Integer(value.into())) |
| 481 | } |
| 482 | |
| 483 | fn visit_f64<E>(self, value: f64) -> Result<Value, E> { |
| 484 | Ok(Value::Float(value)) |
| 485 | } |
| 486 | |
| 487 | fn visit_str<E>(self, value: &str) -> Result<Value, E> { |
| 488 | Ok(Value::String(value.into())) |
| 489 | } |
| 490 | |
| 491 | fn visit_string<E>(self, value: String) -> Result<Value, E> { |
| 492 | Ok(Value::String(value)) |
| 493 | } |
| 494 | |
| 495 | fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> |
| 496 | where |
| 497 | D: de::Deserializer<'de>, |
| 498 | { |
| 499 | de::Deserialize::deserialize(deserializer) |
| 500 | } |
| 501 | |
| 502 | fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> |
| 503 | where |
| 504 | V: de::SeqAccess<'de>, |
| 505 | { |
| 506 | let mut vec = Vec::new(); |
| 507 | while let Some(elem) = visitor.next_element()? { |
| 508 | vec.push(elem); |
| 509 | } |
| 510 | Ok(Value::Array(vec)) |
| 511 | } |
| 512 | |
| 513 | fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> |
| 514 | where |
| 515 | V: de::MapAccess<'de>, |
| 516 | { |
| 517 | let mut key = String::new(); |
| 518 | let datetime = visitor.next_key_seed(DatetimeOrTable { key: &mut key })?; |
| 519 | match datetime { |
| 520 | Some(true) => { |
| 521 | let date: datetime::DatetimeFromString = visitor.next_value()?; |
| 522 | return Ok(Value::Datetime(date.value)); |
| 523 | } |
| 524 | None => return Ok(Value::Table(Table::new())), |
| 525 | Some(false) => {} |
| 526 | } |
| 527 | let mut map = Table::new(); |
| 528 | map.insert(key, visitor.next_value()?); |
| 529 | while let Some(key) = visitor.next_key::<String>()? { |
| 530 | if let crate::map::Entry::Vacant(vacant) = map.entry(&key) { |
| 531 | vacant.insert(visitor.next_value()?); |
| 532 | } else { |
| 533 | let msg = format!("duplicate key: ` {}`" , key); |
| 534 | return Err(de::Error::custom(msg)); |
| 535 | } |
| 536 | } |
| 537 | Ok(Value::Table(map)) |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | deserializer.deserialize_any(ValueVisitor) |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | // This is wrapped by `Table` and any trait methods implemented here need to be wrapped there. |
| 546 | impl<'de> de::Deserializer<'de> for Value { |
| 547 | type Error = crate::de::Error; |
| 548 | |
| 549 | fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error> |
| 550 | where |
| 551 | V: de::Visitor<'de>, |
| 552 | { |
| 553 | match self { |
| 554 | Value::Boolean(v) => visitor.visit_bool(v), |
| 555 | Value::Integer(n) => visitor.visit_i64(n), |
| 556 | Value::Float(n) => visitor.visit_f64(n), |
| 557 | Value::String(v) => visitor.visit_string(v), |
| 558 | Value::Datetime(v) => visitor.visit_string(v.to_string()), |
| 559 | Value::Array(v) => { |
| 560 | let len = v.len(); |
| 561 | let mut deserializer = SeqDeserializer::new(v); |
| 562 | let seq = visitor.visit_seq(&mut deserializer)?; |
| 563 | let remaining = deserializer.iter.len(); |
| 564 | if remaining == 0 { |
| 565 | Ok(seq) |
| 566 | } else { |
| 567 | Err(de::Error::invalid_length(len, &"fewer elements in array" )) |
| 568 | } |
| 569 | } |
| 570 | Value::Table(v) => { |
| 571 | let len = v.len(); |
| 572 | let mut deserializer = MapDeserializer::new(v); |
| 573 | let map = visitor.visit_map(&mut deserializer)?; |
| 574 | let remaining = deserializer.iter.len(); |
| 575 | if remaining == 0 { |
| 576 | Ok(map) |
| 577 | } else { |
| 578 | Err(de::Error::invalid_length(len, &"fewer elements in map" )) |
| 579 | } |
| 580 | } |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | #[inline ] |
| 585 | fn deserialize_enum<V>( |
| 586 | self, |
| 587 | _name: &'static str, |
| 588 | _variants: &'static [&'static str], |
| 589 | visitor: V, |
| 590 | ) -> Result<V::Value, crate::de::Error> |
| 591 | where |
| 592 | V: de::Visitor<'de>, |
| 593 | { |
| 594 | match self { |
| 595 | Value::String(variant) => visitor.visit_enum(variant.into_deserializer()), |
| 596 | Value::Table(variant) => { |
| 597 | use de::Error; |
| 598 | if variant.is_empty() { |
| 599 | Err(crate::de::Error::custom( |
| 600 | "wanted exactly 1 element, found 0 elements" , |
| 601 | )) |
| 602 | } else if variant.len() != 1 { |
| 603 | Err(crate::de::Error::custom( |
| 604 | "wanted exactly 1 element, more than 1 element" , |
| 605 | )) |
| 606 | } else { |
| 607 | let deserializer = MapDeserializer::new(variant); |
| 608 | visitor.visit_enum(deserializer) |
| 609 | } |
| 610 | } |
| 611 | _ => Err(de::Error::invalid_type( |
| 612 | de::Unexpected::UnitVariant, |
| 613 | &"string only" , |
| 614 | )), |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | // `None` is interpreted as a missing field so be sure to implement `Some` |
| 619 | // as a present field. |
| 620 | fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error> |
| 621 | where |
| 622 | V: de::Visitor<'de>, |
| 623 | { |
| 624 | visitor.visit_some(self) |
| 625 | } |
| 626 | |
| 627 | fn deserialize_newtype_struct<V>( |
| 628 | self, |
| 629 | _name: &'static str, |
| 630 | visitor: V, |
| 631 | ) -> Result<V::Value, crate::de::Error> |
| 632 | where |
| 633 | V: de::Visitor<'de>, |
| 634 | { |
| 635 | visitor.visit_newtype_struct(self) |
| 636 | } |
| 637 | |
| 638 | serde::forward_to_deserialize_any! { |
| 639 | bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq |
| 640 | bytes byte_buf map unit_struct tuple_struct struct |
| 641 | tuple ignored_any identifier |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | struct SeqDeserializer { |
| 646 | iter: vec::IntoIter<Value>, |
| 647 | } |
| 648 | |
| 649 | impl SeqDeserializer { |
| 650 | fn new(vec: Vec<Value>) -> Self { |
| 651 | SeqDeserializer { |
| 652 | iter: vec.into_iter(), |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | impl<'de> de::SeqAccess<'de> for SeqDeserializer { |
| 658 | type Error = crate::de::Error; |
| 659 | |
| 660 | fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error> |
| 661 | where |
| 662 | T: de::DeserializeSeed<'de>, |
| 663 | { |
| 664 | match self.iter.next() { |
| 665 | Some(value: Value) => seed.deserialize(value).map(op:Some), |
| 666 | None => Ok(None), |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | fn size_hint(&self) -> Option<usize> { |
| 671 | match self.iter.size_hint() { |
| 672 | (lower: usize, Some(upper: usize)) if lower == upper => Some(upper), |
| 673 | _ => None, |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | struct MapDeserializer { |
| 679 | iter: <Table as IntoIterator>::IntoIter, |
| 680 | value: Option<(String, Value)>, |
| 681 | } |
| 682 | |
| 683 | impl MapDeserializer { |
| 684 | fn new(map: Table) -> Self { |
| 685 | MapDeserializer { |
| 686 | iter: map.into_iter(), |
| 687 | value: None, |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | impl<'de> de::MapAccess<'de> for MapDeserializer { |
| 693 | type Error = crate::de::Error; |
| 694 | |
| 695 | fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error> |
| 696 | where |
| 697 | T: de::DeserializeSeed<'de>, |
| 698 | { |
| 699 | match self.iter.next() { |
| 700 | Some((key, value)) => { |
| 701 | self.value = Some((key.clone(), value)); |
| 702 | seed.deserialize(Value::String(key)).map(Some) |
| 703 | } |
| 704 | None => Ok(None), |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error> |
| 709 | where |
| 710 | T: de::DeserializeSeed<'de>, |
| 711 | { |
| 712 | let (key, res) = match self.value.take() { |
| 713 | Some((key, value)) => (key, seed.deserialize(value)), |
| 714 | None => return Err(de::Error::custom("value is missing" )), |
| 715 | }; |
| 716 | res.map_err(|mut error| { |
| 717 | error.add_key(key); |
| 718 | error |
| 719 | }) |
| 720 | } |
| 721 | |
| 722 | fn size_hint(&self) -> Option<usize> { |
| 723 | match self.iter.size_hint() { |
| 724 | (lower, Some(upper)) if lower == upper => Some(upper), |
| 725 | _ => None, |
| 726 | } |
| 727 | } |
| 728 | } |
| 729 | |
| 730 | impl<'de> de::EnumAccess<'de> for MapDeserializer { |
| 731 | type Error = crate::de::Error; |
| 732 | type Variant = MapEnumDeserializer; |
| 733 | |
| 734 | fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> |
| 735 | where |
| 736 | V: serde::de::DeserializeSeed<'de>, |
| 737 | { |
| 738 | use de::Error; |
| 739 | let (key, value) = match self.iter.next() { |
| 740 | Some(pair) => pair, |
| 741 | None => { |
| 742 | return Err(Error::custom( |
| 743 | "expected table with exactly 1 entry, found empty table" , |
| 744 | )); |
| 745 | } |
| 746 | }; |
| 747 | |
| 748 | let val = seed.deserialize(key.into_deserializer())?; |
| 749 | |
| 750 | let variant = MapEnumDeserializer::new(value); |
| 751 | |
| 752 | Ok((val, variant)) |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | /// Deserializes table values into enum variants. |
| 757 | pub(crate) struct MapEnumDeserializer { |
| 758 | value: Value, |
| 759 | } |
| 760 | |
| 761 | impl MapEnumDeserializer { |
| 762 | pub(crate) fn new(value: Value) -> Self { |
| 763 | MapEnumDeserializer { value } |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | impl<'de> serde::de::VariantAccess<'de> for MapEnumDeserializer { |
| 768 | type Error = crate::de::Error; |
| 769 | |
| 770 | fn unit_variant(self) -> Result<(), Self::Error> { |
| 771 | use de::Error; |
| 772 | match self.value { |
| 773 | Value::Table(values) => { |
| 774 | if values.is_empty() { |
| 775 | Ok(()) |
| 776 | } else { |
| 777 | Err(Error::custom("expected empty table" )) |
| 778 | } |
| 779 | } |
| 780 | e => Err(Error::custom(format!( |
| 781 | "expected table, found {}" , |
| 782 | e.type_str() |
| 783 | ))), |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> |
| 788 | where |
| 789 | T: serde::de::DeserializeSeed<'de>, |
| 790 | { |
| 791 | seed.deserialize(self.value.into_deserializer()) |
| 792 | } |
| 793 | |
| 794 | fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> |
| 795 | where |
| 796 | V: serde::de::Visitor<'de>, |
| 797 | { |
| 798 | use de::Error; |
| 799 | match self.value { |
| 800 | Value::Table(values) => { |
| 801 | let tuple_values = values |
| 802 | .into_iter() |
| 803 | .enumerate() |
| 804 | .map(|(index, (key, value))| match key.parse::<usize>() { |
| 805 | Ok(key_index) if key_index == index => Ok(value), |
| 806 | Ok(_) | Err(_) => Err(Error::custom(format!( |
| 807 | "expected table key ` {}`, but was ` {}`" , |
| 808 | index, key |
| 809 | ))), |
| 810 | }) |
| 811 | // Fold all values into a `Vec`, or return the first error. |
| 812 | .fold(Ok(Vec::with_capacity(len)), |result, value_result| { |
| 813 | result.and_then(move |mut tuple_values| match value_result { |
| 814 | Ok(value) => { |
| 815 | tuple_values.push(value); |
| 816 | Ok(tuple_values) |
| 817 | } |
| 818 | // `Result<de::Value, Self::Error>` to `Result<Vec<_>, Self::Error>` |
| 819 | Err(e) => Err(e), |
| 820 | }) |
| 821 | })?; |
| 822 | |
| 823 | if tuple_values.len() == len { |
| 824 | serde::de::Deserializer::deserialize_seq( |
| 825 | tuple_values.into_deserializer(), |
| 826 | visitor, |
| 827 | ) |
| 828 | } else { |
| 829 | Err(Error::custom(format!("expected tuple with length {}" , len))) |
| 830 | } |
| 831 | } |
| 832 | e => Err(Error::custom(format!( |
| 833 | "expected table, found {}" , |
| 834 | e.type_str() |
| 835 | ))), |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | fn struct_variant<V>( |
| 840 | self, |
| 841 | fields: &'static [&'static str], |
| 842 | visitor: V, |
| 843 | ) -> Result<V::Value, Self::Error> |
| 844 | where |
| 845 | V: serde::de::Visitor<'de>, |
| 846 | { |
| 847 | serde::de::Deserializer::deserialize_struct( |
| 848 | self.value.into_deserializer(), |
| 849 | "" , // TODO: this should be the variant name |
| 850 | fields, |
| 851 | visitor, |
| 852 | ) |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | impl<'de> de::IntoDeserializer<'de, crate::de::Error> for Value { |
| 857 | type Deserializer = Self; |
| 858 | |
| 859 | fn into_deserializer(self) -> Self { |
| 860 | self |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | struct ValueSerializer; |
| 865 | |
| 866 | impl ser::Serializer for ValueSerializer { |
| 867 | type Ok = Value; |
| 868 | type Error = crate::ser::Error; |
| 869 | |
| 870 | type SerializeSeq = ValueSerializeVec; |
| 871 | type SerializeTuple = ValueSerializeVec; |
| 872 | type SerializeTupleStruct = ValueSerializeVec; |
| 873 | type SerializeTupleVariant = ValueSerializeVec; |
| 874 | type SerializeMap = ValueSerializeMap; |
| 875 | type SerializeStruct = ValueSerializeMap; |
| 876 | type SerializeStructVariant = ser::Impossible<Value, crate::ser::Error>; |
| 877 | |
| 878 | fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> { |
| 879 | Ok(Value::Boolean(value)) |
| 880 | } |
| 881 | |
| 882 | fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> { |
| 883 | self.serialize_i64(value.into()) |
| 884 | } |
| 885 | |
| 886 | fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> { |
| 887 | self.serialize_i64(value.into()) |
| 888 | } |
| 889 | |
| 890 | fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> { |
| 891 | self.serialize_i64(value.into()) |
| 892 | } |
| 893 | |
| 894 | fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> { |
| 895 | Ok(Value::Integer(value)) |
| 896 | } |
| 897 | |
| 898 | fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> { |
| 899 | self.serialize_i64(value.into()) |
| 900 | } |
| 901 | |
| 902 | fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> { |
| 903 | self.serialize_i64(value.into()) |
| 904 | } |
| 905 | |
| 906 | fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> { |
| 907 | self.serialize_i64(value.into()) |
| 908 | } |
| 909 | |
| 910 | fn serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error> { |
| 911 | if value <= i64::max_value() as u64 { |
| 912 | self.serialize_i64(value as i64) |
| 913 | } else { |
| 914 | Err(ser::Error::custom("u64 value was too large" )) |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> { |
| 919 | self.serialize_f64(value.into()) |
| 920 | } |
| 921 | |
| 922 | fn serialize_f64(self, value: f64) -> Result<Value, crate::ser::Error> { |
| 923 | Ok(Value::Float(value)) |
| 924 | } |
| 925 | |
| 926 | fn serialize_char(self, value: char) -> Result<Value, crate::ser::Error> { |
| 927 | let mut s = String::new(); |
| 928 | s.push(value); |
| 929 | self.serialize_str(&s) |
| 930 | } |
| 931 | |
| 932 | fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> { |
| 933 | Ok(Value::String(value.to_owned())) |
| 934 | } |
| 935 | |
| 936 | fn serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error> { |
| 937 | let vec = value.iter().map(|&b| Value::Integer(b.into())).collect(); |
| 938 | Ok(Value::Array(vec)) |
| 939 | } |
| 940 | |
| 941 | fn serialize_unit(self) -> Result<Value, crate::ser::Error> { |
| 942 | Err(crate::ser::Error::unsupported_type(Some("unit" ))) |
| 943 | } |
| 944 | |
| 945 | fn serialize_unit_struct(self, name: &'static str) -> Result<Value, crate::ser::Error> { |
| 946 | Err(crate::ser::Error::unsupported_type(Some(name))) |
| 947 | } |
| 948 | |
| 949 | fn serialize_unit_variant( |
| 950 | self, |
| 951 | _name: &'static str, |
| 952 | _variant_index: u32, |
| 953 | _variant: &'static str, |
| 954 | ) -> Result<Value, crate::ser::Error> { |
| 955 | self.serialize_str(_variant) |
| 956 | } |
| 957 | |
| 958 | fn serialize_newtype_struct<T: ?Sized>( |
| 959 | self, |
| 960 | _name: &'static str, |
| 961 | value: &T, |
| 962 | ) -> Result<Value, crate::ser::Error> |
| 963 | where |
| 964 | T: ser::Serialize, |
| 965 | { |
| 966 | value.serialize(self) |
| 967 | } |
| 968 | |
| 969 | fn serialize_newtype_variant<T: ?Sized>( |
| 970 | self, |
| 971 | _name: &'static str, |
| 972 | _variant_index: u32, |
| 973 | variant: &'static str, |
| 974 | value: &T, |
| 975 | ) -> Result<Value, crate::ser::Error> |
| 976 | where |
| 977 | T: ser::Serialize, |
| 978 | { |
| 979 | let value = value.serialize(ValueSerializer)?; |
| 980 | let mut table = Table::new(); |
| 981 | table.insert(variant.to_owned(), value); |
| 982 | Ok(table.into()) |
| 983 | } |
| 984 | |
| 985 | fn serialize_none(self) -> Result<Value, crate::ser::Error> { |
| 986 | Err(crate::ser::Error::unsupported_none()) |
| 987 | } |
| 988 | |
| 989 | fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, crate::ser::Error> |
| 990 | where |
| 991 | T: ser::Serialize, |
| 992 | { |
| 993 | value.serialize(self) |
| 994 | } |
| 995 | |
| 996 | fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> { |
| 997 | Ok(ValueSerializeVec { |
| 998 | vec: Vec::with_capacity(len.unwrap_or(0)), |
| 999 | }) |
| 1000 | } |
| 1001 | |
| 1002 | fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> { |
| 1003 | self.serialize_seq(Some(len)) |
| 1004 | } |
| 1005 | |
| 1006 | fn serialize_tuple_struct( |
| 1007 | self, |
| 1008 | _name: &'static str, |
| 1009 | len: usize, |
| 1010 | ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> { |
| 1011 | self.serialize_seq(Some(len)) |
| 1012 | } |
| 1013 | |
| 1014 | fn serialize_tuple_variant( |
| 1015 | self, |
| 1016 | _name: &'static str, |
| 1017 | _variant_index: u32, |
| 1018 | _variant: &'static str, |
| 1019 | len: usize, |
| 1020 | ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> { |
| 1021 | self.serialize_seq(Some(len)) |
| 1022 | } |
| 1023 | |
| 1024 | fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> { |
| 1025 | Ok(ValueSerializeMap { |
| 1026 | ser: SerializeMap { |
| 1027 | map: Table::new(), |
| 1028 | next_key: None, |
| 1029 | }, |
| 1030 | }) |
| 1031 | } |
| 1032 | |
| 1033 | fn serialize_struct( |
| 1034 | self, |
| 1035 | _name: &'static str, |
| 1036 | len: usize, |
| 1037 | ) -> Result<Self::SerializeStruct, crate::ser::Error> { |
| 1038 | self.serialize_map(Some(len)) |
| 1039 | } |
| 1040 | |
| 1041 | fn serialize_struct_variant( |
| 1042 | self, |
| 1043 | name: &'static str, |
| 1044 | _variant_index: u32, |
| 1045 | _variant: &'static str, |
| 1046 | _len: usize, |
| 1047 | ) -> Result<Self::SerializeStructVariant, crate::ser::Error> { |
| 1048 | Err(crate::ser::Error::unsupported_type(Some(name))) |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | pub(crate) struct TableSerializer; |
| 1053 | |
| 1054 | impl ser::Serializer for TableSerializer { |
| 1055 | type Ok = Table; |
| 1056 | type Error = crate::ser::Error; |
| 1057 | |
| 1058 | type SerializeSeq = ser::Impossible<Table, crate::ser::Error>; |
| 1059 | type SerializeTuple = ser::Impossible<Table, crate::ser::Error>; |
| 1060 | type SerializeTupleStruct = ser::Impossible<Table, crate::ser::Error>; |
| 1061 | type SerializeTupleVariant = ser::Impossible<Table, crate::ser::Error>; |
| 1062 | type SerializeMap = SerializeMap; |
| 1063 | type SerializeStruct = SerializeMap; |
| 1064 | type SerializeStructVariant = ser::Impossible<Table, crate::ser::Error>; |
| 1065 | |
| 1066 | fn serialize_bool(self, _value: bool) -> Result<Table, crate::ser::Error> { |
| 1067 | Err(crate::ser::Error::unsupported_type(None)) |
| 1068 | } |
| 1069 | |
| 1070 | fn serialize_i8(self, _value: i8) -> Result<Table, crate::ser::Error> { |
| 1071 | Err(crate::ser::Error::unsupported_type(None)) |
| 1072 | } |
| 1073 | |
| 1074 | fn serialize_i16(self, _value: i16) -> Result<Table, crate::ser::Error> { |
| 1075 | Err(crate::ser::Error::unsupported_type(None)) |
| 1076 | } |
| 1077 | |
| 1078 | fn serialize_i32(self, _value: i32) -> Result<Table, crate::ser::Error> { |
| 1079 | Err(crate::ser::Error::unsupported_type(None)) |
| 1080 | } |
| 1081 | |
| 1082 | fn serialize_i64(self, _value: i64) -> Result<Table, crate::ser::Error> { |
| 1083 | Err(crate::ser::Error::unsupported_type(None)) |
| 1084 | } |
| 1085 | |
| 1086 | fn serialize_u8(self, _value: u8) -> Result<Table, crate::ser::Error> { |
| 1087 | Err(crate::ser::Error::unsupported_type(None)) |
| 1088 | } |
| 1089 | |
| 1090 | fn serialize_u16(self, _value: u16) -> Result<Table, crate::ser::Error> { |
| 1091 | Err(crate::ser::Error::unsupported_type(None)) |
| 1092 | } |
| 1093 | |
| 1094 | fn serialize_u32(self, _value: u32) -> Result<Table, crate::ser::Error> { |
| 1095 | Err(crate::ser::Error::unsupported_type(None)) |
| 1096 | } |
| 1097 | |
| 1098 | fn serialize_u64(self, _value: u64) -> Result<Table, crate::ser::Error> { |
| 1099 | Err(crate::ser::Error::unsupported_type(None)) |
| 1100 | } |
| 1101 | |
| 1102 | fn serialize_f32(self, _value: f32) -> Result<Table, crate::ser::Error> { |
| 1103 | Err(crate::ser::Error::unsupported_type(None)) |
| 1104 | } |
| 1105 | |
| 1106 | fn serialize_f64(self, _value: f64) -> Result<Table, crate::ser::Error> { |
| 1107 | Err(crate::ser::Error::unsupported_type(None)) |
| 1108 | } |
| 1109 | |
| 1110 | fn serialize_char(self, _value: char) -> Result<Table, crate::ser::Error> { |
| 1111 | Err(crate::ser::Error::unsupported_type(None)) |
| 1112 | } |
| 1113 | |
| 1114 | fn serialize_str(self, _value: &str) -> Result<Table, crate::ser::Error> { |
| 1115 | Err(crate::ser::Error::unsupported_type(None)) |
| 1116 | } |
| 1117 | |
| 1118 | fn serialize_bytes(self, _value: &[u8]) -> Result<Table, crate::ser::Error> { |
| 1119 | Err(crate::ser::Error::unsupported_type(None)) |
| 1120 | } |
| 1121 | |
| 1122 | fn serialize_unit(self) -> Result<Table, crate::ser::Error> { |
| 1123 | Err(crate::ser::Error::unsupported_type(None)) |
| 1124 | } |
| 1125 | |
| 1126 | fn serialize_unit_struct(self, _name: &'static str) -> Result<Table, crate::ser::Error> { |
| 1127 | Err(crate::ser::Error::unsupported_type(None)) |
| 1128 | } |
| 1129 | |
| 1130 | fn serialize_unit_variant( |
| 1131 | self, |
| 1132 | name: &'static str, |
| 1133 | _variant_index: u32, |
| 1134 | _variant: &'static str, |
| 1135 | ) -> Result<Table, crate::ser::Error> { |
| 1136 | Err(crate::ser::Error::unsupported_type(Some(name))) |
| 1137 | } |
| 1138 | |
| 1139 | fn serialize_newtype_struct<T: ?Sized>( |
| 1140 | self, |
| 1141 | _name: &'static str, |
| 1142 | value: &T, |
| 1143 | ) -> Result<Table, crate::ser::Error> |
| 1144 | where |
| 1145 | T: ser::Serialize, |
| 1146 | { |
| 1147 | value.serialize(self) |
| 1148 | } |
| 1149 | |
| 1150 | fn serialize_newtype_variant<T: ?Sized>( |
| 1151 | self, |
| 1152 | _name: &'static str, |
| 1153 | _variant_index: u32, |
| 1154 | variant: &'static str, |
| 1155 | value: &T, |
| 1156 | ) -> Result<Table, crate::ser::Error> |
| 1157 | where |
| 1158 | T: ser::Serialize, |
| 1159 | { |
| 1160 | let value = value.serialize(ValueSerializer)?; |
| 1161 | let mut table = Table::new(); |
| 1162 | table.insert(variant.to_owned(), value); |
| 1163 | Ok(table) |
| 1164 | } |
| 1165 | |
| 1166 | fn serialize_none(self) -> Result<Table, crate::ser::Error> { |
| 1167 | Err(crate::ser::Error::unsupported_none()) |
| 1168 | } |
| 1169 | |
| 1170 | fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Table, crate::ser::Error> |
| 1171 | where |
| 1172 | T: ser::Serialize, |
| 1173 | { |
| 1174 | value.serialize(self) |
| 1175 | } |
| 1176 | |
| 1177 | fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> { |
| 1178 | Err(crate::ser::Error::unsupported_type(None)) |
| 1179 | } |
| 1180 | |
| 1181 | fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> { |
| 1182 | Err(crate::ser::Error::unsupported_type(None)) |
| 1183 | } |
| 1184 | |
| 1185 | fn serialize_tuple_struct( |
| 1186 | self, |
| 1187 | name: &'static str, |
| 1188 | _len: usize, |
| 1189 | ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> { |
| 1190 | Err(crate::ser::Error::unsupported_type(Some(name))) |
| 1191 | } |
| 1192 | |
| 1193 | fn serialize_tuple_variant( |
| 1194 | self, |
| 1195 | name: &'static str, |
| 1196 | _variant_index: u32, |
| 1197 | _variant: &'static str, |
| 1198 | _len: usize, |
| 1199 | ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> { |
| 1200 | Err(crate::ser::Error::unsupported_type(Some(name))) |
| 1201 | } |
| 1202 | |
| 1203 | fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> { |
| 1204 | Ok(SerializeMap { |
| 1205 | map: Table::new(), |
| 1206 | next_key: None, |
| 1207 | }) |
| 1208 | } |
| 1209 | |
| 1210 | fn serialize_struct( |
| 1211 | self, |
| 1212 | _name: &'static str, |
| 1213 | len: usize, |
| 1214 | ) -> Result<Self::SerializeStruct, crate::ser::Error> { |
| 1215 | self.serialize_map(Some(len)) |
| 1216 | } |
| 1217 | |
| 1218 | fn serialize_struct_variant( |
| 1219 | self, |
| 1220 | name: &'static str, |
| 1221 | _variant_index: u32, |
| 1222 | _variant: &'static str, |
| 1223 | _len: usize, |
| 1224 | ) -> Result<Self::SerializeStructVariant, crate::ser::Error> { |
| 1225 | Err(crate::ser::Error::unsupported_type(Some(name))) |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | struct ValueSerializeVec { |
| 1230 | vec: Vec<Value>, |
| 1231 | } |
| 1232 | |
| 1233 | impl ser::SerializeSeq for ValueSerializeVec { |
| 1234 | type Ok = Value; |
| 1235 | type Error = crate::ser::Error; |
| 1236 | |
| 1237 | fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
| 1238 | where |
| 1239 | T: ser::Serialize, |
| 1240 | { |
| 1241 | self.vec.push(Value::try_from(value)?); |
| 1242 | Ok(()) |
| 1243 | } |
| 1244 | |
| 1245 | fn end(self) -> Result<Value, crate::ser::Error> { |
| 1246 | Ok(Value::Array(self.vec)) |
| 1247 | } |
| 1248 | } |
| 1249 | |
| 1250 | impl ser::SerializeTuple for ValueSerializeVec { |
| 1251 | type Ok = Value; |
| 1252 | type Error = crate::ser::Error; |
| 1253 | |
| 1254 | fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
| 1255 | where |
| 1256 | T: ser::Serialize, |
| 1257 | { |
| 1258 | ser::SerializeSeq::serialize_element(self, value) |
| 1259 | } |
| 1260 | |
| 1261 | fn end(self) -> Result<Value, crate::ser::Error> { |
| 1262 | ser::SerializeSeq::end(self) |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | impl ser::SerializeTupleStruct for ValueSerializeVec { |
| 1267 | type Ok = Value; |
| 1268 | type Error = crate::ser::Error; |
| 1269 | |
| 1270 | fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
| 1271 | where |
| 1272 | T: ser::Serialize, |
| 1273 | { |
| 1274 | ser::SerializeSeq::serialize_element(self, value) |
| 1275 | } |
| 1276 | |
| 1277 | fn end(self) -> Result<Value, crate::ser::Error> { |
| 1278 | ser::SerializeSeq::end(self) |
| 1279 | } |
| 1280 | } |
| 1281 | |
| 1282 | impl ser::SerializeTupleVariant for ValueSerializeVec { |
| 1283 | type Ok = Value; |
| 1284 | type Error = crate::ser::Error; |
| 1285 | |
| 1286 | fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
| 1287 | where |
| 1288 | T: ser::Serialize, |
| 1289 | { |
| 1290 | ser::SerializeSeq::serialize_element(self, value) |
| 1291 | } |
| 1292 | |
| 1293 | fn end(self) -> Result<Value, crate::ser::Error> { |
| 1294 | ser::SerializeSeq::end(self) |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | pub(crate) struct SerializeMap { |
| 1299 | map: Table, |
| 1300 | next_key: Option<String>, |
| 1301 | } |
| 1302 | |
| 1303 | impl ser::SerializeMap for SerializeMap { |
| 1304 | type Ok = Table; |
| 1305 | type Error = crate::ser::Error; |
| 1306 | |
| 1307 | fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error> |
| 1308 | where |
| 1309 | T: ser::Serialize, |
| 1310 | { |
| 1311 | match Value::try_from(key)? { |
| 1312 | Value::String(s) => self.next_key = Some(s), |
| 1313 | _ => return Err(crate::ser::Error::key_not_string()), |
| 1314 | }; |
| 1315 | Ok(()) |
| 1316 | } |
| 1317 | |
| 1318 | fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
| 1319 | where |
| 1320 | T: ser::Serialize, |
| 1321 | { |
| 1322 | let key = self.next_key.take(); |
| 1323 | let key = key.expect("serialize_value called before serialize_key" ); |
| 1324 | match Value::try_from(value) { |
| 1325 | Ok(value) => { |
| 1326 | self.map.insert(key, value); |
| 1327 | } |
| 1328 | Err(crate::ser::Error { |
| 1329 | inner: crate::edit::ser::Error::UnsupportedNone, |
| 1330 | }) => {} |
| 1331 | Err(e) => return Err(e), |
| 1332 | } |
| 1333 | Ok(()) |
| 1334 | } |
| 1335 | |
| 1336 | fn end(self) -> Result<Table, crate::ser::Error> { |
| 1337 | Ok(self.map) |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | impl ser::SerializeStruct for SerializeMap { |
| 1342 | type Ok = Table; |
| 1343 | type Error = crate::ser::Error; |
| 1344 | |
| 1345 | fn serialize_field<T: ?Sized>( |
| 1346 | &mut self, |
| 1347 | key: &'static str, |
| 1348 | value: &T, |
| 1349 | ) -> Result<(), crate::ser::Error> |
| 1350 | where |
| 1351 | T: ser::Serialize, |
| 1352 | { |
| 1353 | ser::SerializeMap::serialize_key(self, key)?; |
| 1354 | ser::SerializeMap::serialize_value(self, value) |
| 1355 | } |
| 1356 | |
| 1357 | fn end(self) -> Result<Table, crate::ser::Error> { |
| 1358 | ser::SerializeMap::end(self) |
| 1359 | } |
| 1360 | } |
| 1361 | |
| 1362 | struct ValueSerializeMap { |
| 1363 | ser: SerializeMap, |
| 1364 | } |
| 1365 | |
| 1366 | impl ser::SerializeMap for ValueSerializeMap { |
| 1367 | type Ok = Value; |
| 1368 | type Error = crate::ser::Error; |
| 1369 | |
| 1370 | fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error> |
| 1371 | where |
| 1372 | T: ser::Serialize, |
| 1373 | { |
| 1374 | self.ser.serialize_key(key) |
| 1375 | } |
| 1376 | |
| 1377 | fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> |
| 1378 | where |
| 1379 | T: ser::Serialize, |
| 1380 | { |
| 1381 | self.ser.serialize_value(value) |
| 1382 | } |
| 1383 | |
| 1384 | fn end(self) -> Result<Value, crate::ser::Error> { |
| 1385 | self.ser.end().map(op:Value::Table) |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | impl ser::SerializeStruct for ValueSerializeMap { |
| 1390 | type Ok = Value; |
| 1391 | type Error = crate::ser::Error; |
| 1392 | |
| 1393 | fn serialize_field<T: ?Sized>( |
| 1394 | &mut self, |
| 1395 | key: &'static str, |
| 1396 | value: &T, |
| 1397 | ) -> Result<(), crate::ser::Error> |
| 1398 | where |
| 1399 | T: ser::Serialize, |
| 1400 | { |
| 1401 | ser::SerializeMap::serialize_key(self, key)?; |
| 1402 | ser::SerializeMap::serialize_value(self, value) |
| 1403 | } |
| 1404 | |
| 1405 | fn end(self) -> Result<Value, crate::ser::Error> { |
| 1406 | ser::SerializeMap::end(self) |
| 1407 | } |
| 1408 | } |
| 1409 | |
| 1410 | struct DatetimeOrTable<'a> { |
| 1411 | key: &'a mut String, |
| 1412 | } |
| 1413 | |
| 1414 | impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> { |
| 1415 | type Value = bool; |
| 1416 | |
| 1417 | fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> |
| 1418 | where |
| 1419 | D: de::Deserializer<'de>, |
| 1420 | { |
| 1421 | deserializer.deserialize_any(self) |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> { |
| 1426 | type Value = bool; |
| 1427 | |
| 1428 | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1429 | formatter.write_str("a string key" ) |
| 1430 | } |
| 1431 | |
| 1432 | fn visit_str<E>(self, s: &str) -> Result<bool, E> |
| 1433 | where |
| 1434 | E: de::Error, |
| 1435 | { |
| 1436 | if s == datetime::FIELD { |
| 1437 | Ok(true) |
| 1438 | } else { |
| 1439 | self.key.push_str(s); |
| 1440 | Ok(false) |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | fn visit_string<E>(self, s: String) -> Result<bool, E> |
| 1445 | where |
| 1446 | E: de::Error, |
| 1447 | { |
| 1448 | if s == datetime::FIELD { |
| 1449 | Ok(true) |
| 1450 | } else { |
| 1451 | *self.key = s; |
| 1452 | Ok(false) |
| 1453 | } |
| 1454 | } |
| 1455 | } |
| 1456 | |