monotone

monotone Mtn Source Tree

Root/interner.hh

1#ifndef __INTERNER_HH__
2#define __INTERNER_HH__
3
4// Copyright (C) 2002 Graydon Hoare <graydon@pobox.com>
5//
6// This program is made available under the GNU GPL version 2.0 or
7// greater. See the accompanying file COPYING for details.
8//
9// This program is distributed WITHOUT ANY WARRANTY; without even the
10// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11// PURPOSE.
12
13#include <string>
14
15#include "hash_map.hh"
16#include "sanity.hh"
17
18template <typename T>
19struct
20interner
21{
22 typedef typename hashmap::hash_map<std::string, T> hmap;
23
24 hmap fwd;
25 std::vector<std::string> rev;
26 interner() {}
27 interner(std::string const & init_str, T init_value)
28 {
29 I(intern(init_str) == init_value);
30 }
31 std::string lookup (T in) const
32 {
33 std::vector<std::string>::size_type k = static_cast<std::vector<std::string>::size_type>(in);
34 I(k < rev.size());
35 return rev[k];
36 }
37 T intern(std::string const & s)
38 {
39 bool is_new;
40 return intern(s, is_new);
41 }
42 T intern(std::string const & s, bool & is_new)
43 {
44 std::pair<typename hmap::iterator, bool> res;
45 T t = rev.size();
46 // if fwd already contains an entry with key s, this just finds
47 // that and returns it
48 res = fwd.insert(make_pair(s, t));
49 is_new = res.second;
50 if (is_new)
51 rev.push_back(s);
52 return res.first->second;
53 }
54};
55
56// Local Variables:
57// mode: C++
58// fill-column: 76
59// c-file-style: "gnu"
60// indent-tabs-mode: nil
61// End:
62// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:
63
64#endif // __INTERNER_HH__

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status