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
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

#[cfg(test)]
#[cfg(feature = "serde")]
mod test;

use crate::error::Error;
use crate::marker::DataMarker;
use crate::resource::ResourceKey;
use crate::resource::ResourcePath;
use crate::yoke::trait_hack::YokeTraitHack;
use crate::yoke::*;

use alloc::rc::Rc;

use core::convert::TryFrom;
use core::fmt;
use core::fmt::Debug;
use core::marker::PhantomData;
use icu_locid::LanguageIdentifier;

/// A struct to request a certain piece of data from a data provider.
#[derive(Clone, Debug, PartialEq)]
pub struct DataRequest {
    pub resource_path: ResourcePath,
}

impl fmt::Display for DataRequest {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}/{}",
            self.resource_path.key, self.resource_path.options
        )
    }
}

/// Create a [`DataRequest`] to a particular [`ResourceKey`] with default options.
impl From<ResourceKey> for DataRequest {
    fn from(key: ResourceKey) -> Self {
        Self {
            resource_path: ResourcePath {
                key,
                options: Default::default(),
            },
        }
    }
}

impl DataRequest {
    /// Returns the [`LanguageIdentifier`] for this [`DataRequest`], or an error if it is not present.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    ///
    /// const FOO_BAR: ResourceKey = icu_provider::resource_key!(x, "foo", "bar", 1);
    ///
    /// let req_no_langid = DataRequest {
    ///     resource_path: ResourcePath {
    ///         key: FOO_BAR,
    ///         options: ResourceOptions::default(),
    ///     }
    /// };
    ///
    /// let req_with_langid = DataRequest {
    ///     resource_path: ResourcePath {
    ///         key: FOO_BAR,
    ///         options: ResourceOptions {
    ///             variant: None,
    ///             langid: Some(icu_locid_macros::langid!("ar-EG")),
    ///         },
    ///     }
    /// };
    ///
    /// assert!(matches!(req_no_langid.try_langid(), Err(DataError::NeedsLanguageIdentifier(_))));
    /// assert!(matches!(req_with_langid.try_langid(), Ok(_)));
    /// ```
    pub fn try_langid(&self) -> Result<&LanguageIdentifier, Error> {
        self.resource_path
            .options
            .langid
            .as_ref()
            .ok_or_else(|| Error::NeedsLanguageIdentifier(self.clone()))
    }
}

/// A response object containing metadata about the returned data.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct DataResponseMetadata {
    /// The language of the returned data, or None if the resource key isn't localized.
    pub data_langid: Option<LanguageIdentifier>,
}

pub(crate) enum DataPayloadInner<'data, M>
where
    M: DataMarker<'data>,
{
    RcStruct(Yoke<M::Yokeable, Rc<M::Cart>>),
    Owned(Yoke<M::Yokeable, ()>),
    RcBuf(Yoke<M::Yokeable, Rc<[u8]>>),
}

