Debian Codegraph @

debian/rust-vendor/yoke/tests/bincode.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 // This test is a duplicate of one of the doctests, but is written separately
6 // since `cargo miri test` doesn't work on doctests yet
7
8 use std::borrow::Cow;
9 use std::mem;
10 use std::rc::Rc;
11 use yoke::{Yoke, Yokeable};
12
13 fn load_from_cache(_filename: &str) -> Rc<[u8]> {
14 // dummy implementation
15 Rc::new([0x5, 0, 0, 0, 0, 0, 0, 0, 0x68, 0x65, 0x6c, 0x6c, 0x6f])
16 }
17
18 fn load_object(filename: &str) -> Yoke<Bar<'static>, Rc<[u8]>> {
19 let rc: Rc<[u8]> = load_from_cache(filename);
20 Yoke::<Bar<'static>, Rc<[u8]>>::attach_to_cart(rc, |data: &[u8]| {
21 // A real implementation would properly deserialize `Bar` as a whole
22 Bar {
23 numbers: Cow::Borrowed(bincode::deserialize(data).unwrap()),
24 string: Cow::Borrowed(bincode::deserialize(data).unwrap()),
25 owned: Vec::new(),
26 }
27 })
28 }
29
30 // also implements Yokeable
31 struct Bar<'a> {
32 numbers: Cow<'a, [u8]>,
33 string: Cow<'a, str>,
34 owned: Vec<u8>,
35 }
36
37 unsafe impl<'a> Yokeable<'a> for Bar<'static> {
38 type Output = Bar<'a>;
39 #[inline]
40 fn transform(&'a self) -> &'a Bar<'a> {
41 self
42 }
43 #[inline]
44 fn transform_owned(self) -> Bar<'a> {
45 self
46 }
47 #[inline]
48 unsafe fn make(from: Bar<'a>) -> Self {
49 let ret = mem::transmute_copy(&from);
50 mem::forget(from);
51 ret
52 }
53 #[inline]
54 fn transform_mut<F>(&'a mut self, f: F)
55 where
56 F: 'static + FnOnce(&'a mut Self::Output),
57 {
58 unsafe { f(mem::transmute::<&mut Bar<'_>, &mut Bar<'a>>(self)) }
59 }
60 }
61
62 #[test]
63 fn test_load() {
64 // `load_object()` deserializes an object from a file
65 let mut bar = load_object("filename.bincode");
66 assert_eq!(bar.get().string, "hello");
67 assert!(matches!(bar.get().string, Cow::Borrowed(_)));
68 assert_eq!(&*bar.get().numbers, &[0x68, 0x65, 0x6c, 0x6c, 0x6f]);
69 assert!(matches!(bar.get().numbers, Cow::Borrowed(_)));
70 assert_eq!(&*bar.get().owned, &[]);
71
72 bar.with_mut(|bar| {
73 bar.string.to_mut().push_str(" world");
74 bar.owned.extend_from_slice(&[1, 4, 1, 5, 9]);
75 });
76
77 assert_eq!(bar.get().string, "hello world");
78 assert!(matches!(bar.get().string, Cow::Owned(_)));
79 assert_eq!(&*bar.get().owned, &[1, 4, 1, 5, 9]);
80 // Unchanged and still Cow::Borrowed
81 assert_eq!(&*bar.get().numbers, &[0x68, 0x65, 0x6c, 0x6c, 0x6f]);
82 assert!(matches!(bar.get().numbers, Cow::Borrowed(_)));
83 }