Debian Codegraph @

third_party/rust/zerovec/examples/zv_serde.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 example demonstrates zero-copy, zero-allocation deserialization of a u32 vector
6 // stored in a Bincode buffer.
7
8 #![no_main] // https://github.com/unicode-org/icu4x/issues/395
9
10 icu_benchmark_macros::static_setup!();
11
12 use zerovec::ZeroVec;
13
14 #[derive(serde::Serialize, serde::Deserialize)]
15 struct DataStruct<'s> {
16 #[serde(borrow)]
17 pub nums: ZeroVec<'s, u16>,
18 }
19
20 const U16_SLICE: [u16; 16] = [
21 196, 989, 414, 731, 660, 217, 716, 353, 218, 730, 245, 846, 122, 294, 922, 488,
22 ];
23
24 const POSTCARD_BYTES: [u8; 33] = [
25 0x20, 0xc4, 0x0, 0xdd, 0x3, 0x9e, 0x1, 0xdb, 0x2, 0x94, 0x2, 0xd9, 0x0, 0xcc, 0x2, 0x61, 0x1,
26 0xda, 0x0, 0xda, 0x2, 0xf5, 0x0, 0x4e, 0x3, 0x7a, 0x0, 0x26, 0x1, 0x9a, 0x3, 0xe8, 0x1,
27 ];
28
29 #[allow(dead_code)]
30 fn serialize() {
31 let data = DataStruct {
32 nums: ZeroVec::from_slice_or_alloc(&U16_SLICE),
33 };
34 let postcard_bytes = postcard::to_stdvec(&data).expect("Serialization should be successful");
35 println!("Postcard bytes: {postcard_bytes:#x?}");
36 println!("ZeroVec bytes: {:#x?}", data.nums.as_bytes());
37 }
38
39 #[no_mangle]
40 fn main(_argc: isize, _argv: *const *const u8) -> isize {
41 icu_benchmark_macros::main_setup!();
42
43 // Un-comment the following line to generate postcard data:
44 // serialize();
45
46 let data: DataStruct = postcard::from_bytes(&POSTCARD_BYTES).expect("Valid bytes");
47 let result = data.nums.iter().sum::<u16>();
48 assert_eq!(8141, result);
49
50 0
51 }