bump_scope/
destructure.rs

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/// Allows you to destructure structs that have a drop implementation.
macro_rules! destructure {
    (let $ty:ty {
        $($field:ident $(: $field_alias:ident)?),* $(,)?
    } = $value:expr) => {
        let value: $ty = $value;
        let value = ::core::mem::ManuallyDrop::new(value);

        #[allow(dead_code)]
        const _: () = assert!(!$crate::destructure::has_duplicates(&[$(stringify!($field)),*]), "you can't destructure a field twice");

        $(
            let $crate::destructure::or!($($field_alias)? $field) = unsafe { ::core::ptr::read(&value.$field) };
        )*
    };
}

pub(crate) use destructure;

macro_rules! or {
    ($this:ident $that:ident) => {
        $this
    };
    ($that:ident) => {
        $that
    };
}

pub(crate) use or;

pub(crate) const fn has_duplicates(strings: &[&str]) -> bool {
    let mut x = 0;

    while x < strings.len() {
        let mut y = x + 1;

        while y < strings.len() {
            if str_eq(strings[x], strings[y]) {
                return true;
            }

            y += 1;
        }

        x += 1;
    }

    false
}

const fn str_eq(a: &str, b: &str) -> bool {
    let a = a.as_bytes();
    let b = b.as_bytes();

    if a.len() != b.len() {
        return false;
    }

    let mut i = 0;

    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }

        i += 1;
    }

    true
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn example() {
        pub struct Foo {
            bar: String,
            baz: String,
        }

        impl Drop for Foo {
            fn drop(&mut self) {}
        }

        let foo = Foo {
            bar: "bar".into(),
            baz: "baz".into(),
        };

        // won't compile
        // let Foo { bar: qux, baz } = foo;

        destructure!(let Foo { bar: qux, baz } = foo);

        assert_eq!(qux, "bar");
        assert_eq!(baz, "baz");
    }
}