/// A container for data payloads returned from a [`DataProvider`].
///
/// [`DataPayload`] is built on top of the [`yoke`] framework, which allows for cheap, zero-copy
/// operations on data via the use of self-references. A [`DataPayload`] may be backed by one of
/// several data stores ("carts"):
///
/// 1. Fully-owned structured data ([`DataPayload::from_owned()`])
/// 2. Partially-owned structured data in an [`Rc`] ([`DataPayload::from_partial_owned()`])
/// 3. A reference-counted byte buffer ([`DataPayload::try_from_rc_buffer()`])
///
/// The type of the data stored in [`DataPayload`], and the type of the structured data store
/// (cart), is determined by the [`DataMarker`] type parameter.
///
/// ## Accessing the data
///
/// To get a reference to the data inside [`DataPayload`], use [`DataPayload::get()`]. If you need
/// to store the data for later use, it is recommended to store the [`DataPayload`] itself, not
/// the ephemeral reference, since the reference results in a short-lived lifetime.
///
/// ## Mutating the data
///
/// To modify the data stored in a [`DataPayload`], use [`DataPayload::with_mut()`].
///
/// ## Transforming the data to a different type
///
/// To transform a [`DataPayload`] to a different type backed by the same data store (cart), use
/// [`DataPayload::map_project()`] or one of its sister methods.
///
/// ## Downcasting from a trait object
///
/// If you have a [`DataPayload`]`<`[`ErasedDataStructMarker`]`>`, use [`DataPayload::downcast()`]
/// to transform it into a payload of a concrete type.
///
/// # Examples
///
/// Basic usage, using the `CowStrMarker` marker:
///
/// ```
/// use icu_provider::prelude::*;
/// use icu_provider::marker::CowStrMarker;
/// use std::borrow::Cow;
///
/// let payload = DataPayload::<CowStrMarker>::from_owned(Cow::Borrowed("Demo"));
///
/// assert_eq!("Demo", payload.get());
/// ```
///
/// [`ErasedDataStructMarker`]: crate::erased::ErasedDataStructMarker
pub struct DataPayload<'data, M>
where
    M: DataMarker<'data>,
{
    pub(crate) inner: DataPayloadInner<'data, M>,
}

impl<'data, M> Debug for DataPayload<'data, M>
where
    M: DataMarker<'data>,
    for<'a> &'a <M::Yokeable as Yokeable<'a>>::Output: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.get().fmt(f)
    }
}

/// Cloning a DataPayload is generally a cheap operation.
/// See notes in the `Clone` impl for [`Yoke`].
///
/// # Examples
///
/// ```no_run
/// use icu_provider::prelude::*;
/// use icu_provider::hello_world::*;
///
/// let resp1: DataPayload<HelloWorldV1Marker> = todo!();
/// let resp2 = resp1.clone();
/// ```
impl<'data, M> Clone for DataPayload<'data, M>
where
    M: DataMarker<'data>,
    for<'a> YokeTraitHack<<M::Yokeable as Yokeable<'a>>::Output>: Clone,
{
    fn clone(&self) -> Self {
        use DataPayloadInner::*;
        let new_inner = match &self.inner {
            RcStruct(yoke) => RcStruct(yoke.clone()),
            Owned(yoke) => Owned(yoke.clone()),
            RcBuf(yoke) => RcBuf(yoke.clone()),
        };
        Self { inner: new_inner }
    }
}

impl<'data, M> PartialEq for DataPayload<'data, M>
where
    M: DataMarker<'data>,
    for<'a> YokeTraitHack<<M::Yokeable as Yokeable<'a>>::Output>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        YokeTraitHack(self.get()).into_ref() == YokeTraitHack(other.get()).into_ref()
    }
}

impl<'data, M> Eq for DataPayload<'data, M>
where
    M: DataMarker<'data>,
    for<'a> YokeTraitHack<<M::Yokeable as Yokeable<'a>>::Output>: Eq,
{
}

#[test]
fn test_clone_eq() {
    use crate::marker::CowStrMarker;
    let p1 = DataPayload::<CowStrMarker>::from_static_str("Demo");
    let p2 = p1.clone();
    assert_eq!(p1, p2);
}

impl<'data, M> DataPayload<'data, M>
where
    M: DataMarker<'data>,
    M::Yokeable: ZeroCopyFrom<M::Cart>,
{
    /// Convert an [`Rc`]`<`[`Cart`]`>` into a [`DataPayload`].
    ///
    /// The data need not be fully owned; this constructor creates payloads bounded by `'data`.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    /// use icu_provider::hello_world::*;
    /// use std::borrow::Cow;
    /// use std::rc::Rc;
    ///
    /// let local_data = "example".to_string();
    ///
    /// let rc_struct = Rc::from(HelloWorldV1 {
    ///     message: Cow::Borrowed(&local_data),
    /// });
    ///
    /// let payload = DataPayload::<HelloWorldV1Marker>::from_partial_owned(rc_struct.clone());
    ///
    /// assert_eq!(payload.get(), &*rc_struct);
    /// ```
    ///
    /// [`Cart`]: crate::marker::DataMarker::Cart
    #[inline]
    pub fn from_partial_owned(data: Rc<M::Cart>) -> Self {
        Self {
            inner: DataPayloadInner::RcStruct(Yoke::attach_to_rc_cart(data)),
        }
    }
}

