1 #[cfg(feature = "with-serde")] 2 use serde; 3 4 use std::default::Default; 5 use std::fmt; 6 use std::hash::Hash; 7 use std::hash::Hasher; 8 use std::mem; 9 use std::option; 10 11 use crate::clear::Clear; 12 13 /// Like `Option<T>`, but keeps the actual element on `clear`. 14 pub struct SingularField<T> { 15 value: T, 16 set: bool, 17 } 18 19 /// Like `Option<Box<T>>`, but keeps the actual element on `clear`. 20 pub struct SingularPtrField<T> { 21 value: Option<Box<T>>, 22 set: bool, 23 } 24 25 impl<T> SingularField<T> { 26 /// Construct this object from given value. 27 #[inline] some(value: T) -> SingularField<T>28 pub fn some(value: T) -> SingularField<T> { 29 SingularField { 30 value: value, 31 set: true, 32 } 33 } 34 35 /// True iff this object contains data. 36 #[inline] is_some(&self) -> bool37 pub fn is_some(&self) -> bool { 38 self.set 39 } 40 41 /// True iff this object contains no data. 42 #[inline] is_none(&self) -> bool43 pub fn is_none(&self) -> bool { 44 !self.is_some() 45 } 46 47 /// Convert this object into `Option`. 48 #[inline] into_option(self) -> Option<T>49 pub fn into_option(self) -> Option<T> { 50 if self.set { 51 Some(self.value) 52 } else { 53 None 54 } 55 } 56 57 /// View data as `Option`. 58 #[inline] as_ref<'a>(&'a self) -> Option<&'a T>59 pub fn as_ref<'a>(&'a self) -> Option<&'a T> { 60 if self.set { 61 Some(&self.value) 62 } else { 63 None 64 } 65 } 66 67 /// View data as mutable `Option`. 68 #[inline] as_mut<'a>(&'a mut self) -> Option<&'a mut T>69 pub fn as_mut<'a>(&'a mut self) -> Option<&'a mut T> { 70 if self.set { 71 Some(&mut self.value) 72 } else { 73 None 74 } 75 } 76 77 /// Unwrap data as reference. 78 #[inline] unwrap_ref<'a>(&'a self) -> &'a T79 pub fn unwrap_ref<'a>(&'a self) -> &'a T { 80 self.as_ref().unwrap() 81 } 82 83 /// Unwrap data as mutable reference. 84 #[inline] unwrap_mut_ref<'a>(&'a mut self) -> &'a mut T85 pub fn unwrap_mut_ref<'a>(&'a mut self) -> &'a mut T { 86 self.as_mut().unwrap() 87 } 88 89 /// Unwrap data, panic if not set. 90 #[inline] unwrap(self) -> T91 pub fn unwrap(self) -> T { 92 if self.set { 93 self.value 94 } else { 95 panic!(); 96 } 97 } 98 99 /// Unwrap data or return given default value. 100 #[inline] unwrap_or(self, def: T) -> T101 pub fn unwrap_or(self, def: T) -> T { 102 if self.set { 103 self.value 104 } else { 105 def 106 } 107 } 108 109 /// Unwrap data or return given default value. 110 #[inline] unwrap_or_else<F>(self, f: F) -> T where F: FnOnce() -> T,111 pub fn unwrap_or_else<F>(self, f: F) -> T 112 where 113 F: FnOnce() -> T, 114 { 115 if self.set { 116 self.value 117 } else { 118 f() 119 } 120 } 121 122 /// Apply a function to contained element and store result in new `SingularPtrField`. 123 #[inline] map<U, F>(self, f: F) -> SingularPtrField<U> where F: FnOnce(T) -> U,124 pub fn map<U, F>(self, f: F) -> SingularPtrField<U> 125 where 126 F: FnOnce(T) -> U, 127 { 128 SingularPtrField::from_option(self.into_option().map(f)) 129 } 130 131 /// View as iterator over references. 132 #[inline] iter<'a>(&'a self) -> option::IntoIter<&'a T>133 pub fn iter<'a>(&'a self) -> option::IntoIter<&'a T> { 134 self.as_ref().into_iter() 135 } 136 137 /// View as iterator over mutable references. 138 #[inline] mut_iter<'a>(&'a mut self) -> option::IntoIter<&'a mut T>139 pub fn mut_iter<'a>(&'a mut self) -> option::IntoIter<&'a mut T> { 140 self.as_mut().into_iter() 141 } 142 143 /// Clear this object. 144 /// Note, contained object destructor is not called, so allocated memory could be reused. 145 #[inline] clear(&mut self)146 pub fn clear(&mut self) { 147 self.set = false; 148 } 149 } 150 151 impl<T: Default> SingularField<T> { 152 /// Construct a `SingularField` with no data. 153 #[inline] none() -> SingularField<T>154 pub fn none() -> SingularField<T> { 155 SingularField { 156 value: Default::default(), 157 set: false, 158 } 159 } 160 161 /// Construct `SingularField` from `Option`. 162 #[inline] from_option(option: Option<T>) -> SingularField<T>163 pub fn from_option(option: Option<T>) -> SingularField<T> { 164 match option { 165 Some(x) => SingularField::some(x), 166 None => SingularField::none(), 167 } 168 } 169 170 /// Return data as option, clear this object. 171 #[inline] take(&mut self) -> Option<T>172 pub fn take(&mut self) -> Option<T> { 173 if self.set { 174 self.set = false; 175 Some(mem::replace(&mut self.value, Default::default())) 176 } else { 177 None 178 } 179 } 180 } 181 182 impl<T> SingularPtrField<T> { 183 /// Construct `SingularPtrField` from given object. 184 #[inline] some(value: T) -> SingularPtrField<T>185 pub fn some(value: T) -> SingularPtrField<T> { 186 SingularPtrField { 187 value: Some(Box::new(value)), 188 set: true, 189 } 190 } 191 192 /// Construct an empty `SingularPtrField`. 193 #[inline] none() -> SingularPtrField<T>194 pub fn none() -> SingularPtrField<T> { 195 SingularPtrField { 196 value: None, 197 set: false, 198 } 199 } 200 201 /// Construct `SingularPtrField` from optional. 202 #[inline] from_option(option: Option<T>) -> SingularPtrField<T>203 pub fn from_option(option: Option<T>) -> SingularPtrField<T> { 204 match option { 205 Some(x) => SingularPtrField::some(x), 206 None => SingularPtrField::none(), 207 } 208 } 209 210 /// True iff this object contains data. 211 #[inline] is_some(&self) -> bool212 pub fn is_some(&self) -> bool { 213 self.set 214 } 215 216 /// True iff this object contains no data. 217 #[inline] is_none(&self) -> bool218 pub fn is_none(&self) -> bool { 219 !self.is_some() 220 } 221 222 /// Convert into `Option<T>`. 223 #[inline] into_option(self) -> Option<T>224 pub fn into_option(self) -> Option<T> { 225 if self.set { 226 Some(*self.value.unwrap()) 227 } else { 228 None 229 } 230 } 231 232 /// View data as reference option. 233 #[inline] as_ref<'a>(&'a self) -> Option<&'a T>234 pub fn as_ref<'a>(&'a self) -> Option<&'a T> { 235 if self.set { 236 Some(&**self.value.as_ref().unwrap()) 237 } else { 238 None 239 } 240 } 241 242 /// View data as mutable reference option. 243 #[inline] as_mut<'a>(&'a mut self) -> Option<&'a mut T>244 pub fn as_mut<'a>(&'a mut self) -> Option<&'a mut T> { 245 if self.set { 246 Some(&mut **self.value.as_mut().unwrap()) 247 } else { 248 None 249 } 250 } 251 252 /// Get data as reference. 253 /// Panics if empty. 254 #[inline] get_ref<'a>(&'a self) -> &'a T255 pub fn get_ref<'a>(&'a self) -> &'a T { 256 self.as_ref().unwrap() 257 } 258 259 /// Get data as mutable reference. 260 /// Panics if empty. 261 #[inline] get_mut_ref<'a>(&'a mut self) -> &'a mut T262 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T { 263 self.as_mut().unwrap() 264 } 265 266 /// Take the data. 267 /// Panics if empty 268 #[inline] unwrap(self) -> T269 pub fn unwrap(self) -> T { 270 if self.set { 271 *self.value.unwrap() 272 } else { 273 panic!(); 274 } 275 } 276 277 /// Take the data or return supplied default element if empty. 278 #[inline] unwrap_or(self, def: T) -> T279 pub fn unwrap_or(self, def: T) -> T { 280 if self.set { 281 *self.value.unwrap() 282 } else { 283 def 284 } 285 } 286 287 /// Take the data or return supplied default element if empty. 288 #[inline] unwrap_or_else<F>(self, f: F) -> T where F: FnOnce() -> T,289 pub fn unwrap_or_else<F>(self, f: F) -> T 290 where 291 F: FnOnce() -> T, 292 { 293 if self.set { 294 *self.value.unwrap() 295 } else { 296 f() 297 } 298 } 299 300 /// Apply given function to contained data to construct another `SingularPtrField`. 301 /// Returns empty `SingularPtrField` if this object is empty. 302 #[inline] map<U, F>(self, f: F) -> SingularPtrField<U> where F: FnOnce(T) -> U,303 pub fn map<U, F>(self, f: F) -> SingularPtrField<U> 304 where 305 F: FnOnce(T) -> U, 306 { 307 SingularPtrField::from_option(self.into_option().map(f)) 308 } 309 310 /// View data as iterator. 311 #[inline] iter<'a>(&'a self) -> option::IntoIter<&'a T>312 pub fn iter<'a>(&'a self) -> option::IntoIter<&'a T> { 313 self.as_ref().into_iter() 314 } 315 316 /// View data as mutable iterator. 317 #[inline] mut_iter<'a>(&'a mut self) -> option::IntoIter<&'a mut T>318 pub fn mut_iter<'a>(&'a mut self) -> option::IntoIter<&'a mut T> { 319 self.as_mut().into_iter() 320 } 321 322 /// Take data as option, leaving this object empty. 323 #[inline] take(&mut self) -> Option<T>324 pub fn take(&mut self) -> Option<T> { 325 if self.set { 326 self.set = false; 327 Some(*self.value.take().unwrap()) 328 } else { 329 None 330 } 331 } 332 333 /// Clear this object, but do not call destructor of underlying data. 334 #[inline] clear(&mut self)335 pub fn clear(&mut self) { 336 self.set = false; 337 } 338 } 339 340 impl<T: Default + Clear> SingularField<T> { 341 /// Get contained data, consume self. Return default value for type if this is empty. 342 #[inline] unwrap_or_default(mut self) -> T343 pub fn unwrap_or_default(mut self) -> T { 344 self.value.clear(); 345 self.value 346 } 347 348 /// Initialize this object with default value. 349 /// This operation can be more efficient then construction of clear element, 350 /// because it may reuse previously contained object. 351 #[inline] set_default<'a>(&'a mut self) -> &'a mut T352 pub fn set_default<'a>(&'a mut self) -> &'a mut T { 353 self.set = true; 354 self.value.clear(); 355 &mut self.value 356 } 357 } 358 359 impl<T: Default + Clear> SingularPtrField<T> { 360 /// Get contained data, consume self. Return default value for type if this is empty. 361 #[inline] unwrap_or_default(mut self) -> T362 pub fn unwrap_or_default(mut self) -> T { 363 if self.set { 364 self.unwrap() 365 } else if self.value.is_some() { 366 self.value.clear(); 367 *self.value.unwrap() 368 } else { 369 Default::default() 370 } 371 } 372 373 /// Initialize this object with default value. 374 /// This operation can be more efficient then construction of clear element, 375 /// because it may reuse previously contained object. 376 #[inline] set_default<'a>(&'a mut self) -> &'a mut T377 pub fn set_default<'a>(&'a mut self) -> &'a mut T { 378 self.set = true; 379 if self.value.is_some() { 380 self.value.as_mut().unwrap().clear(); 381 } else { 382 self.value = Some(Default::default()); 383 } 384 self.as_mut().unwrap() 385 } 386 } 387 388 impl<T: Default> Default for SingularField<T> { 389 #[inline] default() -> SingularField<T>390 fn default() -> SingularField<T> { 391 SingularField::none() 392 } 393 } 394 395 impl<T> Default for SingularPtrField<T> { 396 #[inline] default() -> SingularPtrField<T>397 fn default() -> SingularPtrField<T> { 398 SingularPtrField::none() 399 } 400 } 401 402 impl<T: Default> From<Option<T>> for SingularField<T> { from(o: Option<T>) -> Self403 fn from(o: Option<T>) -> Self { 404 SingularField::from_option(o) 405 } 406 } 407 408 impl<T> From<Option<T>> for SingularPtrField<T> { from(o: Option<T>) -> Self409 fn from(o: Option<T>) -> Self { 410 SingularPtrField::from_option(o) 411 } 412 } 413 414 impl<T: Clone + Default> Clone for SingularField<T> { 415 #[inline] clone(&self) -> SingularField<T>416 fn clone(&self) -> SingularField<T> { 417 if self.set { 418 SingularField::some(self.value.clone()) 419 } else { 420 SingularField::none() 421 } 422 } 423 } 424 425 impl<T: Clone> Clone for SingularPtrField<T> { 426 #[inline] clone(&self) -> SingularPtrField<T>427 fn clone(&self) -> SingularPtrField<T> { 428 if self.set { 429 SingularPtrField::some(self.as_ref().unwrap().clone()) 430 } else { 431 SingularPtrField::none() 432 } 433 } 434 } 435 436 impl<T: fmt::Debug> fmt::Debug for SingularField<T> { 437 #[inline] fmt(&self, f: &mut fmt::Formatter) -> fmt::Result438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 439 if self.is_some() { 440 write!(f, "Some({:?})", *self.as_ref().unwrap()) 441 } else { 442 write!(f, "None") 443 } 444 } 445 } 446 447 impl<T: fmt::Debug> fmt::Debug for SingularPtrField<T> { 448 #[inline] fmt(&self, f: &mut fmt::Formatter) -> fmt::Result449 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 450 if self.is_some() { 451 write!(f, "Some({:?})", *self.as_ref().unwrap()) 452 } else { 453 write!(f, "None") 454 } 455 } 456 } 457 458 impl<T: PartialEq> PartialEq for SingularField<T> { 459 #[inline] eq(&self, other: &SingularField<T>) -> bool460 fn eq(&self, other: &SingularField<T>) -> bool { 461 self.as_ref() == other.as_ref() 462 } 463 } 464 465 impl<T: Eq> Eq for SingularField<T> {} 466 467 impl<T: PartialEq> PartialEq for SingularPtrField<T> { 468 #[inline] eq(&self, other: &SingularPtrField<T>) -> bool469 fn eq(&self, other: &SingularPtrField<T>) -> bool { 470 self.as_ref() == other.as_ref() 471 } 472 } 473 474 impl<T: Eq> Eq for SingularPtrField<T> {} 475 476 impl<T: Hash> Hash for SingularField<T> { hash<H: Hasher>(&self, state: &mut H)477 fn hash<H: Hasher>(&self, state: &mut H) { 478 self.as_ref().hash(state); 479 } 480 } 481 482 impl<T: Hash> Hash for SingularPtrField<T> { hash<H: Hasher>(&self, state: &mut H)483 fn hash<H: Hasher>(&self, state: &mut H) { 484 self.as_ref().hash(state); 485 } 486 } 487 488 impl<'a, T> IntoIterator for &'a SingularField<T> { 489 type Item = &'a T; 490 type IntoIter = option::IntoIter<&'a T>; 491 into_iter(self) -> option::IntoIter<&'a T>492 fn into_iter(self) -> option::IntoIter<&'a T> { 493 self.iter() 494 } 495 } 496 497 impl<'a, T> IntoIterator for &'a SingularPtrField<T> { 498 type Item = &'a T; 499 type IntoIter = option::IntoIter<&'a T>; 500 into_iter(self) -> option::IntoIter<&'a T>501 fn into_iter(self) -> option::IntoIter<&'a T> { 502 self.iter() 503 } 504 } 505 506 #[cfg(feature = "with-serde")] 507 impl<T: serde::Serialize> serde::Serialize for SingularPtrField<T> { serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer,508 fn serialize<S>( 509 &self, 510 serializer: S, 511 ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> 512 where 513 S: serde::Serializer, 514 { 515 self.as_ref().serialize(serializer) 516 } 517 } 518 519 #[cfg(feature = "with-serde")] 520 impl<T: serde::Serialize> serde::Serialize for SingularField<T> { serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer,521 fn serialize<S>( 522 &self, 523 serializer: S, 524 ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> 525 where 526 S: serde::Serializer, 527 { 528 self.as_ref().serialize(serializer) 529 } 530 } 531 532 #[cfg(feature = "with-serde")] 533 impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for SingularPtrField<T> { deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> where D: serde::Deserializer<'de>,534 fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> 535 where 536 D: serde::Deserializer<'de>, 537 { 538 Option::deserialize(deserializer).map(SingularPtrField::from_option) 539 } 540 } 541 542 #[cfg(feature = "with-serde")] 543 impl<'de, T: serde::Deserialize<'de> + Default> serde::Deserialize<'de> for SingularField<T> { deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> where D: serde::Deserializer<'de>,544 fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> 545 where 546 D: serde::Deserializer<'de>, 547 { 548 Option::deserialize(deserializer).map(SingularField::from_option) 549 } 550 } 551 552 #[cfg(test)] 553 mod test { 554 use super::SingularField; 555 use crate::clear::Clear; 556 557 #[test] test_set_default_clears()558 fn test_set_default_clears() { 559 #[derive(Default)] 560 struct Foo { 561 b: isize, 562 } 563 564 impl Clear for Foo { 565 fn clear(&mut self) { 566 self.b = 0; 567 } 568 } 569 570 let mut x = SingularField::some(Foo { b: 10 }); 571 x.clear(); 572 x.set_default(); 573 assert_eq!(0, x.as_ref().unwrap().b); 574 575 x.as_mut().unwrap().b = 11; 576 // without clear 577 x.set_default(); 578 assert_eq!(0, x.as_ref().unwrap().b); 579 } 580 } 581