serde_extract

Crates.io License

Enables turning a value that has Serialize into a Deserializer

Effectively this enables extracting a struct that implements Deserialize from a struct that implements Serialize.

Usage

TL;DR

```rust

[derive(serde_derive::Serialize)]

struct Source<'a> { a: &'a str, b: u32, }

[derive(Debug, PartialEq, serde_derive::Deserialize)]

struct Extract { b: u32, } asserteq!( Extract { b: 3 }, serdeextract::extract(&Source { a: "hello", b: 3 }).unwrap(), ); ```

More realistic example

Let's say we're in a scenario where we want to implement an SDK where results are paginated, we only need to send the original query once, but we need to re-send page_size if it was provided in the original query. Since the code that manages pagination has no knowledge of the underlying struct, and because adding a page_size argument to our make_paginated_request function would be very un-ergonomic because (let's say) it would be very rarely used and it's nicer to specify it in the same struct as the rest of the query parameters, this is a good use-case for this crate.

```rust // This will be our original query

[derive(serde_derive::Serialize)]

struct SomeSpecificRequest { fielda: &'static str, pagesize: usize, }

// Let's say makerequest is our generic function that makes a call to the server makepaginatedrequest(&SomeSpecificRequest { fielda: "hello!", page_size: 2, }) .expect("Failed to make request");

fn makepaginatedrequest( serializable: &S, ) -> Result<(), Box> { #[derive(serdederive::Deserialize)] struct MaybePageSize { pagesize: Option, } // We will reuse the page size for the subsequent paginated requests if it was // provided in the original query, so we need to extract it let pagesizeforthisrequest = serdeextract::extract::(serializable)?.pagesize; // this works: asserteq!(pagesizeforthis_request, Some(2)); // Make request... Ok(()) } ```

Limitations