cached_pair/pair.rs
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A pair (or an either) of values where one can be converted to the other.
//! This data structure caches the converted value to avoid redundant conversion.
#[cfg(test)]
mod tests;
use ::std::cell::OnceCell;
use ::std::convert::Infallible;
use ::std::fmt::Debug;
use ::std::hash::Hash;
use ::std::marker::PhantomData;
/// Re-exporting from `itertools` crate.
pub use ::itertools::EitherOrBoth;
/// A pair of values where one can be converted to the other.
///
/// # Example
///
/// ```rust
/// use cached_pair::{Pair, Converter};
/// use std::convert::Infallible;
/// use std::num::ParseIntError;
///
/// // Define a converter between i32 and String
/// #[derive(Clone)]
/// struct MyConverter;
///
/// impl Converter<i32, String> for MyConverter {
/// type ToLeftError<'a> = ParseIntError;
/// type ToRightError<'a> = Infallible;
///
/// fn convert_to_right(&self, left: &i32) -> Result<String, Self::ToRightError<'_>> {
/// Ok(left.to_string())
/// }
///
/// fn convert_to_left(&self, right: &String) -> Result<i32, Self::ToLeftError<'_>> {
/// right.parse() // parse() returns Result<i32, ParseIntError>
/// }
/// }
///
/// impl Default for MyConverter {
/// fn default() -> Self {
/// MyConverter
/// }
/// }
///
/// // Construct a pair from a left value.
/// let pair: Pair<i32, String, MyConverter> = Pair::from_left(42);
///
/// // Left value is present, but right value is not.
/// assert_eq!(pair.left_opt(), Some(&42));
/// assert_eq!(pair.right_opt(), None);
///
/// // Get a right value by converting the left value.
/// assert_eq!(pair.try_right(), Ok(&"42".to_string()));
///
/// // Once we get the right value, it is cached.
/// assert_eq!(pair.right_opt(), Some(&"42".to_string()));
///
/// // mutable access
/// let mut pair = pair;
///
/// // Get a mutable reference to the left value.
/// *pair.left_opt_mut().unwrap() = 123;
///
/// // ...then the right value is cleared.
/// assert_eq!(pair.right_opt(), None);
/// ```
#[derive(Clone)]
pub struct Pair<L, R, C = StdConverter<L, R>> {
inner: PairInner<L, R>,
converter: C,
}
impl<L, R, C> Pair<L, R, C> {
/// Creates a new pair from a left value.
pub fn from_left(left: L) -> Self
where
C: Default,
{
Self {
inner: PairInner::from_left(left),
converter: C::default(),
}
}
/// Creates a new pair from a right value.
pub fn from_right(right: R) -> Self
where
C: Default,
{
Self {
inner: PairInner::from_right(right),
converter: C::default(),
}
}
/// Creates a new pair from a left value with a custom converter.
pub fn from_left_conv(left: L, converter: C) -> Self {
Self {
inner: PairInner::from_left(left),
converter,
}
}
/// Creates a new pair from a right value with a custom converter.
pub fn from_right_conv(right: R, converter: C) -> Self {
Self {
inner: PairInner::from_right(right),
converter,
}
}
/// Returns the left value if it is available. Otherwise, returns `None`.
pub fn left_opt(&self) -> Option<&L> {
self.inner.left_opt()
}
/// Returns the right value if it is available. Otherwise, returns `None`.
pub fn right_opt(&self) -> Option<&R> {
self.inner.right_opt()
}
/// Returns a mutable reference to the left value if it is available.
/// Note: Obtaining a mutable reference will erase the right value.
pub fn left_opt_mut(&mut self) -> Option<&mut L> {
self.inner.left_opt_mut()
}
/// Returns a mutable reference to the right value if it is available.
/// Note: Obtaining a mutable reference will erase the left value.
pub fn right_opt_mut(&mut self) -> Option<&mut R> {
self.inner.right_opt_mut()
}
/// Returns a left value if it is available.
/// If the left value is not available, converts the right value using the given closure.
/// The closure must not fail.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn left_with<'a, F: FnOnce(&'a R) -> L>(&'a self, f: F) -> &'a L {
self.try_left_with(|r| Ok::<L, Infallible>(f(r))).into_ok2()
}
/// Returns a right value if it is available.
/// If the right value is not available, converts the left value using the given closure.
/// The closure must not fail.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn right_with<'a, F: FnOnce(&'a L) -> R>(&'a self, f: F) -> &'a R {
self.try_right_with(|l| Ok::<R, Infallible>(f(l)))
.into_ok2()
}
/// Returns a left value if it is available.
/// If the left value is not available, attempts to convert the right value using the given closure.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn try_left_with<'a, F: FnOnce(&'a R) -> Result<L, E>, E>(
&'a self,
f: F,
) -> Result<&'a L, E> {
self.inner.try_left_with(f)
}
/// Returns a right value if it is available.
/// If the right value is not available, attempts to convert the left value using the given closure.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn try_right_with<'a, F: FnOnce(&'a L) -> Result<R, E>, E>(
&'a self,
f: F,
) -> Result<&'a R, E> {
self.inner.try_right_with(f)
}
/// Returns a mutable reference to the left value if it is available.
/// Note: Obtaining a mutable reference will erase the right value.
/// If the left value is not available, converts the right value using the given closure.
/// The closure must not fail.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn left_mut_with<'a, F: FnOnce(&R) -> L>(&'a mut self, f: F) -> &'a mut L {
self.try_left_mut_with(|r| Ok::<L, Infallible>(f(r)))
.into_ok2()
}
/// Returns a mutable reference to the right value if it is available.
/// Note: Obtaining a mutable reference will erase the left value.
/// If the right value is not available, converts the left value using the given closure.
/// The closure must not fail.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn right_mut_with<'a, F: FnOnce(&L) -> R>(&'a mut self, f: F) -> &'a mut R {
self.try_right_mut_with(|l| Ok::<R, Infallible>(f(l)))
.into_ok2()
}
/// Returns a mutable reference to the left value if it is available.
/// Note: Obtaining a mutable reference will erase the right value.
/// If the left value is not available, attempts to convert the right value using the given closure.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn try_left_mut_with<'a, F: FnOnce(&R) -> Result<L, E>, E>(
&'a mut self,
f: F,
) -> Result<&'a mut L, E> {
self.inner.try_left_mut_with(f)
}
/// Returns a mutable reference to the right value if it is available.
/// Note: Obtaining a mutable reference will erase the left value.
/// If the right value is not available, attempts to convert the left value using the given closure.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn try_right_mut_with<'a, F: FnOnce(&L) -> Result<R, E>, E>(
&'a mut self,
f: F,
) -> Result<&'a mut R, E> {
self.inner.try_right_mut_with(f)
}
/// Consumes the pair and returns the left value.
/// If the left value is not available, converts the right value using the given closure.
/// The closure must not fail.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn into_left_with<F: FnOnce(R) -> L>(self, f: F) -> L {
self.try_into_left_with(|r| Ok::<L, Infallible>(f(r)))
.into_ok2()
}
/// Consumes the pair and returns the right value.
/// If the right value is not available, converts the left value using the given closure.
/// The closure must not fail.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn into_right_with<F: FnOnce(L) -> R>(self, f: F) -> R {
self.try_into_right_with(|l| Ok::<R, Infallible>(f(l)))
.into_ok2()
}
/// Consumes the pair and attempts to return the left value.
/// If the left value is not available, attempts to convert the right value using the given closure.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn try_into_left_with<F: FnOnce(R) -> Result<L, E>, E>(self, f: F) -> Result<L, E> {
self.inner.try_into_left_with(f)
}
/// Consumes the pair and attempts to return the right value.
/// If the right value is not available, attempts to convert the left value using the given closure.
///
/// # Safety
/// The conversion function must be consistent with the converter's behavior.
/// Inconsistent conversions may lead to invalid state.
pub unsafe fn try_into_right_with<F: FnOnce(L) -> Result<R, E>, E>(self, f: F) -> Result<R, E> {
self.inner.try_into_right_with(f)
}
/// Returns a reference to the pair as `itertools::EitherOrBoth`.
pub fn as_ref(&self) -> EitherOrBoth<&L, &R> {
match &self.inner {
PairInner::GivenLeft { left, right_cell } => match right_cell.get() {
Some(right) => EitherOrBoth::Both(left, right),
None => EitherOrBoth::Left(left),
},
PairInner::GivenRight { right, left_cell } => match left_cell.get() {
Some(left) => EitherOrBoth::Both(left, right),
None => EitherOrBoth::Right(right),
},
}
}
}
impl<L, R, C> Pair<L, R, C>
where
C: Converter<L, R>,
{
/// Returns a reference to the left value.
/// If the left value is not available, converts the right value using the converter.
/// This method will only succeed if the conversion is infallible.
pub fn left<'a>(&'a self) -> &'a L
where
C::ToLeftError<'a>: Into<Infallible>,
{
self.try_left().map_err(Into::into).into_ok2()
}
/// Returns a reference to the right value.
/// If the right value is not available, converts the left value using the converter.
/// This method will only succeed if the conversion is infallible.
pub fn right<'a>(&'a self) -> &'a R
where
C::ToRightError<'a>: Into<Infallible>,
{
self.try_right().map_err(Into::into).into_ok2()
}
/// Attempts to get a reference to the left value.
/// If the left value is not available, attempts to convert the right value using the converter.
pub fn try_left(&self) -> Result<&L, C::ToLeftError<'_>> {
self.inner
.try_left_with(|r| self.converter.convert_to_left(r))
}
/// Attempts to get a reference to the right value.
/// If the right value is not available, attempts to convert the left value using the converter.
pub fn try_right(&self) -> Result<&R, C::ToRightError<'_>> {
self.inner
.try_right_with(|l| self.converter.convert_to_right(l))
}
/// Returns a mutable reference to the left value.
/// If the left value is not available, converts the right value using the converter.
/// This method will only succeed if the conversion is infallible.
/// Note: Obtaining a mutable reference will erase the right value.
pub fn left_mut(&mut self) -> &mut L
where
for<'a> Infallible: From<C::ToLeftError<'a>>,
{
self.try_left_mut::<Infallible>().into_ok2()
}
/// Returns a mutable reference to the right value.
/// If the right value is not available, converts the left value using the converter.
/// This method will only succeed if the conversion is infallible.
/// Note: Obtaining a mutable reference will erase the left value.
pub fn right_mut(&mut self) -> &mut R
where
for<'a> Infallible: From<<C as Converter<L, R>>::ToRightError<'a>>,
{
self.try_right_mut::<Infallible>().into_ok2()
}
/// Attempts to get a mutable reference to the left value.
/// If the left value is not available, attempts to convert the right value using the converter.
/// Note: Obtaining a mutable reference will erase the right value.
pub fn try_left_mut<E>(&mut self) -> Result<&mut L, E>
where
for<'a> E: From<C::ToLeftError<'a>>,
{
self.inner
.try_left_mut_with(|r| Ok(self.converter.convert_to_left(r)?))
}
/// Attempts to get a mutable reference to the right value.
/// If the right value is not available, attempts to convert the left value using the converter.
/// Note: Obtaining a mutable reference will erase the left value.
pub fn try_right_mut<E>(&mut self) -> Result<&mut R, E>
where
for<'a> E: From<C::ToRightError<'a>>,
{
self.inner
.try_right_mut_with(|l| Ok(self.converter.convert_to_right(l)?))
}
/// Consumes the pair and returns the left value.
/// If the left value is not available, converts the right value using the converter.
/// This method will only succeed if the conversion is infallible.
pub fn into_left(self) -> L
where
for<'a> Infallible: From<<C as Converter<L, R>>::ToLeftError<'a>>,
{
self.try_into_left::<Infallible>().into_ok2()
}
/// Consumes the pair and returns the right value.
/// If the right value is not available, converts the left value using the converter.
/// This method will only succeed if the conversion is infallible.
pub fn into_right(self) -> R
where
for<'a> Infallible: From<<C as Converter<L, R>>::ToRightError<'a>>,
{
self.try_into_right::<Infallible>().into_ok2()
}
/// Attempts to consume the pair and return the left value.
/// If the left value is not available, attempts to convert the right value using the converter.
pub fn try_into_left<E>(self) -> Result<L, E>
where
for<'a> E: From<<C as Converter<L, R>>::ToLeftError<'a>>,
{
let converter = &self.converter;
self.inner
.try_into_left_with(|r| Ok(converter.convert_to_left(&r)?))
}
/// Attempts to consume the pair and return the right value.
/// If the right value is not available, attempts to convert the left value using the converter.
pub fn try_into_right<E>(self) -> Result<R, E>
where
for<'a> E: From<<C as Converter<L, R>>::ToRightError<'a>>,
{
let converter = &self.converter;
self.inner
.try_into_right_with(|l| Ok(converter.convert_to_right(&l)?))
}
}
#[derive(Clone)]
enum PairInner<L, R> {
#[doc(hidden)]
GivenLeft { left: L, right_cell: OnceCell<R> },
#[doc(hidden)]
GivenRight { left_cell: OnceCell<L>, right: R },
}
impl<L, R> PairInner<L, R> {
fn from_left(left: L) -> Self {
Self::GivenLeft {
left,
right_cell: OnceCell::new(),
}
}
fn from_right(right: R) -> Self {
Self::GivenRight {
left_cell: OnceCell::new(),
right,
}
}
fn left_opt(&self) -> Option<&L> {
match self {
PairInner::GivenLeft { left, .. } => Some(left),
PairInner::GivenRight { left_cell, .. } => left_cell.get(),
}
}
fn right_opt(&self) -> Option<&R> {
match self {
PairInner::GivenLeft { right_cell, .. } => right_cell.get(),
PairInner::GivenRight { right, .. } => Some(right),
}
}
fn left_opt_mut(&mut self) -> Option<&mut L> {
match self {
PairInner::GivenLeft { left, right_cell } => {
let _ = right_cell.take();
Some(left)
}
PairInner::GivenRight { left_cell, .. } => {
if left_cell.get().is_some() {
let left = left_cell.take().unwrap();
*self = Self::from_left(left);
if let PairInner::GivenLeft { left, .. } = self {
Some(left)
} else {
unreachable!()
}
} else {
None
}
}
}
}
fn right_opt_mut(&mut self) -> Option<&mut R> {
match self {
PairInner::GivenLeft { right_cell, .. } => {
if right_cell.get().is_some() {
let right = right_cell.take().unwrap();
*self = Self::from_right(right);
if let PairInner::GivenRight { right, .. } = self {
Some(right)
} else {
unreachable!()
}
} else {
None
}
}
PairInner::GivenRight { right, left_cell } => {
let _ = left_cell.take();
Some(right)
}
}
}
fn try_into_left_with<F: FnOnce(R) -> Result<L, E>, E>(self, f: F) -> Result<L, E> {
match self {
PairInner::GivenLeft { left, .. } => Ok(left),
PairInner::GivenRight {
right,
mut left_cell,
} => left_cell.take().map_or_else(|| f(right), Ok),
}
}
fn try_into_right_with<F: FnOnce(L) -> Result<R, E>, E>(self, f: F) -> Result<R, E> {
match self {
PairInner::GivenRight { right, .. } => Ok(right),
PairInner::GivenLeft {
left,
mut right_cell,
} => right_cell.take().map_or_else(|| f(left), Ok),
}
}
fn try_left_mut_with<F: FnOnce(&R) -> Result<L, E>, E>(&mut self, f: F) -> Result<&mut L, E> {
match self {
PairInner::GivenLeft { left, right_cell } => {
let _ = right_cell.take();
Ok(left)
}
PairInner::GivenRight { left_cell, right } => {
if left_cell.get().is_none() {
let left = f(right)?;
*self = Self::from_left(left);
if let PairInner::GivenLeft { left, .. } = self {
Ok(left)
} else {
unreachable!()
}
} else {
let left = left_cell.take().unwrap();
*self = Self::from_left(left);
if let PairInner::GivenLeft { left, .. } = self {
Ok(left)
} else {
unreachable!()
}
}
}
}
}
fn try_left_with<'a, F: FnOnce(&'a R) -> Result<L, E>, E>(&'a self, f: F) -> Result<&'a L, E> {
match self {
PairInner::GivenLeft { left, .. } => Ok(left),
PairInner::GivenRight { left_cell, right } => left_cell.get_or_try_init2(|| f(right)),
}
}
fn try_right_mut_with<F: FnOnce(&L) -> Result<R, E>, E>(&mut self, f: F) -> Result<&mut R, E> {
match self {
PairInner::GivenLeft { left, right_cell } => {
if right_cell.get().is_none() {
let right = f(left)?;
*self = Self::from_right(right);
if let PairInner::GivenRight { right, .. } = self {
Ok(right)
} else {
unreachable!()
}
} else {
let right = right_cell.take().unwrap();
*self = Self::from_right(right);
if let PairInner::GivenRight { right, .. } = self {
Ok(right)
} else {
unreachable!()
}
}
}
PairInner::GivenRight { right, left_cell } => {
let _ = left_cell.take();
Ok(right)
}
}
}
fn try_right_with<'a, F: FnOnce(&'a L) -> Result<R, E>, E>(&'a self, f: F) -> Result<&'a R, E> {
match self {
PairInner::GivenLeft { left, right_cell } => right_cell.get_or_try_init2(|| f(left)),
PairInner::GivenRight { right, .. } => Ok(right),
}
}
}
impl<L: Debug, R: Debug, C> Debug for Pair<L, R, C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Pair")
.field(&self.left_opt())
.field(&self.right_opt())
.finish()
}
}
impl<L: PartialEq, R: PartialEq, C> PartialEq for Pair<L, R, C> {
fn eq(&self, other: &Self) -> bool {
(self.left_opt(), self.right_opt()) == (other.left_opt(), other.right_opt())
}
}
impl<L: Hash, R: Hash, C> Hash for Pair<L, R, C> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.left_opt().hash(state);
self.right_opt().hash(state);
}
}
impl<L, R, C> From<Pair<L, R, C>> for EitherOrBoth<L, R> {
fn from(pair: Pair<L, R, C>) -> Self {
let (left, right) = match pair.inner {
PairInner::GivenLeft {
left,
mut right_cell,
} => (Some(left), right_cell.take()),
PairInner::GivenRight {
mut left_cell,
right,
} => (left_cell.take(), Some(right)),
};
match (left, right) {
(Some(left), Some(right)) => EitherOrBoth::Both(left, right),
(Some(left), None) => EitherOrBoth::Left(left),
(None, Some(right)) => EitherOrBoth::Right(right),
(None, None) => unreachable!(),
}
}
}
/// A trait for converting between two types.
/// This trait is used by [`Pair`] to convert between its left and right values.
///
/// # Example
///
/// ```rust
/// use cached_pair::Converter;
/// use std::convert::Infallible;
/// use std::num::ParseIntError;
///
/// struct MyConverter;
///
/// impl Converter<i32, String> for MyConverter {
/// type ToLeftError<'a> = ParseIntError;
/// type ToRightError<'a> = Infallible;
///
/// fn convert_to_right(&self, left: &i32) -> Result<String, Self::ToRightError<'_>> {
/// Ok(left.to_string())
/// }
///
/// fn convert_to_left(&self, right: &String) -> Result<i32, Self::ToLeftError<'_>> {
/// right.parse()
/// }
/// }
/// ```
pub trait Converter<L, R> {
/// The error type returned when converting from right to left.
type ToLeftError<'a>
where
R: 'a;
/// The error type returned when converting from left to right.
type ToRightError<'a>
where
L: 'a;
/// Converts a reference to a right value into a left value.
fn convert_to_left<'a>(&self, right: &'a R) -> Result<L, Self::ToLeftError<'a>>;
/// Converts a reference to a left value into a right value.
fn convert_to_right<'a>(&self, left: &'a L) -> Result<R, Self::ToRightError<'a>>;
}
/// A standard converter that uses the `TryFrom` trait for conversions.
/// This is the default converter used by [`Pair`] when no converter is specified.
/// Note that this converter requires the `TryFrom<&L> for R` and `TryFrom<&R> for L`
/// implementations, which are not typically implemented by the library authors.
#[derive(::derive_more::Debug, Clone, Default)]
pub struct StdConverter<L, R>(#[debug(skip)] PhantomData<(L, R)>);
impl<L, R> Converter<L, R> for StdConverter<L, R>
where
for<'a> &'a L: TryInto<R>,
for<'a> &'a R: TryInto<L>,
{
type ToLeftError<'a>
= <&'a R as TryInto<L>>::Error
where
R: 'a;
type ToRightError<'a>
= <&'a L as TryInto<R>>::Error
where
L: 'a;
fn convert_to_left<'a>(&self, right: &'a R) -> Result<L, Self::ToLeftError<'a>> {
right.try_into()
}
fn convert_to_right<'a>(&self, left: &'a L) -> Result<R, Self::ToRightError<'a>> {
left.try_into()
}
}
/// A converter that uses closures for conversions.
/// This is useful when you want to provide custom conversion logic without implementing the `TryFrom` trait.
#[derive(::derive_more::Debug, Clone)]
pub struct FnConverter<L, R, F, G, EL = Infallible, ER = Infallible> {
#[debug(skip)]
to_left: F,
#[debug(skip)]
to_right: G,
#[debug(skip)]
_phantom: PhantomData<(L, R, EL, ER)>,
}
/// Creates a new [`FnConverter`] from two functions.
/// This is a convenience function for creating a converter that uses closures for conversions.
/// Note that the type of the converter is not descriptable if you use the closure as an argument.
/// Use [`boxed_fn_converter`] instead if you need a descriptable type.
///
/// # Example
///
/// ```rust
/// use cached_pair::{Pair, fn_converter};
/// use std::convert::Infallible;
/// use std::num::TryFromIntError;
///
/// let converter = fn_converter(
/// |i: &i32| -> Result<u8, TryFromIntError> { (*i - 10).try_into() },
/// |u: &u8| -> Result<i32, Infallible> { Ok((*u as i32) + 10) },
/// );
///
/// let pair = Pair::from_right_conv(52i32, converter);
/// assert_eq!(pair.try_left(), Ok(&42u8));
/// ```
pub fn fn_converter<L, R, F, G, EL, ER>(f: F, g: G) -> FnConverter<L, R, F, G, EL, ER>
where
for<'a> F: Fn(&'a R) -> Result<L, EL>,
for<'a> G: Fn(&'a L) -> Result<R, ER>,
{
FnConverter {
to_left: f,
to_right: g,
_phantom: PhantomData,
}
}
impl<L, R, F, G, EL, ER> Converter<L, R> for FnConverter<L, R, F, G, EL, ER>
where
for<'a> F: Fn(&'a R) -> Result<L, EL>,
for<'a> G: Fn(&'a L) -> Result<R, ER>,
{
type ToLeftError<'a>
= EL
where
R: 'a;
type ToRightError<'a>
= ER
where
L: 'a;
fn convert_to_left<'a>(&self, right: &'a R) -> Result<L, Self::ToLeftError<'a>> {
(self.to_left)(right)
}
fn convert_to_right<'a>(&self, left: &'a L) -> Result<R, Self::ToRightError<'a>> {
(self.to_right)(left)
}
}
/// A converter that uses boxed closures for conversions.
/// This is similar to [`FnConverter`] but uses trait objects,
/// making its type always descriptable.
///
/// # Example
///
/// ```rust
/// use cached_pair::{Pair, boxed_fn_converter};
/// use std::convert::Infallible;
/// use std::num::TryFromIntError;
///
/// let converter = boxed_fn_converter(
/// |i: &i32| -> Result<u8, TryFromIntError> { (*i - 100).try_into() },
/// |u: &u8| -> Result<i32, Infallible> { Ok((*u as i32) + 100) },
/// );
///
/// let pair = Pair::from_right_conv(142i32, converter);
/// assert_eq!(pair.try_left(), Ok(&42u8));
/// ```
#[derive(::derive_more::Debug)]
pub struct BoxedFnConverter<L, R, EL = Infallible, ER = Infallible> {
#[debug(skip)]
to_left: Box<dyn for<'a> Fn(&'a R) -> Result<L, EL>>,
#[debug(skip)]
to_right: Box<dyn for<'a> Fn(&'a L) -> Result<R, ER>>,
#[debug(skip)]
_phantom: PhantomData<(L, R)>,
}
/// Creates a new [`BoxedFnConverter`] from two closures.
/// This is a convenience function for creating a converter that uses boxed closures for conversions.
///
/// # Example
///
/// ```rust
/// use cached_pair::{Pair, boxed_fn_converter};
/// use std::convert::Infallible;
/// use std::num::TryFromIntError;
///
/// let converter = boxed_fn_converter(
/// |i: &i32| -> Result<u8, TryFromIntError> { (*i - 100).try_into() },
/// |u: &u8| -> Result<i32, Infallible> { Ok((*u as i32) + 100) },
/// );
///
/// let pair = Pair::from_right_conv(142i32, converter);
/// assert_eq!(pair.try_left(), Ok(&42u8));
/// ```
pub fn boxed_fn_converter<L, R, F, G, EL, ER>(f: F, g: G) -> BoxedFnConverter<L, R, EL, ER>
where
for<'a> F: Fn(&'a R) -> Result<L, EL> + 'static,
for<'a> G: Fn(&'a L) -> Result<R, ER> + 'static,
{
BoxedFnConverter {
to_left: Box::new(f),
to_right: Box::new(g),
_phantom: PhantomData,
}
}
impl<L, R, EL, ER> Converter<L, R> for BoxedFnConverter<L, R, EL, ER> {
type ToLeftError<'a>
= EL
where
R: 'a;
type ToRightError<'a>
= ER
where
L: 'a;
fn convert_to_left<'a>(&self, right: &'a R) -> Result<L, Self::ToLeftError<'a>> {
(self.to_left)(right)
}
fn convert_to_right<'a>(&self, left: &'a L) -> Result<R, Self::ToRightError<'a>> {
(self.to_right)(left)
}
}
trait OnceCellExt<T> {
fn get_or_try_init2<E, F>(&self, init: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>;
}
impl<T> OnceCellExt<T> for OnceCell<T> {
fn get_or_try_init2<E, F>(&self, init: F) -> Result<&T, E>
where
F: FnOnce() -> Result<T, E>,
{
match self.get() {
Some(v) => Ok(v),
None => {
let v = init()?;
let _ = self.set(v); // We are sure the `set` will succeed.
Ok(unsafe { self.get().unwrap_unchecked() })
}
}
}
}
trait ResultExt<T, E> {
fn into_ok2(self) -> T
where
E: Into<Infallible>;
}
impl<T, E> ResultExt<T, E> for Result<T, E> {
#[allow(unreachable_code)]
fn into_ok2(self) -> T
where
E: Into<Infallible>,
{
match self {
Ok(v) => v,
Err(e) => match e.into() {},
}
}
}