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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// Copyright 2018-2022 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{
    AutoStorableHint,
    Packed,
    StorableHint,
    StorageKey,
};
use core::{
    fmt::Debug,
    marker::PhantomData,
};
use ink_primitives::{
    Key,
    KeyComposer,
};

/// Auto key type means that the storage key should be calculated automatically.
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct AutoKey;

impl StorageKey for AutoKey {
    const KEY: Key = 0;
}

impl Debug for AutoKey {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("AutoKey")
            .field("key", &<Self as StorageKey>::KEY)
            .finish()
    }
}

/// Manual key type specifies the storage key.
#[derive(Default, Copy, Clone, Eq, PartialEq, PartialOrd)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct ManualKey<const KEY: Key, ParentKey: StorageKey = ()>(
    PhantomData<fn() -> ParentKey>,
);

impl<const KEY: Key, ParentKey: StorageKey> StorageKey for ManualKey<KEY, ParentKey> {
    const KEY: Key = KeyComposer::concat(KEY, ParentKey::KEY);
}

impl<const KEY: Key, ParentKey: StorageKey> Debug for ManualKey<KEY, ParentKey> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("ManualKey")
            .field("key", &<Self as StorageKey>::KEY)
            .finish()
    }
}

/// Resolver key type selects between preferred key and autogenerated key.
/// If the `L` type is `AutoKey` it returns auto-generated `R` else `L`.
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Debug)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct ResolverKey<L: StorageKey, R: StorageKey>(PhantomData<fn() -> (L, R)>);

impl<L: StorageKey, R: StorageKey> StorageKey for ResolverKey<L, R> {
    /// `KEY` of the `AutoKey` is zero. If left key is zero, then use right manual key.
    const KEY: Key = if L::KEY == 0 { R::KEY } else { L::KEY };
}

type FinalKey<T, const KEY: Key, ParentKey> =
    ResolverKey<<T as StorableHint<ParentKey>>::PreferredKey, ManualKey<KEY, ParentKey>>;

// `AutoStorableHint` trait figures out that storage key it should use.
// - If the `PreferredKey` is `AutoKey` it will use an auto-generated key passed as generic
// into `AutoStorableHint`.
// - If `PreferredKey` is `ManualKey`, then it will use it.
impl<T, const KEY: Key, ParentKey> AutoStorableHint<ManualKey<KEY, ParentKey>> for T
where
    T: StorableHint<ParentKey>,
    T: StorableHint<FinalKey<T, KEY, ParentKey>>,
    ParentKey: StorageKey,
{
    type Type = <T as StorableHint<FinalKey<T, KEY, ParentKey>>>::Type;
}

impl<P> super::storage::private::Sealed for P where P: scale::Decode + scale::Encode {}
impl<P> Packed for P where P: scale::Decode + scale::Encode {}

impl<P> StorageKey for P
where
    P: Packed,
{
    const KEY: Key = 0;
}

impl<P, Key> StorableHint<Key> for P
where
    P: Packed,
    Key: StorageKey,
{
    type Type = P;
    type PreferredKey = AutoKey;
}

#[cfg(test)]
mod tests {
    /// Creates test to verify that the primitive types are packed.
    #[macro_export]
    macro_rules! storage_hint_works_for_primitive {
        ( $ty:ty ) => {
            paste::item! {
                #[test]
                #[allow(non_snake_case)]
                fn [<$ty _storage_hint_works>] () {
                    assert_eq!(
                        ::core::any::TypeId::of::<$ty>(),
                        ::core::any::TypeId::of::<<$ty as $crate::StorableHint<$crate::ManualKey<123>>>::Type>()
                    );
                }
            }
        };
    }
    mod arrays {
        use crate::storage_hint_works_for_primitive;

        type Array = [i32; 4];
        storage_hint_works_for_primitive!(Array);

        type ArrayTuples = [(i32, i32); 2];
        storage_hint_works_for_primitive!(ArrayTuples);
    }

    mod prims {
        use crate::storage_hint_works_for_primitive;
        use ink_primitives::AccountId;

        storage_hint_works_for_primitive!(bool);
        storage_hint_works_for_primitive!(String);
        storage_hint_works_for_primitive!(AccountId);
        storage_hint_works_for_primitive!(i8);
        storage_hint_works_for_primitive!(i16);
        storage_hint_works_for_primitive!(i32);
        storage_hint_works_for_primitive!(i64);
        storage_hint_works_for_primitive!(i128);
        storage_hint_works_for_primitive!(u8);
        storage_hint_works_for_primitive!(u16);
        storage_hint_works_for_primitive!(u32);
        storage_hint_works_for_primitive!(u64);
        storage_hint_works_for_primitive!(u128);

        type OptionU8 = Option<u8>;
        storage_hint_works_for_primitive!(OptionU8);

        type ResultU8 = Result<u8, bool>;
        storage_hint_works_for_primitive!(ResultU8);

        type BoxU8 = Box<u8>;
        storage_hint_works_for_primitive!(BoxU8);

        type BoxOptionU8 = Box<Option<u8>>;
        storage_hint_works_for_primitive!(BoxOptionU8);
    }

    mod tuples {
        use crate::storage_hint_works_for_primitive;

        type TupleSix = (i32, u32, String, u8, bool, Box<Option<i32>>);
        storage_hint_works_for_primitive!(TupleSix);
    }
}