impl<'data, M> DataPayload<'data, M>
where
    M: DataMarker<'data>,
{
    /// Convert a byte buffer into a [`DataPayload`]. A function must be provided to perform the
    /// conversion. This can often be a Serde deserialization operation.
    ///
    /// This constructor creates `'static` payloads; borrowing is handled by [`Yoke`].
    ///
    /// Due to [compiler bug #84937](https://github.com/rust-lang/rust/issues/84937), call sites
    /// for this function may not compile; if this happens, use
    /// [`try_from_rc_buffer_badly()`](Self::try_from_rc_buffer_badly) instead.
    #[inline]
    pub fn try_from_rc_buffer<E>(
        rc_buffer: Rc<[u8]>,
        f: impl for<'de> FnOnce(&'de [u8]) -> Result<<M::Yokeable as Yokeable<'de>>::Output, E>,
    ) -> Result<Self, E> {
        let yoke = Yoke::try_attach_to_cart(rc_buffer, f)?;
        Ok(Self {
            inner: DataPayloadInner::RcBuf(yoke),
        })
    }

    /// Convert a byte buffer into a [`DataPayload`]. A function must be provided to perform the
    /// conversion. This can often be a Serde deserialization operation.
    ///
    /// This constructor creates `'static` payloads; borrowing is handled by [`Yoke`].
    ///
    /// For a version of this function that takes a `FnOnce` instead of a raw function pointer,
    /// see [`try_from_rc_buffer()`](Self::try_from_rc_buffer).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "provider_serde")] {
    /// use icu_provider::prelude::*;
    /// use icu_provider::hello_world::*;
    /// use std::rc::Rc;
    ///
    /// let json_text = "{\"message\":\"Hello World\"}";
    /// let json_rc_buffer: Rc<[u8]> = json_text.as_bytes().into();
    ///
    /// let payload = DataPayload::<HelloWorldV1Marker>::try_from_rc_buffer_badly(
    ///     json_rc_buffer.clone(),
    ///     |bytes| {
    ///         serde_json::from_slice(bytes)
    ///     }
    /// )
    /// .expect("JSON is valid");
    ///
    /// assert_eq!("Hello World", payload.get().message);
    /// # } // feature = "provider_serde"
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn try_from_rc_buffer_badly<E>(
        rc_buffer: Rc<[u8]>,
        f: for<'de> fn(&'de [u8]) -> Result<<M::Yokeable as Yokeable<'de>>::Output, E>,
    ) -> Result<Self, E> {
        let yoke = Yoke::try_attach_to_cart_badly(rc_buffer, f)?;
        Ok(Self {
            inner: DataPayloadInner::RcBuf(yoke),
        })
    }

    /// Convert a byte buffer into a [`DataPayload`]. A function must be provided to perform the
    /// conversion. This can often be a Serde deserialization operation.
    ///
    /// This function is similar to [`DataPayload::try_from_rc_buffer`], but it accepts a buffer
    /// that is already yoked to an Rc buffer cart.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "provider_serde")] {
    /// use icu_provider::prelude::*;
    /// use icu_provider::hello_world::*;
    /// use std::rc::Rc;
    /// use icu_provider::yoke::Yoke;
    ///
    /// let json_text = "{\"message\":\"Hello World\"}";
    /// let json_rc_buffer: Rc<[u8]> = json_text.as_bytes().into();
    ///
    /// let payload = DataPayload::<HelloWorldV1Marker>::try_from_yoked_buffer(
    ///     Yoke::attach_to_rc_cart(json_rc_buffer),
    ///     (),
    ///     |bytes, _, _| {
    ///         serde_json::from_slice(bytes)
    ///     }
    /// )
    /// .expect("JSON is valid");
    ///
    /// assert_eq!("Hello World", payload.get().message);
    /// # } // feature = "provider_serde"
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn try_from_yoked_buffer<T, E>(
        yoked_buffer: Yoke<&'static [u8], Rc<[u8]>>,
        capture: T,
        f: for<'de> fn(
            <&'static [u8] as yoke::Yokeable<'de>>::Output,
            T,
            PhantomData<&'de ()>,
        ) -> Result<<M::Yokeable as Yokeable<'de>>::Output, E>,
    ) -> Result<Self, E> {
        let yoke = yoked_buffer.try_project_with_capture(capture, f)?;
        Ok(Self {
            inner: DataPayloadInner::RcBuf(yoke),
        })
    }

    /// Convert a fully owned (`'static`) data struct into a DataPayload.
    ///
    /// This constructor creates `'static` payloads.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    /// use icu_provider::hello_world::*;
    /// use std::borrow::Cow;
    ///
    /// let local_struct = HelloWorldV1 {
    ///     message: Cow::Owned("example".to_string()),
    /// };
    ///
    /// let payload = DataPayload::<HelloWorldV1Marker>::from_owned(local_struct.clone());
    ///
    /// assert_eq!(payload.get(), &local_struct);
    /// ```
    #[inline]
    pub fn from_owned(data: M::Yokeable) -> Self {
        Self {
            inner: DataPayloadInner::Owned(Yoke::new_always_owned(data)),
        }
    }

    /// Mutate the data contained in this DataPayload.
    ///
    /// For safety, all mutation operations must take place within a helper function that cannot
    /// borrow data from the surrounding context.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use icu_provider::prelude::*;
    /// use icu_provider::marker::CowStrMarker;
    ///
    /// let mut payload = DataPayload::<CowStrMarker>::from_static_str("Hello");
    ///
    /// payload.with_mut(|s| s.to_mut().push_str(" World"));
    ///
    /// assert_eq!("Hello World", payload.get());
    /// ```
    ///
    /// To transfer data from the context into the data struct, use the `move` keyword:
    ///
    /// ```
    /// use icu_provider::prelude::*;
    /// use icu_provider::marker::CowStrMarker;
    ///
    /// let mut payload = DataPayload::<CowStrMarker>::from_static_str("Hello");
    ///
    /// let suffix = " World".to_string();
    /// payload.with_mut(move |s| s.to_mut().push_str(&suffix));
    ///
    /// assert_eq!("Hello World", payload.get());
    /// ```
    pub fn with_mut<'a, F>(&'a mut self, f: F)
    where
        F: 'static + for<'b> FnOnce(&'b mut <M::Yokeable as Yokeable<'a>>::Output),
    {
        use DataPayloadInner::*;
        match &mut self.inner {
            RcStruct(yoke) => yoke.with_mut(f),
            Owned(yoke) => yoke.with_mut(f),
            RcBuf(yoke) => yoke.with_mut(f),
        }
    }

    /// Borrows the underlying data.
    ///
    /// This function should be used like `Deref` would normally be used. For more information on
    /// why DataPayload cannot implement `Deref`, see the `yoke` crate.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::prelude::*;
    /// use icu_provider::marker::CowStrMarker;
    ///
    /// let payload = DataPayload::<CowStrMarker>::from_static_str("Demo");
    ///
    /// assert_eq!("Demo", payload.get());
    /// ```
    #[allow(clippy::needless_lifetimes)]
    pub fn get<'a>(&'a self) -> &'a <M::Yokeable as Yokeable<'a>>::Output {
        use DataPayloadInner::*;
        match &self.inner {
            RcStruct(yoke) => yoke.get(),
            Owned(yoke) => yoke.get(),
            RcBuf(yoke) => yoke.get(),
        }
    }

    /// Maps `DataPayload<M>` to `DataPayload<M2>` by projecting it with [`Yoke::project`].
    ///
    /// This is accomplished by a function that takes `M`'s data type and returns `M2`'s data
    /// type. The function takes a second argument which should be ignored. For more details,
    /// see [`Yoke::project()`].
    ///
    /// Both `M` and `M2` have the same [`DataMarker::Cart`]. This means that when using
    /// `map_project`, it is usually necessary to define a custom [`DataMarker`] type.
    ///
    /// The standard [`DataPayload::map_project()`] function moves `self` and cannot capture any
    /// data from its context. Use one of the sister methods if you need these capabilities:
    ///
    /// - [`DataPayload::map_project_cloned()`] if you don't have ownership of `self`
    /// - [`DataPayload::map_project_with_capture()`] to pass context to the mapping function
    /// - [`DataPayload::map_project_cloned_with_capture()`] to do both of these things
    ///
    /// # Examples
    ///
    /// Map from `HelloWorldV1` to a `Cow<str>` containing just the message:
    ///
    /// ```
    /// use icu_provider::hello_world::*;
    /// use icu_provider::prelude::*;
    /// use std::borrow::Cow;
    ///
    /// // A custom marker type is required when using `map_project`. The Yokeable should be the
    /// // target type, and the Cart should correspond to the type being transformed.
    ///
    /// struct HelloWorldV1MessageMarker;
    /// impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    ///     type Yokeable = Cow<'static, str>;
    ///     type Cart = HelloWorldV1<'data>;
    /// }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.map_project(|obj, _| {
    ///     obj.message
    /// });
    ///
    /// // Note: at this point, p1 has been moved.
    /// assert_eq!("Hello World", p2.get());
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn map_project<M2>(
        self,
        f: for<'a> fn(
            <M::Yokeable as Yokeable<'a>>::Output,
            PhantomData<&'a ()>,
        ) -> <M2::Yokeable as Yokeable<'a>>::Output,
    ) -> DataPayload<'data, M2>
    where
        M2: DataMarker<'data, Cart = M::Cart>,
    {
        use DataPayloadInner::*;
        match self.inner {
            RcStruct(yoke) => DataPayload {
                inner: RcStruct(yoke.project(f)),
            },
            Owned(yoke) => DataPayload {
                inner: Owned(yoke.project(f)),
            },
            RcBuf(yoke) => DataPayload {
                inner: RcBuf(yoke.project(f)),
            },
        }
    }

    /// Version of [`DataPayload::map_project()`] that borrows `self` instead of moving `self`.
    ///
    /// # Examples
    ///
    /// Same example as above, but this time, do not move out of `p1`:
    ///
    /// ***[#1061](https://github.com/unicode-org/icu4x/issues/1061): The following example
    /// requires Rust 1.57.***
    ///
    /// ```ignore
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.map_project_cloned(|obj, _| {
    ///     obj.message.clone()
    /// });
    ///
    /// // Note: p1 is still valid.
    /// assert_eq!(p1.get().message, *p2.get());
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn map_project_cloned<'this, M2>(
        &'this self,
        f: for<'a> fn(
            &'this <M::Yokeable as Yokeable<'a>>::Output,
            PhantomData<&'a ()>,
        ) -> <M2::Yokeable as Yokeable<'a>>::Output,
    ) -> DataPayload<'data, M2>
    where
        M2: DataMarker<'data, Cart = M::Cart>,
    {
        use DataPayloadInner::*;
        match &self.inner {
            RcStruct(yoke) => DataPayload {
                inner: RcStruct(yoke.project_cloned(f)),
            },
            Owned(yoke) => DataPayload {
                inner: Owned(yoke.project_cloned(f)),
            },
            RcBuf(yoke) => DataPayload {
                inner: RcBuf(yoke.project_cloned(f)),
            },
        }
    }

    /// Version of [`DataPayload::map_project()`] that moves `self` and takes a `capture`
    /// parameter to pass additional data to `f`.
    ///
    /// # Examples
    ///
    /// Capture a string from the context and append it to the message:
    ///
    /// ***[#1061](https://github.com/unicode-org/icu4x/issues/1061): The following example
    /// requires Rust 1.57.***
    ///
    /// ```ignore
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.map_project_with_capture(
    ///     "Extra",
    ///     |mut obj, capture, _| {
    ///         obj.message.to_mut().push_str(capture);
    ///         obj.message
    ///     });
    ///
    /// assert_eq!("Hello WorldExtra", p2.get());
    /// ```
    ///
    /// Prior to Rust 1.57, pass the capture by value instead of by reference:
    ///
    /// ```
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.map_project_with_capture(
    ///     "Extra".to_string(),
    ///     |mut obj, capture, _| {
    ///         obj.message.to_mut().push_str(&capture);
    ///         obj.message
    ///     });
    ///
    /// assert_eq!("Hello WorldExtra", p2.get());
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn map_project_with_capture<M2, T>(
        self,
        capture: T,
        f: for<'a> fn(
            <M::Yokeable as Yokeable<'a>>::Output,
            capture: T,
            PhantomData<&'a ()>,
        ) -> <M2::Yokeable as Yokeable<'a>>::Output,
    ) -> DataPayload<'data, M2>
    where
        M2: DataMarker<'data, Cart = M::Cart>,
    {
        use DataPayloadInner::*;
        match self.inner {
            RcStruct(yoke) => DataPayload {
                inner: RcStruct(yoke.project_with_capture(capture, f)),
            },
            Owned(yoke) => DataPayload {
                inner: Owned(yoke.project_with_capture(capture, f)),
            },
            RcBuf(yoke) => DataPayload {
                inner: RcBuf(yoke.project_with_capture(capture, f)),
            },
        }
    }

    /// Version of [`DataPayload::map_project()`] that borrows `self` and takes a `capture`
    /// parameter to pass additional data to `f`.
    ///
    /// # Examples
    ///
    /// Same example as above, but this time, do not move out of `p1`:
    ///
    /// ***[#1061](https://github.com/unicode-org/icu4x/issues/1061): The following example
    /// requires Rust 1.57.***
    ///
    /// ```ignore
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.map_project_cloned_with_capture(
    ///     "Extra",
    ///     |obj, capture, _| {
    ///         let mut message = obj.message.clone();
    ///         message.to_mut().push_str(capture);
    ///         message
    ///     });
    ///
    /// // Note: p1 is still valid, but the values no longer equal.
    /// assert_ne!(p1.get().message, *p2.get());
    /// assert_eq!("Hello WorldExtra", p2.get());
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn map_project_cloned_with_capture<'this, M2, T>(
        &'this self,
        capture: T,
        f: for<'a> fn(
            &'this <M::Yokeable as Yokeable<'a>>::Output,
            capture: T,
            PhantomData<&'a ()>,
        ) -> <M2::Yokeable as Yokeable<'a>>::Output,
    ) -> DataPayload<'data, M2>
    where
        M2: DataMarker<'data, Cart = M::Cart>,
    {
        use DataPayloadInner::*;
        match &self.inner {
            RcStruct(yoke) => DataPayload {
                inner: RcStruct(yoke.project_cloned_with_capture(capture, f)),
            },
            Owned(yoke) => DataPayload {
                inner: Owned(yoke.project_cloned_with_capture(capture, f)),
            },
            RcBuf(yoke) => DataPayload {
                inner: RcBuf(yoke.project_cloned_with_capture(capture, f)),
            },
        }
    }

    /// Version of [`DataPayload::map_project()`] that moves `self`, takes a `capture`
    /// parameter to pass additional data to `f`, and bubbles up an error from `f`.
    ///
    /// # Examples
    ///
    /// Same example as above, but bubble up an error:
    ///
    /// ***[#1061](https://github.com/unicode-org/icu4x/issues/1061): The following example
    /// requires Rust 1.57.***
    ///
    /// ```ignore
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.try_map_project_with_capture(
    ///     "Extra",
    ///     |mut obj, capture, _| {
    ///         if obj.message.is_empty() {
    ///             return Err("Example error");
    ///         }
    ///         obj.message.to_mut().push_str(&capture);
    ///         Ok(obj.message)
    ///     })?;
    ///
    /// assert_eq!("Hello WorldExtra", p2.get());
    /// # Ok::<(), &'static str>(())
    /// ```
    ///
    /// Prior to Rust 1.57, pass the capture by value instead of by reference:
    ///
    /// ```
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.try_map_project_with_capture(
    ///     "Extra".to_string(),
    ///     |mut obj, capture, _| {
    ///         if obj.message.is_empty() {
    ///             return Err(())
    ///         }
    ///         obj.message.to_mut().push_str(&capture);
    ///         Ok(obj.message)
    ///     })?;
    ///
    /// assert_eq!("Hello WorldExtra", p2.get());
    /// # Ok::<(), ()>(())
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn try_map_project_with_capture<M2, T, E>(
        self,
        capture: T,
        f: for<'a> fn(
            <M::Yokeable as Yokeable<'a>>::Output,
            capture: T,
            PhantomData<&'a ()>,
        ) -> Result<<M2::Yokeable as Yokeable<'a>>::Output, E>,
    ) -> Result<DataPayload<'data, M2>, E>
    where
        M2: DataMarker<'data, Cart = M::Cart>,
    {
        use DataPayloadInner::*;
        Ok(match self.inner {
            RcStruct(yoke) => DataPayload {
                inner: RcStruct(yoke.try_project_with_capture(capture, f)?),
            },
            Owned(yoke) => DataPayload {
                inner: Owned(yoke.try_project_with_capture(capture, f)?),
            },
            RcBuf(yoke) => DataPayload {
                inner: RcBuf(yoke.try_project_with_capture(capture, f)?),
            },
        })
    }

    /// Version of [`DataPayload::map_project()`] that borrows `self`, takes a `capture`
    /// parameter to pass additional data to `f`, and bubbles up an error from `f`.
    ///
    /// # Examples
    ///
    /// Same example as above, but bubble up an error:
    ///
    /// ***[#1061](https://github.com/unicode-org/icu4x/issues/1061): The following example
    /// requires Rust 1.57.***
    ///
    /// ```ignore
    /// // Same imports and definitions as above
    /// # use icu_provider::hello_world::*;
    /// # use icu_provider::prelude::*;
    /// # use std::borrow::Cow;
    /// # struct HelloWorldV1MessageMarker;
    /// # impl<'data> DataMarker<'data> for HelloWorldV1MessageMarker {
    /// #     type Yokeable = Cow<'static, str>;
    /// #     type Cart = HelloWorldV1<'data>;
    /// # }
    ///
    /// let p1: DataPayload<HelloWorldV1Marker> = DataPayload::from_owned(HelloWorldV1 {
    ///     message: Cow::Borrowed("Hello World")
    /// });
    ///
    /// assert_eq!("Hello World", p1.get().message);
    ///
    /// let p2: DataPayload<HelloWorldV1MessageMarker> = p1.try_map_project_cloned_with_capture(
    ///     "Extra",
    ///     |obj, capture, _| {
    ///         if obj.message.is_empty() {
    ///             return Err("Example error");
    ///         }
    ///         let mut message = obj.message.clone();
    ///         message.to_mut().push_str(capture);
    ///         Ok(message)
    ///     })?;
    ///
    /// // Note: p1 is still valid, but the values no longer equal.
    /// assert_ne!(p1.get().message, *p2.get());
    /// assert_eq!("Hello WorldExtra", p2.get());
    /// # Ok::<(), &'static str>(())
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn try_map_project_cloned_with_capture<'this, M2, T, E>(
        &'this self,
        capture: T,
        f: for<'a> fn(
            &'this <M::Yokeable as Yokeable<'a>>::Output,
            capture: T,
            PhantomData<&'a ()>,
        ) -> Result<<M2::Yokeable as Yokeable<'a>>::Output, E>,
    ) -> Result<DataPayload<'data, M2>, E>
    where
        M2: DataMarker<'data, Cart = M::Cart>,
    {
        use DataPayloadInner::*;
        Ok(match &self.inner {
            RcStruct(yoke) => DataPayload {
                inner: RcStruct(yoke.try_project_cloned_with_capture(capture, f)?),
            },
            Owned(yoke) => DataPayload {
                inner: Owned(yoke.try_project_cloned_with_capture(capture, f)?),
            },
            RcBuf(yoke) => DataPayload {
                inner: RcBuf(yoke.try_project_cloned_with_capture(capture, f)?),
            },
        })
    }
}

