edn/intern_set.rs
1// Copyright 2016-2018 Mozilla
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4// this file except in compliance with the License. You may obtain a copy of the
5// License at http://www.apache.org/licenses/LICENSE-2.0
6// Unless required by applicable law or agreed to in writing, software distributed
7// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8// CONDITIONS OF ANY KIND, either express or implied. See the License for the
9// specific language governing permissions and limitations under the License.
10
11#![allow(dead_code)]
12
13use std::collections::HashSet;
14use std::hash::Hash;
15use std::ops::{Deref, DerefMut};
16
17use crate::ValueRc;
18
19/// An `InternSet` allows to "intern" some potentially large values, maintaining a single value
20/// instance owned by the `InternSet` and leaving consumers with lightweight ref-counted handles to
21/// the large owned value. This can avoid expensive clone() operations.
22///
23/// In Mentat, such large values might be strings or arbitrary [a v] pairs.
24///
25/// See https://en.wikipedia.org/wiki/String_interning for discussion.
26#[derive(Clone, Debug, Default, Eq, PartialEq)]
27pub struct InternSet<T>
28where
29 T: Eq + Hash,
30{
31 inner: HashSet<ValueRc<T>>,
32}
33
34impl<T> Deref for InternSet<T>
35where
36 T: Eq + Hash,
37{
38 type Target = HashSet<ValueRc<T>>;
39
40 fn deref(&self) -> &Self::Target {
41 &self.inner
42 }
43}
44
45impl<T> DerefMut for InternSet<T>
46where
47 T: Eq + Hash,
48{
49 fn deref_mut(&mut self) -> &mut Self::Target {
50 &mut self.inner
51 }
52}
53
54impl<T> InternSet<T>
55where
56 T: Eq + Hash,
57{
58 pub fn new() -> InternSet<T> {
59 InternSet {
60 inner: HashSet::new(),
61 }
62 }
63
64 /// Intern a value, providing a ref-counted handle to the interned value.
65 ///
66 /// ```
67 /// use edn::{InternSet, ValueRc};
68 ///
69 /// let mut s = InternSet::new();
70 ///
71 /// let one = "foo".to_string();
72 /// let two = ValueRc::new("foo".to_string());
73 ///
74 /// let out_one = s.intern(one);
75 /// assert_eq!(out_one, two);
76 /// // assert!(!&out_one.ptr_eq(&two)); // Nightly-only.
77 ///
78 /// let out_two = s.intern(two);
79 /// assert_eq!(out_one, out_two);
80 /// assert_eq!(1, s.len());
81 /// // assert!(&out_one.ptr_eq(&out_two)); // Nightly-only.
82 /// ```
83 pub fn intern<R: Into<ValueRc<T>>>(&mut self, value: R) -> ValueRc<T> {
84 let key: ValueRc<T> = value.into();
85 if self.inner.insert(key.clone()) {
86 key
87 } else {
88 self.inner.get(&key).unwrap().clone()
89 }
90 }
91}