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
#![allow(unknown_lints)]

use interface;
use interface::Term;
use utils::insert_or_get;
use rc::ATerm;

use std::cell::UnsafeCell;
use std::rc::Rc;
use std::collections::HashSet;
use std::hash::Hash;
use std::marker::PhantomData;

#[derive(Default, Debug)]
pub struct ATermFactory<B: Hash + Eq> {
    arena: UnsafeCell<HashSet<Rc<ATerm<B>>>>,
    _nothing: PhantomData<B>,

}

impl<B: Hash + Eq> ATermFactory<B> {
    pub fn new() -> Self {
        ATermFactory { arena: UnsafeCell::new(HashSet::new()), _nothing: PhantomData }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        ATermFactory { arena: UnsafeCell::new(HashSet::with_capacity(capacity)), _nothing: PhantomData }
    }

    // Yes this is evil and unsafe, but that's why it's private!
    #[allow(mut_from_ref)]
    fn get_arena(&self) -> &mut HashSet<Rc<ATerm<B>>> {
        unsafe { &mut *self.arena.get() }
    }
}

impl<'a, B: Clone + Hash + Eq + 'a> interface::ATermFactory<'a, B> for ATermFactory<B> {
    type ATerm = ATerm<B>;
    type ATermRef = Rc<ATerm<B>>;

    fn no_annos(&'a self, term: Term<Rc<ATerm<B>>, B>) -> Self::ATermRef {
        insert_or_get(self.get_arena(), Rc::new(ATerm::no_annos(term))).clone()
    }

    fn with_annos<A>(&'a self, term: Term<Rc<ATerm<B>>, B>, annos: A) -> Self::ATermRef
        where A: IntoIterator<Item = Self::ATermRef>
    {
        insert_or_get(self.get_arena(), Rc::new(ATerm::with_annos(term, annos))).clone()
    }
}

impl<'a, B: Clone + Hash + Eq + 'a> interface::SharedATermFactory<'a, B> for ATermFactory<B> {
    fn get_shared(&'a self, value: Self::ATermRef) -> Self::ATermRef
        where Self::ATermRef: Clone
    {
        insert_or_get(self.get_arena(), value.clone()).clone()
    }
}