147 lines
20 KiB
HTML
147 lines
20 KiB
HTML
<!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="`DeserializeSeed` is the stateful form of the `Deserialize` trait. If you ever find yourself looking for a way to pass data into a `Deserialize` impl, this trait is the way to do it."><title>DeserializeSeed in serde::de - Rust</title><script>if(window.location.protocol!=="file:")document.head.insertAdjacentHTML("beforeend","SourceSerif4-Regular-6b053e98.ttf.woff2,FiraSans-Italic-81dc35de.woff2,FiraSans-Regular-0fe48ade.woff2,FiraSans-MediumItalic-ccf7e434.woff2,FiraSans-Medium-e1aa3f0a.woff2,SourceCodePro-Regular-8badfe75.ttf.woff2,SourceCodePro-Semibold-aa29a496.ttf.woff2".split(",").map(f=>`<link rel="preload" as="font" type="font/woff2"href="../../static.files/${f}">`).join(""))</script><link rel="stylesheet" href="../../static.files/normalize-9960930a.css"><link rel="stylesheet" href="../../static.files/rustdoc-ca0dd0c4.css"><meta name="rustdoc-vars" data-root-path="../../" data-static-root-path="../../static.files/" data-current-crate="serde" data-themes="" data-resource-suffix="" data-rustdoc-version="1.93.1 (01f6ddf75 2026-02-11) (Arch Linux rust 1:1.93.1-1)" data-channel="1.93.1" data-search-js="search-9e2438ea.js" data-stringdex-js="stringdex-a3946164.js" data-settings-js="settings-c38705f0.js" ><script src="../../static.files/storage-e2aeef58.js"></script><script defer src="sidebar-items.js"></script><script defer src="../../static.files/main-a410ff4d.js"></script><noscript><link rel="stylesheet" href="../../static.files/noscript-263c88ec.css"></noscript><link rel="alternate icon" type="image/png" href="../../static.files/favicon-32x32-eab170b8.png"><link rel="icon" type="image/svg+xml" href="../../static.files/favicon-044be391.svg"></head><body class="rustdoc trait"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><rustdoc-topbar><h2><a href="#">DeserializeSeed</a></h2></rustdoc-topbar><nav class="sidebar"><div class="sidebar-crate"><h2><a href="../../serde/index.html">serde</a><span class="version">1.0.228</span></h2></div><div class="sidebar-elems"><section id="rustdoc-toc"><h2 class="location"><a href="#">Deserialize<wbr>Seed</a></h2><h3><a href="#">Sections</a></h3><ul class="block top-toc"><li><a href="#lifetime" title="Lifetime">Lifetime</a></li><li><a href="#example" title="Example">Example</a></li></ul><h3><a href="#required-associated-types">Required Associated Types</a></h3><ul class="block"><li><a href="#associatedtype.Value" title="Value">Value</a></li></ul><h3><a href="#required-methods">Required Methods</a></h3><ul class="block"><li><a href="#tymethod.deserialize" title="deserialize">deserialize</a></li></ul><h3><a href="#foreign-impls">Implementations on Foreign Types</a></h3><ul class="block"><li><a href="#impl-DeserializeSeed%3C'de%3E-for-PhantomData%3CT%3E" title="PhantomData<T>">PhantomData<T></a></li></ul><h3><a href="#dyn-compatibility">Dyn Compatibility</a></h3><h3><a href="#implementors">Implementors</a></h3></section><div id="rustdoc-modnav"><h2><a href="index.html">In serde::<wbr>de</a></h2></div></div></nav><div class="sidebar-resizer" title="Drag to resize sidebar"></div><main><div class="width-limiter"><section id="main-content" class="content"><div class="main-heading"><div class="rustdoc-breadcrumbs"><a href="../index.html">serde</a>::<wbr><a href="index.html">de</a></div><h1>Trait <span class="trait">Deserialize<wbr>Seed</span> <button id="copy-path" title="Copy item path to clipboard">Copy item path</button></h1><rustdoc-toolbar></rustdoc-toolbar><span class="sub-heading"><a class="src" href="../../src/serde_core/de/mod.rs.html#803">Source</a> </span></div><pre class="rust item-decl"><code>pub trait DeserializeSeed<'de>: <a class="trait" href="https://doc.rust-lang.org/1.93.1/core/marker/trait.Sized.html" title="trait core::marker::Sized">Sized</a> {
|
|
type <a href="#associatedtype.Value" class="associatedtype">Value</a>;
|
|
|
|
// Required method
|
|
fn <a href="#tymethod.deserialize" class="fn">deserialize</a><D>(
|
|
self,
|
|
deserializer: D,
|
|
) -> <a class="enum" href="https://doc.rust-lang.org/1.93.1/core/result/enum.Result.html" title="enum core::result::Result">Result</a><Self::<a class="associatedtype" href="trait.DeserializeSeed.html#associatedtype.Value" title="type serde::de::DeserializeSeed::Value">Value</a>, <D as <a class="trait" href="../trait.Deserializer.html" title="trait serde::Deserializer">Deserializer</a><'de>>::<a class="associatedtype" href="../trait.Deserializer.html#associatedtype.Error" title="type serde::Deserializer::Error">Error</a>>
|
|
<span class="where">where D: <a class="trait" href="../trait.Deserializer.html" title="trait serde::Deserializer">Deserializer</a><'de></span>;
|
|
}</code></pre><details class="toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p><code>DeserializeSeed</code> is the stateful form of the <code>Deserialize</code> trait. If you
|
|
ever find yourself looking for a way to pass data into a <code>Deserialize</code> impl,
|
|
this trait is the way to do it.</p>
|
|
<p>As one example of stateful deserialization consider deserializing a JSON
|
|
array into an existing buffer. Using the <code>Deserialize</code> trait we could
|
|
deserialize a JSON array into a <code>Vec<T></code> but it would be a freshly allocated
|
|
<code>Vec<T></code>; there is no way for <code>Deserialize</code> to reuse a previously allocated
|
|
buffer. Using <code>DeserializeSeed</code> instead makes this possible as in the
|
|
example code below.</p>
|
|
<p>The canonical API for stateless deserialization looks like this:</p>
|
|
|
|
<div class="example-wrap edition"><a href="#" class="tooltip" title="This example runs with edition 2021">ⓘ</a><pre class="rust rust-example-rendered"><code><span class="kw">fn </span>func<<span class="lifetime">'de</span>, T: Deserialize<<span class="lifetime">'de</span>>>() -> <span class="prelude-ty">Result</span><T, Error></code></pre></div>
|
|
<p>Adjusting an API like this to support stateful deserialization is a matter
|
|
of accepting a seed as input:</p>
|
|
|
|
<div class="example-wrap edition"><a href="#" class="tooltip" title="This example runs with edition 2021">ⓘ</a><pre class="rust rust-example-rendered"><code><span class="kw">fn </span>func_seed<<span class="lifetime">'de</span>, T: DeserializeSeed<<span class="lifetime">'de</span>>>(seed: T) -> <span class="prelude-ty">Result</span><T::Value, Error></code></pre></div>
|
|
<p>In practice the majority of deserialization is stateless. An API expecting a
|
|
seed can be appeased by passing <code>std::marker::PhantomData</code> as a seed in the
|
|
case of stateless deserialization.</p>
|
|
<h2 id="lifetime"><a class="doc-anchor" href="#lifetime">§</a>Lifetime</h2>
|
|
<p>The <code>'de</code> lifetime of this trait is the lifetime of data that may be
|
|
borrowed by <code>Self::Value</code> when deserialized. See the page <a href="https://serde.rs/lifetimes.html">Understanding
|
|
deserializer lifetimes</a> for a more detailed explanation of these lifetimes.</p>
|
|
<h2 id="example"><a class="doc-anchor" href="#example">§</a>Example</h2>
|
|
<p>Suppose we have JSON that looks like <code>[[1, 2], [3, 4, 5], [6]]</code> and we need
|
|
to deserialize it into a flat representation like <code>vec![1, 2, 3, 4, 5, 6]</code>.
|
|
Allocating a brand new <code>Vec<T></code> for each subarray would be slow. Instead we
|
|
would like to allocate a single <code>Vec<T></code> and then deserialize each subarray
|
|
into it. This requires stateful deserialization using the <code>DeserializeSeed</code>
|
|
trait.</p>
|
|
|
|
<div class="example-wrap edition"><a href="#" class="tooltip" title="This example runs with edition 2021">ⓘ</a><pre class="rust rust-example-rendered"><code><span class="kw">use </span>serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
|
|
<span class="kw">use </span>std::fmt;
|
|
<span class="kw">use </span>std::marker::PhantomData;
|
|
|
|
<span class="comment">// A DeserializeSeed implementation that uses stateful deserialization to
|
|
// append array elements onto the end of an existing vector. The preexisting
|
|
// state ("seed") in this case is the Vec<T>. The `deserialize` method of
|
|
// `ExtendVec` will be traversing the inner arrays of the JSON input and
|
|
// appending each integer into the existing Vec.
|
|
</span><span class="kw">struct </span>ExtendVec<<span class="lifetime">'a</span>, T: <span class="lifetime">'a</span>>(<span class="kw-2">&</span><span class="lifetime">'a </span><span class="kw-2">mut </span>Vec<T>);
|
|
|
|
<span class="kw">impl</span><<span class="lifetime">'de</span>, <span class="lifetime">'a</span>, T> DeserializeSeed<<span class="lifetime">'de</span>> <span class="kw">for </span>ExtendVec<<span class="lifetime">'a</span>, T>
|
|
<span class="kw">where
|
|
</span>T: Deserialize<<span class="lifetime">'de</span>>,
|
|
{
|
|
<span class="comment">// The return type of the `deserialize` method. This implementation
|
|
// appends onto an existing vector but does not create any new data
|
|
// structure, so the return type is ().
|
|
</span><span class="kw">type </span>Value = ();
|
|
|
|
<span class="kw">fn </span>deserialize<D>(<span class="self">self</span>, deserializer: D) -> <span class="prelude-ty">Result</span><<span class="self">Self</span>::Value, D::Error>
|
|
<span class="kw">where
|
|
</span>D: Deserializer<<span class="lifetime">'de</span>>,
|
|
{
|
|
<span class="comment">// Visitor implementation that will walk an inner array of the JSON
|
|
// input.
|
|
</span><span class="kw">struct </span>ExtendVecVisitor<<span class="lifetime">'a</span>, T: <span class="lifetime">'a</span>>(<span class="kw-2">&</span><span class="lifetime">'a </span><span class="kw-2">mut </span>Vec<T>);
|
|
|
|
<span class="kw">impl</span><<span class="lifetime">'de</span>, <span class="lifetime">'a</span>, T> Visitor<<span class="lifetime">'de</span>> <span class="kw">for </span>ExtendVecVisitor<<span class="lifetime">'a</span>, T>
|
|
<span class="kw">where
|
|
</span>T: Deserialize<<span class="lifetime">'de</span>>,
|
|
{
|
|
<span class="kw">type </span>Value = ();
|
|
|
|
<span class="kw">fn </span>expecting(<span class="kw-2">&</span><span class="self">self</span>, formatter: <span class="kw-2">&mut </span>fmt::Formatter) -> fmt::Result {
|
|
<span class="macro">write!</span>(formatter, <span class="string">"an array of integers"</span>)
|
|
}
|
|
|
|
<span class="kw">fn </span>visit_seq<A>(<span class="self">self</span>, <span class="kw-2">mut </span>seq: A) -> <span class="prelude-ty">Result</span><(), A::Error>
|
|
<span class="kw">where
|
|
</span>A: SeqAccess<<span class="lifetime">'de</span>>,
|
|
{
|
|
<span class="comment">// Decrease the number of reallocations if there are many elements
|
|
</span><span class="kw">if let </span><span class="prelude-val">Some</span>(size_hint) = seq.size_hint() {
|
|
<span class="self">self</span>.<span class="number">0</span>.reserve(size_hint);
|
|
}
|
|
|
|
<span class="comment">// Visit each element in the inner array and push it onto
|
|
// the existing vector.
|
|
</span><span class="kw">while let </span><span class="prelude-val">Some</span>(elem) = seq.next_element()<span class="question-mark">? </span>{
|
|
<span class="self">self</span>.<span class="number">0</span>.push(elem);
|
|
}
|
|
<span class="prelude-val">Ok</span>(())
|
|
}
|
|
}
|
|
|
|
deserializer.deserialize_seq(ExtendVecVisitor(<span class="self">self</span>.<span class="number">0</span>))
|
|
}
|
|
}
|
|
|
|
<span class="comment">// Visitor implementation that will walk the outer array of the JSON input.
|
|
</span><span class="kw">struct </span>FlattenedVecVisitor<T>(PhantomData<T>);
|
|
|
|
<span class="kw">impl</span><<span class="lifetime">'de</span>, T> Visitor<<span class="lifetime">'de</span>> <span class="kw">for </span>FlattenedVecVisitor<T>
|
|
<span class="kw">where
|
|
</span>T: Deserialize<<span class="lifetime">'de</span>>,
|
|
{
|
|
<span class="comment">// This Visitor constructs a single Vec<T> to hold the flattened
|
|
// contents of the inner arrays.
|
|
</span><span class="kw">type </span>Value = Vec<T>;
|
|
|
|
<span class="kw">fn </span>expecting(<span class="kw-2">&</span><span class="self">self</span>, formatter: <span class="kw-2">&mut </span>fmt::Formatter) -> fmt::Result {
|
|
<span class="macro">write!</span>(formatter, <span class="string">"an array of arrays"</span>)
|
|
}
|
|
|
|
<span class="kw">fn </span>visit_seq<A>(<span class="self">self</span>, <span class="kw-2">mut </span>seq: A) -> <span class="prelude-ty">Result</span><Vec<T>, A::Error>
|
|
<span class="kw">where
|
|
</span>A: SeqAccess<<span class="lifetime">'de</span>>,
|
|
{
|
|
<span class="comment">// Create a single Vec to hold the flattened contents.
|
|
</span><span class="kw">let </span><span class="kw-2">mut </span>vec = Vec::new();
|
|
|
|
<span class="comment">// Each iteration through this loop is one inner array.
|
|
</span><span class="kw">while let </span><span class="prelude-val">Some</span>(()) = seq.next_element_seed(ExtendVec(<span class="kw-2">&mut </span>vec))<span class="question-mark">? </span>{
|
|
<span class="comment">// Nothing to do; inner array has been appended into `vec`.
|
|
</span>}
|
|
|
|
<span class="comment">// Return the finished vec.
|
|
</span><span class="prelude-val">Ok</span>(vec)
|
|
}
|
|
}
|
|
|
|
<span class="kw">let </span>visitor = FlattenedVecVisitor(PhantomData);
|
|
<span class="kw">let </span>flattened: Vec<u64> = deserializer.deserialize_seq(visitor)<span class="question-mark">?</span>;</code></pre></div></div></details><h2 id="required-associated-types" class="section-header">Required Associated Types<a href="#required-associated-types" class="anchor">§</a></h2><div class="methods"><details class="toggle" open><summary><section id="associatedtype.Value" class="method"><a class="src rightside" href="../../src/serde_core/de/mod.rs.html#805">Source</a><h4 class="code-header">type <a href="#associatedtype.Value" class="associatedtype">Value</a></h4></section></summary><div class="docblock"><p>The type produced by using this seed.</p>
|
|
</div></details></div><h2 id="required-methods" class="section-header">Required Methods<a href="#required-methods" class="anchor">§</a></h2><div class="methods"><details class="toggle method-toggle" open><summary><section id="tymethod.deserialize" class="method"><a class="src rightside" href="../../src/serde_core/de/mod.rs.html#809-811">Source</a><h4 class="code-header">fn <a href="#tymethod.deserialize" class="fn">deserialize</a><D>(
|
|
self,
|
|
deserializer: D,
|
|
) -> <a class="enum" href="https://doc.rust-lang.org/1.93.1/core/result/enum.Result.html" title="enum core::result::Result">Result</a><Self::<a class="associatedtype" href="trait.DeserializeSeed.html#associatedtype.Value" title="type serde::de::DeserializeSeed::Value">Value</a>, <D as <a class="trait" href="../trait.Deserializer.html" title="trait serde::Deserializer">Deserializer</a><'de>>::<a class="associatedtype" href="../trait.Deserializer.html#associatedtype.Error" title="type serde::Deserializer::Error">Error</a>><div class="where">where
|
|
D: <a class="trait" href="../trait.Deserializer.html" title="trait serde::Deserializer">Deserializer</a><'de>,</div></h4></section></summary><div class="docblock"><p>Equivalent to the more common <code>Deserialize::deserialize</code> method, except
|
|
with some initial piece of data (the seed) passed in.</p>
|
|
</div></details></div><h2 id="dyn-compatibility" class="section-header">Dyn Compatibility<a href="#dyn-compatibility" class="anchor">§</a></h2><div class="dyn-compatibility-info"><p>This trait is <b>not</b> <a href="https://doc.rust-lang.org/1.93.1/reference/items/traits.html#dyn-compatibility">dyn compatible</a>.</p><p><i>In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.</i></p></div><h2 id="foreign-impls" class="section-header">Implementations on Foreign Types<a href="#foreign-impls" class="anchor">§</a></h2><details class="toggle implementors-toggle"><summary><section id="impl-DeserializeSeed%3C'de%3E-for-PhantomData%3CT%3E" class="impl"><a class="src rightside" href="../../src/serde_core/de/mod.rs.html#814-816">Source</a><a href="#impl-DeserializeSeed%3C'de%3E-for-PhantomData%3CT%3E" class="anchor">§</a><h3 class="code-header">impl<'de, T> <a class="trait" href="trait.DeserializeSeed.html" title="trait serde::de::DeserializeSeed">DeserializeSeed</a><'de> for <a class="struct" href="https://doc.rust-lang.org/1.93.1/core/marker/struct.PhantomData.html" title="struct core::marker::PhantomData">PhantomData</a><T><div class="where">where
|
|
T: <a class="trait" href="../trait.Deserialize.html" title="trait serde::Deserialize">Deserialize</a><'de>,</div></h3></section></summary><div class="impl-items"><section id="associatedtype.Value-1" class="associatedtype trait-impl"><a class="src rightside" href="../../src/serde_core/de/mod.rs.html#818">Source</a><a href="#associatedtype.Value-1" class="anchor">§</a><h4 class="code-header">type <a href="#associatedtype.Value" class="associatedtype">Value</a> = T</h4></section><section id="method.deserialize" class="method trait-impl"><a class="src rightside" href="../../src/serde_core/de/mod.rs.html#821-823">Source</a><a href="#method.deserialize" class="anchor">§</a><h4 class="code-header">fn <a href="#tymethod.deserialize" class="fn">deserialize</a><D>(
|
|
self,
|
|
deserializer: D,
|
|
) -> <a class="enum" href="https://doc.rust-lang.org/1.93.1/core/result/enum.Result.html" title="enum core::result::Result">Result</a><T, <D as <a class="trait" href="../trait.Deserializer.html" title="trait serde::Deserializer">Deserializer</a><'de>>::<a class="associatedtype" href="../trait.Deserializer.html#associatedtype.Error" title="type serde::Deserializer::Error">Error</a>><div class="where">where
|
|
D: <a class="trait" href="../trait.Deserializer.html" title="trait serde::Deserializer">Deserializer</a><'de>,</div></h4></section></div></details><h2 id="implementors" class="section-header">Implementors<a href="#implementors" class="anchor">§</a></h2><div id="implementors-list"><details class="toggle implementors-toggle"><summary><section id="impl-DeserializeSeed%3C'de%3E-for-InPlaceSeed%3C'a,+T%3E" class="impl"><a class="src rightside" href="../../src/serde_core/private/seed.rs.html#9-11">Source</a><a href="#impl-DeserializeSeed%3C'de%3E-for-InPlaceSeed%3C'a,+T%3E" class="anchor">§</a><h3 class="code-header">impl<'a, 'de, T> <a class="trait" href="trait.DeserializeSeed.html" title="trait serde::de::DeserializeSeed">DeserializeSeed</a><'de> for <a class="struct" href="../../serde_core/private/seed/struct.InPlaceSeed.html" title="struct serde_core::private::seed::InPlaceSeed">InPlaceSeed</a><'a, T><div class="where">where
|
|
T: <a class="trait" href="../trait.Deserialize.html" title="trait serde::Deserialize">Deserialize</a><'de>,</div></h3></section></summary><div class="impl-items"><section id="associatedtype.Value-2" class="associatedtype trait-impl"><a class="src rightside" href="../../src/serde_core/private/seed.rs.html#13">Source</a><a href="#associatedtype.Value-2" class="anchor">§</a><h4 class="code-header">type <a href="#associatedtype.Value" class="associatedtype">Value</a> = <a class="primitive" href="https://doc.rust-lang.org/1.93.1/std/primitive.unit.html">()</a></h4></section></div></details></div><script src="../../trait.impl/serde_core/de/trait.DeserializeSeed.js" data-ignore-extern-crates="core,serde_core" async></script></section></div></main></body></html> |