summaryrefslogtreecommitdiffstats
path: root/third_party/rust/zerovec/src/varzerovec/databake.rs
blob: a3f9db2d176a80d250c9f1e01d0b087d41aa0d17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use crate::{ule::VarULE, VarZeroSlice, VarZeroVec};
use databake::*;

impl<T: VarULE + ?Sized> Bake for VarZeroVec<'_, T> {
    fn bake(&self, env: &CrateEnv) -> TokenStream {
        env.insert("zerovec");
        if self.is_empty() {
            quote! { zerovec::VarZeroVec::new() }
        } else {
            let bytes = databake::Bake::bake(&self.as_bytes(), env);
            // Safe because self.as_bytes is a safe input
            quote! { unsafe { zerovec::VarZeroVec::from_bytes_unchecked(#bytes) } }
        }
    }
}

impl<T: VarULE + ?Sized> Bake for &VarZeroSlice<T> {
    fn bake(&self, env: &CrateEnv) -> TokenStream {
        env.insert("zerovec");
        if self.is_empty() {
            quote! { zerovec::VarZeroSlice::new_empty() }
        } else {
            let bytes = databake::Bake::bake(&self.as_bytes(), env);
            // Safe because self.as_bytes is a safe input
            quote! { unsafe { zerovec::VarZeroSlice::from_bytes_unchecked(#bytes) } }
        }
    }
}

#[test]
fn test_baked_vec() {
    test_bake!(
        VarZeroVec<str>,
        const: crate::VarZeroVec::new(),
        zerovec
    );
    test_bake!(
        VarZeroVec<str>,
        const: unsafe {
            crate::VarZeroVec::from_bytes_unchecked(
                b"\x02\x01\0\x16\0M\x01\\\x11"
            )
        },
        zerovec
    );
}

#[test]
fn test_baked_slice() {
    test_bake!(
        &VarZeroSlice<str>,
        const: crate::VarZeroSlice::new_empty(),
        zerovec
    );
    test_bake!(
        &VarZeroSlice<str>,
        const: unsafe {
            crate::VarZeroSlice::from_bytes_unchecked(
                b"\x02\x01\0\x16\0M\x01\\\x11"
            )
        },
        zerovec
    );
}