1 use std::default::Default; 2 use std::fmt; 3 use std::hash::Hash; 4 use std::hash::Hasher; 5 use std::mem; 6 use std::option; 7 8 #[cfg(feature = "with-serde")] 9 use serde; 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 if !self.set { 345 self.value.clear(); 346 } 347 self.value 348 } 349 350 /// Initialize this object with default value. 351 /// This operation can be more efficient then construction of clear element, 352 /// because it may reuse previously contained object. 353 #[inline] set_default<'a>(&'a mut self) -> &'a mut T354 pub fn set_default<'a>(&'a mut self) -> &'a mut T { 355 self.set = true; 356 self.value.clear(); 357 &mut self.value 358 } 359 } 360 361 impl<T: Default + Clear> SingularPtrField<T> { 362 /// Get contained data, consume self. Return default value for type if this is empty. 363 #[inline] unwrap_or_default(mut self) -> T364 pub fn unwrap_or_default(mut self) -> T { 365 if self.set { 366 self.unwrap() 367 } else if self.value.is_some() { 368 self.value.clear(); 369 *self.value.unwrap() 370 } else { 371 Default::default() 372 } 373 } 374 375 /// Initialize this object with default value. 376 /// This operation can be more efficient then construction of clear element, 377 /// because it may reuse previously contained object. 378 #[inline] set_default<'a>(&'a mut self) -> &'a mut T379 pub fn set_default<'a>(&'a mut self) -> &'a mut T { 380 self.set = true; 381 if self.value.is_some() { 382 self.value.as_mut().unwrap().clear(); 383 } else { 384 self.value = Some(Default::default()); 385 } 386 self.as_mut().unwrap() 387 } 388 } 389 390 impl<T: Default> Default for SingularField<T> { 391 #[inline] default() -> SingularField<T>392 fn default() -> SingularField<T> { 393 SingularField::none() 394 } 395 } 396 397 impl<T> Default for SingularPtrField<T> { 398 #[inline] default() -> SingularPtrField<T>399 fn default() -> SingularPtrField<T> { 400 SingularPtrField::none() 401 } 402 } 403 404 impl<T: Default> From<Option<T>> for SingularField<T> { from(o: Option<T>) -> Self405 fn from(o: Option<T>) -> Self { 406 SingularField::from_option(o) 407 } 408 } 409 410 impl<T> From<Option<T>> for SingularPtrField<T> { from(o: Option<T>) -> Self411 fn from(o: Option<T>) -> Self { 412 SingularPtrField::from_option(o) 413 } 414 } 415 416 impl<T: Clone + Default> Clone for SingularField<T> { 417 #[inline] clone(&self) -> SingularField<T>418 fn clone(&self) -> SingularField<T> { 419 if self.set { 420 SingularField::some(self.value.clone()) 421 } else { 422 SingularField::none() 423 } 424 } 425 } 426 427 impl<T: Clone> Clone for SingularPtrField<T> { 428 #[inline] clone(&self) -> SingularPtrField<T>429 fn clone(&self) -> SingularPtrField<T> { 430 if self.set { 431 SingularPtrField::some(self.as_ref().unwrap().clone()) 432 } else { 433 SingularPtrField::none() 434 } 435 } 436 } 437 438 impl<T: fmt::Debug> fmt::Debug for SingularField<T> { 439 #[inline] fmt(&self, f: &mut fmt::Formatter) -> fmt::Result440 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 441 if self.is_some() { 442 write!(f, "Some({:?})", *self.as_ref().unwrap()) 443 } else { 444 write!(f, "None") 445 } 446 } 447 } 448 449 impl<T: fmt::Debug> fmt::Debug for SingularPtrField<T> { 450 #[inline] fmt(&self, f: &mut fmt::Formatter) -> fmt::Result451 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 452 if self.is_some() { 453 write!(f, "Some({:?})", *self.as_ref().unwrap()) 454 } else { 455 write!(f, "None") 456 } 457 } 458 } 459 460 impl<T: PartialEq> PartialEq for SingularField<T> { 461 #[inline] eq(&self, other: &SingularField<T>) -> bool462 fn eq(&self, other: &SingularField<T>) -> bool { 463 self.as_ref() == other.as_ref() 464 } 465 } 466 467 impl<T: Eq> Eq for SingularField<T> {} 468 469 impl<T: PartialEq> PartialEq for SingularPtrField<T> { 470 #[inline] eq(&self, other: &SingularPtrField<T>) -> bool471 fn eq(&self, other: &SingularPtrField<T>) -> bool { 472 self.as_ref() == other.as_ref() 473 } 474 } 475 476 impl<T: Eq> Eq for SingularPtrField<T> {} 477 478 impl<T: Hash> Hash for SingularField<T> { hash<H: Hasher>(&self, state: &mut H)479 fn hash<H: Hasher>(&self, state: &mut H) { 480 self.as_ref().hash(state); 481 } 482 } 483 484 impl<T: Hash> Hash for SingularPtrField<T> { hash<H: Hasher>(&self, state: &mut H)485 fn hash<H: Hasher>(&self, state: &mut H) { 486 self.as_ref().hash(state); 487 } 488 } 489 490 impl<'a, T> IntoIterator for &'a SingularField<T> { 491 type Item = &'a T; 492 type IntoIter = option::IntoIter<&'a T>; 493 into_iter(self) -> option::IntoIter<&'a T>494 fn into_iter(self) -> option::IntoIter<&'a T> { 495 self.iter() 496 } 497 } 498 499 impl<'a, T> IntoIterator for &'a SingularPtrField<T> { 500 type Item = &'a T; 501 type IntoIter = option::IntoIter<&'a T>; 502 into_iter(self) -> option::IntoIter<&'a T>503 fn into_iter(self) -> option::IntoIter<&'a T> { 504 self.iter() 505 } 506 } 507 508 #[cfg(feature = "with-serde")] 509 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,510 fn serialize<S>( 511 &self, 512 serializer: S, 513 ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> 514 where 515 S: serde::Serializer, 516 { 517 self.as_ref().serialize(serializer) 518 } 519 } 520 521 #[cfg(feature = "with-serde")] 522 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,523 fn serialize<S>( 524 &self, 525 serializer: S, 526 ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> 527 where 528 S: serde::Serializer, 529 { 530 self.as_ref().serialize(serializer) 531 } 532 } 533 534 #[cfg(feature = "with-serde")] 535 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>,536 fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> 537 where 538 D: serde::Deserializer<'de>, 539 { 540 Option::deserialize(deserializer).map(SingularPtrField::from_option) 541 } 542 } 543 544 #[cfg(feature = "with-serde")] 545 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>,546 fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> 547 where 548 D: serde::Deserializer<'de>, 549 { 550 Option::deserialize(deserializer).map(SingularField::from_option) 551 } 552 } 553 554 #[cfg(test)] 555 mod test { 556 use super::SingularField; 557 use crate::clear::Clear; 558 559 #[test] test_set_default_clears()560 fn test_set_default_clears() { 561 #[derive(Default)] 562 struct Foo { 563 b: isize, 564 } 565 566 impl Clear for Foo { 567 fn clear(&mut self) { 568 self.b = 0; 569 } 570 } 571 572 let mut x = SingularField::some(Foo { b: 10 }); 573 x.clear(); 574 x.set_default(); 575 assert_eq!(0, x.as_ref().unwrap().b); 576 577 x.as_mut().unwrap().b = 11; 578 // without clear 579 x.set_default(); 580 assert_eq!(0, x.as_ref().unwrap().b); 581 } 582 583 #[test] unwrap_or_default()584 fn unwrap_or_default() { 585 assert_eq!( 586 "abc", 587 SingularField::some("abc".to_owned()).unwrap_or_default() 588 ); 589 assert_eq!("", SingularField::<String>::none().unwrap_or_default()); 590 let mut some = SingularField::some("abc".to_owned()); 591 some.clear(); 592 assert_eq!("", some.unwrap_or_default()); 593 } 594 } 595