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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::TryFromIntError;
use std::sync::Arc;

use crate::error::{Error, ErrorKind};
use crate::value::{Value, ValueRepr};

pub use crate::key::serialize::KeySerializer;

#[cfg(feature = "deserialization")]
mod deserialize;
mod serialize;

/// Represents a key in a value's map.
#[derive(Clone)]
pub enum Key<'a> {
    Bool(bool),
    I64(i64),
    Char(char),
    String(Arc<String>),
    Str(&'a str),
}

pub type StaticKey = Key<'static>;

impl<'a> fmt::Debug for Key<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bool(val) => fmt::Debug::fmt(val, f),
            Self::I64(val) => fmt::Debug::fmt(val, f),
            Self::Char(val) => fmt::Debug::fmt(val, f),
            Self::String(val) => fmt::Debug::fmt(val, f),
            Self::Str(val) => fmt::Debug::fmt(val, f),
        }
    }
}

#[derive(PartialOrd, Ord, Eq, PartialEq, Hash)]
enum InternalKeyRef<'a> {
    Bool(bool),
    I64(i64),
    Char(char),
    Str(&'a str),
}

impl<'a> Key<'a> {
    pub fn make_string_key(s: &str) -> StaticKey {
        #[cfg(feature = "key_interning")]
        {
            Key::String(key_interning::try_intern(s))
        }
        #[cfg(not(feature = "key_interning"))]
        {
            Key::String(Arc::new(String::from(s)))
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match *self {
            Key::String(ref x) => Some(x.as_str()),
            Key::Str(x) => Some(x),
            _ => None,
        }
    }

    fn as_key_ref(&self) -> InternalKeyRef<'_> {
        match *self {
            Key::Bool(x) => InternalKeyRef::Bool(x),
            Key::I64(x) => InternalKeyRef::I64(x),
            Key::Char(x) => InternalKeyRef::Char(x),
            Key::String(ref x) => InternalKeyRef::Str(x.as_str()),
            Key::Str(x) => InternalKeyRef::Str(x),
        }
    }

    pub fn from_borrowed_value(value: &'a Value) -> Result<Key<'a>, Error> {
        match value.0 {
            ValueRepr::Bool(v) => Ok(Key::Bool(v)),
            ValueRepr::U64(v) => TryFrom::try_from(v)
                .map(Key::I64)
                .map_err(|_| ErrorKind::NonKey.into()),
            ValueRepr::U128(v) => TryFrom::try_from(v.0)
                .map(Key::I64)
                .map_err(|_| ErrorKind::NonKey.into()),
            ValueRepr::I64(v) => Ok(Key::I64(v)),
            ValueRepr::I128(v) => TryFrom::try_from(v.0)
                .map(Key::I64)
                .map_err(|_| ErrorKind::NonKey.into()),
            ValueRepr::F64(x) => {
                // if a float is in fact looking like an integer we
                // allow this to be used for indexing.  Why?  Because
                // in Jinja division is always a division resulting
                // in floating point values (4 / 2 == 2.0).
                let intval = x as i64;
                if intval as f64 == x {
                    Ok(Key::I64(intval))
                } else {
                    Err(ErrorKind::NonKey.into())
                }
            }
            ValueRepr::Char(c) => Ok(Key::Char(c)),
            ValueRepr::String(ref s, _) => Ok(Key::Str(s)),
            _ => Err(ErrorKind::NonKey.into()),
        }
    }
}

impl<'a> PartialEq for Key<'a> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.as_key_ref().eq(&other.as_key_ref())
    }
}

impl<'a> Eq for Key<'a> {}

impl<'a> Hash for Key<'a> {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_key_ref().hash(state)
    }
}

impl<'a> PartialOrd for Key<'a> {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.as_key_ref().partial_cmp(&other.as_key_ref())
    }
}

impl<'a> Ord for Key<'a> {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_key_ref().cmp(&other.as_key_ref())
    }
}

impl<'a> fmt::Display for Key<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Key::Bool(val) => write!(f, "{val}"),
            Key::I64(val) => write!(f, "{val}"),
            Key::Char(val) => write!(f, "{val}"),
            Key::String(val) => write!(f, "{val}"),
            Key::Str(val) => write!(f, "{val}"),
        }
    }
}

macro_rules! key_from {
    ($src:ty, $dst:ident) => {
        impl From<$src> for StaticKey {
            #[inline(always)]
            fn from(val: $src) -> Self {
                Key::$dst(val as _)
            }
        }
    };
}

key_from!(bool, Bool);
key_from!(u8, I64);
key_from!(u16, I64);
key_from!(u32, I64);
key_from!(i8, I64);
key_from!(i16, I64);
key_from!(i32, I64);
key_from!(i64, I64);
key_from!(char, Char);

