Files
google-apis-rs/serde_with/macro.serde_conv.html
2024-03-05 21:06:01 +01:00

99 lines
9.1 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="Create new conversion adapters from functions"><title>serde_conv in serde_with - Rust</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/FiraSans-Regular-018c141bf0843ffd.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/FiraSans-Medium-8f9a781e4970d388.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2"><link rel="stylesheet" href="../static.files/normalize-76eba96aa4d2e634.css"><link rel="stylesheet" href="../static.files/rustdoc-ac92e1bbe349e143.css"><meta name="rustdoc-vars" data-root-path="../" data-static-root-path="../static.files/" data-current-crate="serde_with" data-themes="" data-resource-suffix="" data-rustdoc-version="1.76.0 (07dca489a 2024-02-04)" data-channel="1.76.0" data-search-js="search-2b6ce74ff89ae146.js" data-settings-js="settings-4313503d2e1961c2.js" ><script src="../static.files/storage-f2adc0d6ca4d09fb.js"></script><script defer src="sidebar-items.js"></script><script defer src="../static.files/main-305769736d49e732.js"></script><noscript><link rel="stylesheet" href="../static.files/noscript-feafe1bb7466e4bd.css"></noscript><link rel="alternate icon" type="image/png" href="../static.files/favicon-16x16-8b506e7a72182f1c.png"><link rel="alternate icon" type="image/png" href="../static.files/favicon-32x32-422f7d1d52889060.png"><link rel="icon" type="image/svg+xml" href="../static.files/favicon-2c020d218678b618.svg"></head><body class="rustdoc macro"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="mobile-topbar"><button class="sidebar-menu-toggle">&#9776;</button></nav><nav class="sidebar"><div class="sidebar-crate"><h2><a href="../serde_with/index.html">serde_with</a><span class="version">2.3.3</span></h2></div><div class="sidebar-elems"></div></nav><div class="sidebar-resizer"></div>
<main><div class="width-limiter"><nav class="sub"><form class="search-form"><span></span><div id="sidebar-button" tabindex="-1"><a href="../serde_with/all.html" title="show sidebar"></a></div><input class="search-input" name="search" aria-label="Run search in the documentation" autocomplete="off" spellcheck="false" placeholder="Click or press S to search, ? for more options…" type="search"><div id="help-button" tabindex="-1"><a href="../help.html" title="help">?</a></div><div id="settings-menu" tabindex="-1"><a href="../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../static.files/wheel-7b819b6101059cd0.svg"></a></div></form></nav><section id="main-content" class="content"><div class="main-heading"><h1>Macro <a href="index.html">serde_with</a>::<wbr><a class="macro" href="#">serde_conv</a><button id="copy-path" title="Copy item path to clipboard"><img src="../static.files/clipboard-7571035ce49a181d.svg" width="19" height="18" alt="Copy item path"></button></h1><span class="out-of-band"><a class="src" href="../src/serde_with/serde_conv.rs.html#105-150">source</a> · <button id="toggle-all-docs" title="collapse all docs">[<span>&#x2212;</span>]</button></span></div><pre class="rust item-decl"><span class="macro">macro_rules! </span>serde_conv {
(<span class="macro-nonterminal">$m</span>:ident, <span class="macro-nonterminal">$t</span>:ty, <span class="macro-nonterminal">$ser</span>:expr, <span class="macro-nonterminal">$de</span>:expr) =&gt; { ... };
(<span class="macro-nonterminal">$vis</span>:vis <span class="macro-nonterminal">$m</span>:ident, <span class="macro-nonterminal">$t</span>:ty, <span class="macro-nonterminal">$ser</span>:expr, <span class="macro-nonterminal">$de</span>:expr) =&gt; { ... };
}</pre><details class="toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p>Create new conversion adapters from functions</p>
<p>The macro lets you create a new converter, which is usable for serdes with-attribute and <code>#[serde_as]</code>.
Its main use case is to write simple converters for types, which are not serializable.
Another use-case is to change the serialization behavior if the implemented <code>Serialize</code>/<code>Deserialize</code> trait is insufficient.</p>
<p>The macro takes four arguments:</p>
<ol>
<li>The name of the converter type.
The type can be prefixed with a visibility modifies like <code>pub</code> or <code>pub(crate)</code>.
By default, the type is not marked as public (<code>pub(self)</code>).</li>
<li>The type <code>T</code> we want to extend with custom behavior.</li>
<li>A function or macro taking a <code>&amp;T</code> and returning a serializable type.</li>
<li>A function or macro taking a deserializable type and returning a <code>Result&lt;T, E&gt;</code>.
The error type <code>E</code> must implement <code>Display</code>.</li>
</ol>
<h2 id="example"><a href="#example">Example</a></h2>
<p>In this example, we write custom serialization behavior for a <code>Rgb</code> type.
We want to serialize it as a <code>[u8; 3]</code>.</p>
<div class="example-wrap"><pre class="rust rust-example-rendered"><code>
<span class="attr">#[derive(Clone, Copy, Debug, PartialEq)]
</span><span class="kw">struct </span>Rgb {
red: u8,
green: u8,
blue: u8,
}
<span class="macro">serde_with::serde_conv!</span>(
RgbAsArray,
Rgb,
|rgb: <span class="kw-2">&amp;</span>Rgb| [rgb.red, rgb.green, rgb.blue],
|value: [u8; <span class="number">3</span>]| -&gt; <span class="prelude-ty">Result</span>&lt;<span class="kw">_</span>, std::convert::Infallible&gt; {
<span class="prelude-val">Ok</span>(Rgb {
red: value[<span class="number">0</span>],
green: value[<span class="number">1</span>],
blue: value[<span class="number">2</span>],
})
}
);
<span class="comment">//////////////////////////////////////////////////
// We define some colors to be used later
</span><span class="kw">let </span>green = Rgb {red: <span class="number">0</span>, green: <span class="number">255</span>, blue: <span class="number">0</span>};
<span class="kw">let </span>orange = Rgb {red: <span class="number">255</span>, green: <span class="number">128</span>, blue: <span class="number">0</span>};
<span class="kw">let </span>pink = Rgb {red: <span class="number">255</span>, green: <span class="number">0</span>, blue: <span class="number">255</span>};
<span class="comment">//////////////////////////////////////////////////
// We can now use the `RgbAsArray` adapter with `serde_as`.
</span><span class="attr">#[serde_as]
#[derive(Debug, PartialEq, Serialize, Deserialize)]
</span><span class="kw">struct </span>Colors {
<span class="attr">#[serde_as(<span class="kw">as </span>= <span class="string">"RgbAsArray"</span>)]
</span>one_rgb: Rgb,
<span class="attr">#[serde_as(<span class="kw">as </span>= <span class="string">"Vec&lt;RgbAsArray&gt;"</span>)]
</span>rgbs_in_vec: Vec&lt;Rgb&gt;,
}
<span class="kw">let </span>data = Colors {
one_rgb: orange,
rgbs_in_vec: <span class="macro">vec!</span>[green, pink],
};
<span class="kw">let </span>json = <span class="macro">serde_json::json!</span>({
<span class="string">"one_rgb"</span>: [<span class="number">255</span>, <span class="number">128</span>, <span class="number">0</span>],
<span class="string">"rgbs_in_vec"</span>: [
[<span class="number">0</span>, <span class="number">255</span>, <span class="number">0</span>],
[<span class="number">255</span>, <span class="number">0</span>, <span class="number">255</span>]
]
});
<span class="macro">assert_eq!</span>(json, serde_json::to_value(<span class="kw-2">&amp;</span>data).unwrap());
<span class="macro">assert_eq!</span>(data, serde_json::from_value(json).unwrap());
<span class="comment">//////////////////////////////////////////////////
// The types generated by `serde_conv` is also compatible with serde's with attribute
</span><span class="attr">#[derive(Debug, PartialEq, Serialize, Deserialize)]
</span><span class="kw">struct </span>ColorsWith {
<span class="attr">#[serde(with = <span class="string">"RgbAsArray"</span>)]
</span>rgb_with: Rgb,
}
<span class="kw">let </span>data = ColorsWith {
rgb_with: pink,
};
<span class="kw">let </span>json = <span class="macro">serde_json::json!</span>({
<span class="string">"rgb_with"</span>: [<span class="number">255</span>, <span class="number">0</span>, <span class="number">255</span>]
});
<span class="macro">assert_eq!</span>(json, serde_json::to_value(<span class="kw-2">&amp;</span>data).unwrap());
<span class="macro">assert_eq!</span>(data, serde_json::from_value(json).unwrap());</code></pre></div>
</div></details></section></div></main></body></html>