Skip to main content

pack_io/
view.rs

1//! Zero-copy decoding: the [`DeserializeView`] trait, the [`decode_view`]
2//! free function, and built-in impls for the types that can borrow directly
3//! from the input buffer.
4//!
5//! ## The two decode surfaces
6//!
7//! [`Deserialize`] produces an **owning** value — `String`s and `Vec<u8>`s
8//! are allocated, the input buffer can be dropped immediately after the
9//! call. Use it when the input is transient (a network buffer being
10//! recycled, a file being streamed) or when downstream code holds the
11//! decoded value for an unbounded lifetime.
12//!
13//! [`DeserializeView`] produces a **borrowed** value — `&'a str` and
14//! `&'a [u8]` fields point directly into the input slice. No per-field
15//! allocation. Use it when the input buffer outlives the decoded value
16//! (e.g. a memory-mapped file, an arena, a request-lifetime byte buffer).
17//!
18//! Both surfaces share the same on-wire format. A value encoded with
19//! [`crate::encode`] can be read with either [`crate::decode`] (owning) or
20//! [`decode_view`] (borrowed); choose the one that matches the lifetime
21//! relationship the caller has with the source bytes. Both enforce the same
22//! [`Config`] limits.
23//!
24//! ## Built-in implementors
25//!
26//! - `&'a str`, `&'a [u8]`, `Cow<'a, str>`, `Cow<'a, [u8]>` — the headline
27//!   zero-copy types (the `Cow`s come back as `Cow::Borrowed`).
28//! - Every primitive (`u8` … `u128`, `i8` … `i128`, `usize`, `isize`,
29//!   `bool`, `char`, `f32`, `f64`, `()`), `NonZero*`, `Duration`,
30//!   `PhantomData<T>` — `DeserializeView` reduces to [`Deserialize`] for
31//!   these, no borrow involved.
32//! - Owned text: `String`, `Box<str>`, `Rc<str>`, `Arc<str>`; `Box<T>` for
33//!   any `T: DeserializeView`.
34//! - `Option<T>`, `Result<T, E>`, tuples `(T1, …, Tn)` (arity 1–12),
35//!   fixed-size arrays `[T; N]`.
36//! - `Vec<T>`, `VecDeque<T>` and the standard `BTreeMap` / `BTreeSet` /
37//!   `HashMap` / `HashSet` — these have to allocate the container itself,
38//!   but their element / key / value types may still be borrows.
39//!
40//! User-defined types implement [`DeserializeView`] directly or via the
41//! `#[derive(DeserializeView)]` macro (`feature = "derive"`), which also
42//! works on types without a lifetime parameter so they can be nested inside
43//! borrowing views.
44
45use alloc::borrow::Cow;
46use alloc::boxed::Box;
47use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
48use alloc::rc::Rc;
49use alloc::string::String;
50#[cfg(target_has_atomic = "ptr")]
51use alloc::sync::Arc;
52use alloc::vec::Vec;
53use core::marker::PhantomData;
54use core::num::{
55    NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
56    NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
57};
58use core::time::Duration;
59#[cfg(feature = "std")]
60use std::collections::{HashMap, HashSet};
61#[cfg(feature = "std")]
62use std::hash::{BuildHasher, Hash};
63
64use crate::codec::{
65    Config, Decode, Decoder, charge_boxed, charge_elements, decode_elements_counted, finish,
66    guard_element_count, initial_capacity,
67};
68use crate::error::{Result, SerialError};
69use crate::impls::KeyOrder;
70use crate::traits::Deserialize;
71
72// ---------------------------------------------------------------------------
73// Trait + free function
74// ---------------------------------------------------------------------------
75
76/// Types that decode by **borrowing** directly from the input slice rather
77/// than allocating owned copies.
78///
79/// `'a` is the lifetime of the underlying byte buffer; every borrowed field
80/// in the decoded value points into that buffer. The borrow checker
81/// guarantees the value cannot outlive its source.
82///
83/// # Examples
84///
85/// Borrow string and byte fields out of a request buffer:
86///
87/// ```
88/// use pack_io::{decode_view, Decode, Decoder, DeserializeView, Result, Serialize, Encode};
89///
90/// // Pair of borrowed and owned versions for round-tripping.
91/// struct OwnedMsg { id: u64, text: String, payload: Vec<u8> }
92/// struct ViewMsg<'a> { id: u64, text: &'a str, payload: &'a [u8] }
93///
94/// impl Serialize for OwnedMsg {
95///     fn serialize<E: Encode + ?Sized>(&self, e: &mut E) -> Result<()> {
96///         self.id.serialize(e)?; self.text.serialize(e)?; self.payload.serialize(e)
97///     }
98/// }
99/// impl<'a> DeserializeView<'a> for ViewMsg<'a> {
100///     fn deserialize_view(d: &mut Decoder<'a>) -> Result<Self> {
101///         Ok(ViewMsg {
102///             id:      u64::deserialize_view(d)?,
103///             text:    <&str>::deserialize_view(d)?,
104///             payload: <&[u8]>::deserialize_view(d)?,
105///         })
106///     }
107/// }
108///
109/// let bytes = pack_io::encode(&OwnedMsg {
110///     id: 7,
111///     text: "hello".into(),
112///     payload: vec![1, 2, 3],
113/// }).unwrap();
114///
115/// let view: ViewMsg<'_> = decode_view(&bytes).unwrap();
116/// assert_eq!(view.text, "hello");        // &str borrowed from `bytes`
117/// assert_eq!(view.payload, &[1, 2, 3]);  // &[u8] borrowed from `bytes`
118/// ```
119pub trait DeserializeView<'a>: Sized {
120    /// Read a value of `Self` from `decoder`, borrowing from its
121    /// underlying input slice where possible.
122    ///
123    /// # Errors
124    ///
125    /// Any [`crate::SerialError`] the underlying byte reads surface.
126    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self>;
127
128    /// Read `count` consecutive `Self` values into a `Vec`.
129    ///
130    /// The view-side counterpart of [`Deserialize::deserialize_many`]. The
131    /// default decodes one element at a time with a bounded initial
132    /// capacity; `u8` overrides it with one bounds check and one copy, so a
133    /// `Vec<u8>` field in a view struct is not decoded byte by byte.
134    ///
135    /// # Errors
136    ///
137    /// Propagates any error returned by the per-element / bulk read.
138    fn deserialize_view_many(decoder: &mut Decoder<'a>, count: usize) -> Result<Vec<Self>> {
139        let mut out = Vec::with_capacity(initial_capacity::<Self, Decoder<'a>>(count, decoder));
140        decode_elements_counted::<Self, Decoder<'a>, _>(decoder, count, |decoder| {
141            out.push(Self::deserialize_view(decoder)?);
142            Ok(())
143        })?;
144        Ok(out)
145    }
146
147    /// Read `N` consecutive `Self` values into an array. `u8` overrides it
148    /// with a single read into a stack array.
149    ///
150    /// # Errors
151    ///
152    /// Propagates any error returned by the per-element / bulk read.
153    fn deserialize_view_array<const N: usize>(decoder: &mut Decoder<'a>) -> Result<[Self; N]> {
154        let mut out: Vec<Self> = Vec::with_capacity(N);
155        for _ in 0..N {
156            out.push(Self::deserialize_view(decoder)?);
157        }
158        // Exactly `N` elements were pushed, so this cannot fail.
159        out.try_into()
160            .map_err(|_| SerialError::custom("array length mismatch"))
161    }
162}
163
164/// Decode a borrowed value of type `T` from `bytes`, requiring the input to
165/// be fully consumed.
166///
167/// This is the **Tier-1** zero-copy entry point — the symmetric counterpart
168/// to [`crate::decode`]. The decoded value borrows from `bytes`; the
169/// borrow checker enforces that `bytes` outlives the result.
170///
171/// # Examples
172///
173/// ```
174/// let bytes = pack_io::encode(&"hello").unwrap();
175/// let view: &str = pack_io::decode_view(&bytes).unwrap();
176/// assert_eq!(view, "hello");
177/// ```
178///
179/// # Errors
180///
181/// - Returns [`SerialError::TrailingBytes`] when extra bytes follow the value.
182/// - Propagates any [`SerialError`] from the type's [`DeserializeView`] impl.
183#[inline]
184pub fn decode_view<'a, T: DeserializeView<'a>>(bytes: &'a [u8]) -> Result<T> {
185    let mut dec = Decoder::new(bytes);
186    let value = T::deserialize_view(&mut dec)?;
187    finish(&dec, value)
188}
189
190/// [`decode_view`] under an explicit [`Config`].
191///
192/// # Examples
193///
194/// ```
195/// use pack_io::{Config, SerialError, decode_view_with_config, encode};
196///
197/// let bytes = encode(&"a fairly long string").unwrap();
198/// let tight = Config::new().with_max_alloc(8);
199/// let err = decode_view_with_config::<&str>(&bytes, tight).unwrap_err();
200/// assert!(matches!(err, SerialError::InvalidLength { .. }));
201/// ```
202///
203/// # Errors
204///
205/// - Any error [`Decoder::with_config`] reports for an invalid `config`.
206/// - [`SerialError::TrailingBytes`] when extra bytes follow the value.
207/// - Any [`SerialError`] from the type's [`DeserializeView`] impl.
208#[inline]
209pub fn decode_view_with_config<'a, T: DeserializeView<'a>>(
210    bytes: &'a [u8],
211    config: Config,
212) -> Result<T> {
213    let mut dec = Decoder::with_config(bytes, config)?;
214    let value = T::deserialize_view(&mut dec)?;
215    finish(&dec, value)
216}
217
218// ---------------------------------------------------------------------------
219// Borrowed primitives
220// ---------------------------------------------------------------------------
221
222impl<'a> DeserializeView<'a> for &'a str {
223    #[inline]
224    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
225        let bytes = decoder.read_length_prefixed_borrowed()?;
226        core::str::from_utf8(bytes).map_err(|_| SerialError::InvalidUtf8)
227    }
228}
229
230impl<'a> DeserializeView<'a> for &'a [u8] {
231    #[inline]
232    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
233        decoder.read_length_prefixed_borrowed()
234    }
235}
236
237impl<'a> DeserializeView<'a> for Cow<'a, str> {
238    #[inline]
239    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
240        <&'a str>::deserialize_view(decoder).map(Cow::Borrowed)
241    }
242}
243
244impl<'a> DeserializeView<'a> for Cow<'a, [u8]> {
245    #[inline]
246    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
247        <&'a [u8]>::deserialize_view(decoder).map(Cow::Borrowed)
248    }
249}
250
251// ---------------------------------------------------------------------------
252// Fixed-size scalars and owned text: DeserializeView ≡ Deserialize
253// ---------------------------------------------------------------------------
254
255macro_rules! view_via_owned {
256    ($($t:ty),+ $(,)?) => {
257        $(
258            impl<'a> DeserializeView<'a> for $t {
259                #[inline]
260                fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
261                    <$t as Deserialize>::deserialize(decoder)
262                }
263            }
264        )+
265    };
266}
267
268view_via_owned!(
269    u16,
270    u32,
271    u64,
272    u128,
273    usize,
274    i8,
275    i16,
276    i32,
277    i64,
278    i128,
279    isize,
280    bool,
281    char,
282    f32,
283    f64,
284    (),
285    String,
286    Box<str>,
287    Rc<str>,
288    Duration,
289    NonZeroU8,
290    NonZeroU16,
291    NonZeroU32,
292    NonZeroU64,
293    NonZeroU128,
294    NonZeroUsize,
295    NonZeroI8,
296    NonZeroI16,
297    NonZeroI32,
298    NonZeroI64,
299    NonZeroI128,
300    NonZeroIsize,
301);
302
303#[cfg(target_has_atomic = "ptr")]
304view_via_owned!(Arc<str>);
305
306impl<'a> DeserializeView<'a> for u8 {
307    #[inline]
308    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
309        decoder.read_byte()
310    }
311
312    /// One bounds check and one copy for `Vec<u8>` fields in view structs.
313    #[inline]
314    fn deserialize_view_many(decoder: &mut Decoder<'a>, count: usize) -> Result<Vec<Self>> {
315        decoder.read_borrowed(count).map(<[u8]>::to_vec)
316    }
317
318    /// `[u8; N]` in a view struct is one read into a stack array.
319    #[inline]
320    fn deserialize_view_array<const N: usize>(decoder: &mut Decoder<'a>) -> Result<[Self; N]> {
321        <u8 as Deserialize>::deserialize_array::<Decoder<'a>, N>(decoder)
322    }
323}
324
325impl<'a, T: DeserializeView<'a>> DeserializeView<'a> for Box<T> {
326    #[inline]
327    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
328        charge_boxed::<T, Decoder<'a>>(decoder, 0)?;
329        T::deserialize_view(decoder).map(Box::new)
330    }
331}
332
333impl<'a, T: ?Sized> DeserializeView<'a> for PhantomData<T> {
334    #[inline]
335    fn deserialize_view(_decoder: &mut Decoder<'a>) -> Result<Self> {
336        Ok(PhantomData)
337    }
338}
339
340// ---------------------------------------------------------------------------
341// Containers: Option, Result, tuples, arrays — propagate the lifetime
342// ---------------------------------------------------------------------------
343
344impl<'a, T: DeserializeView<'a>> DeserializeView<'a> for Option<T> {
345    #[inline]
346    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
347        match decoder.read_byte()? {
348            0x00 => Ok(None),
349            0x01 => Ok(Some(T::deserialize_view(decoder)?)),
350            tag => Err(SerialError::InvalidTag {
351                kind: "Option",
352                tag,
353            }),
354        }
355    }
356}
357
358impl<'a, T: DeserializeView<'a>, E: DeserializeView<'a>> DeserializeView<'a>
359    for core::result::Result<T, E>
360{
361    #[inline]
362    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
363        match decoder.read_byte()? {
364            0x00 => Ok(Ok(T::deserialize_view(decoder)?)),
365            0x01 => Ok(Err(E::deserialize_view(decoder)?)),
366            tag => Err(SerialError::InvalidTag {
367                kind: "Result",
368                tag,
369            }),
370        }
371    }
372}
373
374impl<'a, T: DeserializeView<'a>, const N: usize> DeserializeView<'a> for [T; N] {
375    #[inline]
376    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
377        T::deserialize_view_array::<N>(decoder)
378    }
379}
380
381impl<'a, T: DeserializeView<'a>> DeserializeView<'a> for Vec<T> {
382    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
383        let declared = decoder.read_varint_u64()?;
384        let len = guard_element_count(declared, decoder)?;
385        charge_elements::<T, Decoder<'a>>(decoder, len)?;
386        T::deserialize_view_many(decoder, len)
387    }
388}
389
390impl<'a, T: DeserializeView<'a>> DeserializeView<'a> for VecDeque<T> {
391    #[inline]
392    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
393        Vec::<T>::deserialize_view(decoder).map(VecDeque::from)
394    }
395}
396
397macro_rules! view_tuple {
398    ($($name:ident),+) => {
399        impl<'a, $($name: DeserializeView<'a>),+> DeserializeView<'a> for ($($name,)+) {
400            #[inline]
401            fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
402                Ok(( $( $name::deserialize_view(decoder)?, )+ ))
403            }
404        }
405    };
406}
407
408view_tuple!(T0);
409view_tuple!(T0, T1);
410view_tuple!(T0, T1, T2);
411view_tuple!(T0, T1, T2, T3);
412view_tuple!(T0, T1, T2, T3, T4);
413view_tuple!(T0, T1, T2, T3, T4, T5);
414view_tuple!(T0, T1, T2, T3, T4, T5, T6);
415view_tuple!(T0, T1, T2, T3, T4, T5, T6, T7);
416view_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
417view_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
418view_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
419view_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
420
421// ---------------------------------------------------------------------------
422// Map / set collections: the container is allocated, but K / V may borrow.
423// ---------------------------------------------------------------------------
424
425/// Decode `len` borrowed `(K, V)` entries, enforcing strictly increasing
426/// encoded keys in canonical mode and charging entries that consume no
427/// input against `max_alloc`.
428fn view_entries<'a, K, V, F>(decoder: &mut Decoder<'a>, len: usize, mut insert: F) -> Result<()>
429where
430    K: DeserializeView<'a>,
431    V: DeserializeView<'a>,
432    F: FnMut(K, V),
433{
434    let mut order = decoder
435        .config()
436        .canonical
437        .then(|| KeyOrder::new("map key order"));
438    decode_elements_counted::<(K, V), Decoder<'a>, _>(decoder, len, |decoder| {
439        let start = decoder.position();
440        let k = K::deserialize_view(decoder)?;
441        if let Some(order) = order.as_mut() {
442            order.check(decoder, start)?;
443        }
444        let v = V::deserialize_view(decoder)?;
445        insert(k, v);
446        Ok(())
447    })
448}
449
450/// Decode `len` borrowed set elements, enforcing strictly increasing
451/// encodings in canonical mode and charging elements that consume no input
452/// against `max_alloc`.
453fn view_elements<'a, T, F>(decoder: &mut Decoder<'a>, len: usize, mut insert: F) -> Result<()>
454where
455    T: DeserializeView<'a>,
456    F: FnMut(T),
457{
458    let mut order = decoder
459        .config()
460        .canonical
461        .then(|| KeyOrder::new("set element order"));
462    decode_elements_counted::<T, Decoder<'a>, _>(decoder, len, |decoder| {
463        let start = decoder.position();
464        let item = T::deserialize_view(decoder)?;
465        if let Some(order) = order.as_mut() {
466            order.check(decoder, start)?;
467        }
468        insert(item);
469        Ok(())
470    })
471}
472
473impl<'a, K, V> DeserializeView<'a> for BTreeMap<K, V>
474where
475    K: DeserializeView<'a> + Ord,
476    V: DeserializeView<'a>,
477{
478    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
479        let declared = decoder.read_varint_u64()?;
480        let len = guard_element_count(declared, decoder)?;
481        charge_elements::<(K, V), Decoder<'a>>(decoder, len)?;
482        let mut out = BTreeMap::new();
483        view_entries(decoder, len, |k, v| {
484            let _ = out.insert(k, v);
485        })?;
486        Ok(out)
487    }
488}
489
490impl<'a, T> DeserializeView<'a> for BTreeSet<T>
491where
492    T: DeserializeView<'a> + Ord,
493{
494    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
495        let declared = decoder.read_varint_u64()?;
496        let len = guard_element_count(declared, decoder)?;
497        charge_elements::<T, Decoder<'a>>(decoder, len)?;
498        let mut out = BTreeSet::new();
499        view_elements(decoder, len, |item| {
500            let _ = out.insert(item);
501        })?;
502        Ok(out)
503    }
504}
505
506#[cfg(feature = "std")]
507impl<'a, K, V, S> DeserializeView<'a> for HashMap<K, V, S>
508where
509    K: DeserializeView<'a> + Hash + Eq,
510    V: DeserializeView<'a>,
511    S: BuildHasher + Default,
512{
513    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
514        let declared = decoder.read_varint_u64()?;
515        let len = guard_element_count(declared, decoder)?;
516        charge_elements::<(K, V), Decoder<'a>>(decoder, len)?;
517        let capacity = initial_capacity::<(K, V), Decoder<'a>>(len, decoder);
518        let mut out = HashMap::with_capacity_and_hasher(capacity, S::default());
519        view_entries(decoder, len, |k, v| {
520            let _ = out.insert(k, v);
521        })?;
522        Ok(out)
523    }
524}
525
526#[cfg(feature = "std")]
527impl<'a, T, S> DeserializeView<'a> for HashSet<T, S>
528where
529    T: DeserializeView<'a> + Hash + Eq,
530    S: BuildHasher + Default,
531{
532    fn deserialize_view(decoder: &mut Decoder<'a>) -> Result<Self> {
533        let declared = decoder.read_varint_u64()?;
534        let len = guard_element_count(declared, decoder)?;
535        charge_elements::<T, Decoder<'a>>(decoder, len)?;
536        let capacity = initial_capacity::<T, Decoder<'a>>(len, decoder);
537        let mut out = HashSet::with_capacity_and_hasher(capacity, S::default());
538        view_elements(decoder, len, |item| {
539            let _ = out.insert(item);
540        })?;
541        Ok(out)
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548    use crate::encode;
549    use alloc::string::ToString;
550    use alloc::vec;
551
552    #[test]
553    fn borrowed_str_round_trips() {
554        let bytes = encode(&"hello").unwrap();
555        let view: &str = decode_view(&bytes).unwrap();
556        assert_eq!(view, "hello");
557    }
558
559    #[test]
560    fn borrowed_bytes_round_trip() {
561        let bytes = encode(&vec![1u8, 2, 3, 4, 5]).unwrap();
562        let view: &[u8] = decode_view(&bytes).unwrap();
563        assert_eq!(view, &[1, 2, 3, 4, 5]);
564    }
565
566    #[test]
567    fn primitive_view_decodes_like_owning() {
568        let bytes = encode(&42_u64).unwrap();
569        let n: u64 = decode_view(&bytes).unwrap();
570        assert_eq!(n, 42);
571    }
572
573    #[test]
574    fn option_borrowed_view_round_trips() {
575        let bytes = encode(&Some(String::from("hi"))).unwrap();
576        let v: Option<&str> = decode_view(&bytes).unwrap();
577        assert_eq!(v, Some("hi"));
578
579        let none_bytes = encode::<Option<String>>(&None).unwrap();
580        let v: Option<&str> = decode_view(&none_bytes).unwrap();
581        assert_eq!(v, None);
582    }
583
584    #[test]
585    fn tuple_with_borrowed_str_round_trips() {
586        let owned = (7_u64, String::from("hello"), true);
587        let bytes = encode(&owned).unwrap();
588        let view: (u64, &str, bool) = decode_view(&bytes).unwrap();
589        assert_eq!(view, (7, "hello", true));
590    }
591
592    #[test]
593    fn vec_of_borrowed_str_round_trips() {
594        let owned = vec![
595            String::from("alpha"),
596            String::from("beta"),
597            String::from("gamma"),
598        ];
599        let bytes = encode(&owned).unwrap();
600        let view: Vec<&str> = decode_view(&bytes).unwrap();
601        assert_eq!(view, vec!["alpha", "beta", "gamma"]);
602    }
603
604    #[test]
605    fn decode_view_rejects_trailing_bytes() {
606        let mut bytes = encode(&"hi").unwrap();
607        bytes.push(0xff);
608        let err = decode_view::<&str>(&bytes).expect_err("trailing bytes");
609        assert!(matches!(err, SerialError::TrailingBytes { remaining: 1 }));
610    }
611
612    #[test]
613    fn borrowed_str_with_invalid_utf8_is_rejected() {
614        let bytes = [0x02u8, 0xff, 0xff];
615        let err = decode_view::<&str>(&bytes).expect_err("invalid utf-8");
616        assert!(matches!(err, SerialError::InvalidUtf8));
617    }
618
619    #[test]
620    fn map_with_borrowed_keys_round_trips() {
621        let mut owned: BTreeMap<String, u32> = BTreeMap::new();
622        let _ = owned.insert("alpha".to_string(), 1);
623        let _ = owned.insert("beta".to_string(), 2);
624        let bytes = encode(&owned).unwrap();
625        let view: BTreeMap<&str, u32> = decode_view(&bytes).unwrap();
626        assert_eq!(view.get("alpha"), Some(&1));
627        assert_eq!(view.get("beta"), Some(&2));
628    }
629}