impl TryFrom<u64> for StaticKey {
    type Error = TryFromIntError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        TryFrom::try_from(value).map(Key::I64)
    }
}

impl From<Arc<String>> for StaticKey {
    #[inline(always)]
    fn from(value: Arc<String>) -> Self {
        Key::String(value)
    }
}

impl From<String> for StaticKey {
    #[inline(always)]
    fn from(value: String) -> Self {
        Key::String(Arc::new(value))
    }
}

impl<'a> From<&'a str> for StaticKey {
    #[inline(always)]
    fn from(value: &'a str) -> Self {
        Key::make_string_key(value)
    }
}

#[cfg(feature = "key_interning")]
pub mod key_interning {
    use crate::utils::OnDrop;

    use super::*;
    use std::cell::{Cell, RefCell};
    use std::collections::HashSet;

    thread_local! {
        static STRING_KEY_CACHE: RefCell<HashSet<CachedKey<'static>>> = Default::default();
        static USE_STRING_KEY_CACHE: Cell<bool> = Cell::new(false);
    }

    enum CachedKey<'a> {
        Ref(&'a str),
        Stored(Arc<String>),
    }

    impl<'a> CachedKey<'a> {
        fn as_str(&self) -> &str {
            match self {
                CachedKey::Ref(x) => x,
                CachedKey::Stored(x) => x.as_str(),
            }
        }
    }

    impl<'a> Hash for CachedKey<'a> {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.as_str().hash(state)
        }
    }

    impl<'a> PartialEq for CachedKey<'a> {
        fn eq(&self, other: &Self) -> bool {
            self.as_str().eq(other.as_str())
        }
    }

    impl<'a> Eq for CachedKey<'a> {}

    pub fn use_string_cache() -> impl Drop {
        let was_enabled = USE_STRING_KEY_CACHE.with(|flag| {
            let was_enabled = flag.get();
            flag.set(true);
            was_enabled
        });
        OnDrop::new(move || {
            if !was_enabled {
                USE_STRING_KEY_CACHE.with(|flag| flag.set(false));
                STRING_KEY_CACHE.with(|cache| cache.borrow_mut().clear());
            }
        })
    }

    #[inline(always)]
    pub(crate) fn try_intern(s: &str) -> Arc<String> {
        // strings longer than 16 bytes are never interned or if we're at
        // depth 0.  (serialization code outside of internal serialization)
        // not checking for depth can cause a memory leak.
        if s.len() > 16 || !USE_STRING_KEY_CACHE.with(|flag| flag.get()) {
            return Arc::new(String::from(s));
        }

        STRING_KEY_CACHE.with(|cache| {
            let mut set = cache.borrow_mut();
            match set.get(&CachedKey::Ref(s)) {
                Some(CachedKey::Stored(s)) => s.clone(),
                None => {
                    let rv = Arc::new(String::from(s));
                    set.insert(CachedKey::Stored(rv.clone()));
                    rv
                }
                _ => unreachable!(),
            }
        })
    }

    #[test]
    fn test_key_interning() {
        let mut m = std::collections::BTreeMap::new();
        m.insert("x", 1u32);

        let v = Value::from_serializable(&vec![m.clone(), m.clone(), m.clone()]);

        for value in v.try_iter_owned().unwrap() {
            match value.0 {
                ValueRepr::Map(m, _) => {
                    let k = m.iter().next().unwrap().0;
                    match k {
                        Key::String(s) => {
                            assert_eq!(Arc::strong_count(s), 3);
                        }
                        _ => unreachable!(),
                    }
                }
                _ => unreachable!(),
            }
        }
    }
}

#[test]
fn test_string_key_lookup() {
    let mut m = std::collections::BTreeMap::new();
    m.insert(Key::String(Arc::new("foo".into())), Value::from(42));
    let m = Value::from(m);
    assert_eq!(m.get_item(&Value::from("foo")).unwrap(), Value::from(42));
}

#[test]
fn test_int_key_lookup() {
    let mut m = std::collections::BTreeMap::new();
    m.insert(Key::I64(42), Value::from(42));
    m.insert(Key::I64(23), Value::from(23));
    let m = Value::from(m);
    assert_eq!(m.get_item(&Value::from(42.0f32)).unwrap(), Value::from(42));
    assert_eq!(m.get_item(&Value::from(42u32)).unwrap(), Value::from(42));

    let s = Value::from(vec![42i32, 23]);
    assert_eq!(s.get_item(&Value::from(0.0f32)).unwrap(), Value::from(42));
    assert_eq!(s.get_item(&Value::from(0i32)).unwrap(), Value::from(42));
}