/// A response object containing an object as payload and metadata about it.
pub struct DataResponse<'data, M>
where
    M: DataMarker<'data>,
{
    /// Metadata about the returned object.
    pub metadata: DataResponseMetadata,

    /// The object itself; None if it was not loaded.
    pub payload: Option<DataPayload<'data, M>>,
}

impl<'data, M> DataResponse<'data, M>
where
    M: DataMarker<'data>,
{
    /// Takes ownership of the underlying payload. Error if not present.
    #[inline]
    pub fn take_payload(self) -> Result<DataPayload<'data, M>, Error> {
        self.payload.ok_or(Error::MissingPayload)
    }
}

impl<'data, M> TryFrom<DataResponse<'data, M>> for DataPayload<'data, M>
where
    M: DataMarker<'data>,
{
    type Error = Error;

    fn try_from(response: DataResponse<'data, M>) -> Result<Self, Self::Error> {
        response.take_payload()
    }
}

impl<'data, M> Debug for DataResponse<'data, M>
where
    M: DataMarker<'data>,
    for<'a> &'a <M::Yokeable as Yokeable<'a>>::Output: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "DataResponse {{ metadata: {:?}, payload: {:?} }}",
            self.metadata, self.payload
        )
    }
}

/// Cloning a DataResponse is generally a cheap operation.
/// See notes in the `Clone` impl for [`Yoke`].
///
/// # Examples
///
/// ```no_run
/// use icu_provider::prelude::*;
/// use icu_provider::hello_world::*;
///
/// let resp1: DataResponse<HelloWorldV1Marker> = todo!();
/// let resp2 = resp1.clone();
/// ```
impl<'data, M> Clone for DataResponse<'data, M>
where
    M: DataMarker<'data>,
    for<'a> YokeTraitHack<<M::Yokeable as Yokeable<'a>>::Output>: Clone,
{
    fn clone(&self) -> Self {
        Self {
            metadata: self.metadata.clone(),
            payload: self.payload.clone(),
        }
    }
}

#[test]
fn test_debug() {
    use crate::hello_world::*;
    use alloc::borrow::Cow;
    let resp = DataResponse::<HelloWorldV1Marker> {
        metadata: Default::default(),
        payload: Some(DataPayload::from_owned(HelloWorldV1 {
            message: Cow::Borrowed("foo"),
        })),
    };
    assert_eq!("DataResponse { metadata: DataResponseMetadata { data_langid: None }, payload: Some(HelloWorldV1 { message: \"foo\" }) }", format!("{:?}", resp));
}

/// A generic data provider that loads a payload of a specific type.
///
/// See examples on some of the concrete implementations:
///
/// - [`HelloWorldProvider`](crate::hello_world::HelloWorldProvider)
/// - [`StructProvider`](crate::struct_provider::StructProvider)
/// - [`InvariantDataProvider`](crate::inv::InvariantDataProvider)
pub trait DataProvider<'data, M>
where
    M: DataMarker<'data>,
{
    /// Query the provider for data, returning the result.
    ///
    /// Returns [`Ok`] if the request successfully loaded data. If data failed to load, returns an
    /// Error with more information.
    fn load_payload(&self, req: &DataRequest) -> Result<DataResponse<'data, M>, Error>;
}