pub struct DataPayload<M> where
    M: DataMarker
{ /* private fields */ }
Expand description

A container for data payloads returned from a data provider.

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. 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.

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());

Implementations

Wraps this DataPayload in an Rc and returns it as an AnyPayload.

Examples
use icu_provider::prelude::*;
use icu_provider::hello_world::*;
use std::borrow::Cow;
use std::rc::Rc;

let payload: DataPayload<HelloWorldV1Marker> =
    DataPayload::from_owned(HelloWorldV1 {
        message: Cow::Borrowed("Custom Hello World")
    });

let any_payload = payload.wrap_into_any_payload();

let payload: DataPayload<HelloWorldV1Marker> = any_payload.downcast()
    .expect("TypeId matches");
assert_eq!("Custom Hello World", payload.get().message);

Transforms a type-erased DataPayload<AnyMarker> into a concrete DataPayload<M>.

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, call sites for this function may not compile; if this happens, use try_from_rc_buffer_badly() instead.

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().

Examples
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);

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
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_zero_copy_cart(json_rc_buffer),
    (),
    |bytes, _, _| {
        serde_json::from_slice(bytes)
    }
)
.expect("JSON is valid");

assert_eq!("Hello World", payload.get().message);

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);

Convert a DataPayload that was created via DataPayload::from_owned() back into the concrete type used to construct it.

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());

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());

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().

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:

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 DataMarker for HelloWorldV1MessageMarker {
    type Yokeable = Cow<'static, str>;
}

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());

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:

// Same imports and definitions as above

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());

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:

// Same imports and definitions as above

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());

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:

// Same imports and definitions as above

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());

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:

// Same imports and definitions as above

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());

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:

// Same imports and definitions as above

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());

Converts a reference-counted byte buffer into a DataPayload<BufferMarker>.

Converts a yoked byte buffer into a DataPayload<BufferMarker>.

Converts a static byte buffer into a DataPayload<BufferMarker>.

Converts a DataPayload into something that can be baked.

See DataPayload::tokenize() for an example.

Serializes this DataPayload’s value and marker type into TokenStreams using their Bakeable implementations.

Examples
use icu_provider::prelude::*;
use icu_provider::hello_world::HelloWorldV1Marker;

// Create an example DataPayload
let payload: DataPayload<HelloWorldV1Marker> = Default::default();

let env = crabbake::CrateEnv::default();
let (tokens, marker) = payload.into_bakeable().tokenize(&env);
assert_eq!(
    quote!{
        ::icu_provider::hello_world::HelloWorldV1 {
            message: ::alloc::borrow::Cow::Borrowed("(und) Hello World"),
        }
    }.to_string(),
    tokens.to_string()
);
assert_eq!(
    quote!{ ::icu_provider::hello_world::HelloWorldV1Marker }.to_string(),
    marker.to_string()
);
assert_eq!(
    env.into_iter().collect::<BTreeSet<_>>(),
    ["icu_provider", "alloc"].into_iter().collect::<BTreeSet<_>>()
);

Given a buffer known to be in postcard-0.7 format, attempt to zero-copy deserialize it and record the amount of heap allocations that occurred.

Ideally, this number should be zero.

dhat’s profiler must be initialized before using this.

Panics

Panics if the buffer is not in postcard-0.7 format.

Make a DataPayload<CowStrMarker> from a static string slice.

Converts a DataPayload into something that can be serialized.

See DataPayload::serialize() for an example.

Serializes this DataPayload into a serializer using Serde.

Examples
use icu_provider::prelude::*;
use icu_provider::hello_world::HelloWorldV1Marker;

// Create an example DataPayload
let payload: DataPayload<HelloWorldV1Marker> = Default::default();

// Serialize the payload to a JSON string
let mut buffer: Vec<u8> = vec![];
payload.into_serializable().serialize(
    &mut <dyn erased_serde::Serializer>::erase(
        &mut serde_json::Serializer::new(&mut buffer)
    )
).expect("Serialization should succeed");
assert_eq!("{\"message\":\"(und) Hello World\"}".as_bytes(), buffer);

Trait Implementations

Cloning a DataPayload is generally a cheap operation. See notes in the Clone impl for Yoke.

Examples

use icu_provider::prelude::*;
use icu_provider::hello_world::*;

let resp1: DataPayload<HelloWorldV1Marker> = todo!();
let resp2 = resp1.clone();

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

The type returned in the event of a conversion error.

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.