monotone

monotone Mtn Source Tree

Root/safe_map.hh

1#ifndef __SAFE_MAP_HH__
2#define __SAFE_MAP_HH__
3
4// Copyright (C) 2005 Nathaniel Smith <njs@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// some helpers to safely use maps
14
15// errors out if the key does not exist
16template <typename T>
17void
18do_safe_erase(T & container, typename T::key_type const & key,
19 char const * container_name, char const * file, int line)
20{
21 if (!container.erase(key))
22 global_sanity.invariant_failure((F("erasing nonexistent key from %s")
23 % container_name).str(),
24 file, line);
25}
26#define safe_erase(CONT, KEY) \
27 do_safe_erase((CONT), (KEY), #CONT, __FILE__, __LINE__)
28
29
30// errors out if the key already exists
31template <typename T>
32typename T::iterator
33do_safe_insert(T & container, typename T::value_type const & val,
34 char const * container_name, char const * file, int line)
35{
36 std::pair<typename T::iterator, bool> r = container.insert(val);
37 if (!r.second)
38 global_sanity.invariant_failure((F("inserting duplicate entry into %s")
39 % container_name).str(),
40 file, line);
41 return r.first;
42}
43#define safe_insert(CONT, VAL) \
44 do_safe_insert((CONT), (VAL), #CONT, __FILE__, __LINE__)
45
46
47// errors out if the key does not exist
48template <typename T>
49typename T::mapped_type const &
50do_safe_get(T & container, typename T::key_type const & key,
51 char const * container_name, char const * file, int line)
52{
53 typename T::const_iterator i = container.find(key);
54 if (i == container.end())
55 global_sanity.invariant_failure((F("fetching nonexistent entry from %s")
56 % container_name).str(),
57 file, line);
58 return i->second;
59}
60#define safe_get(CONT, VAL) \
61 do_safe_get((CONT), (VAL), #CONT, __FILE__, __LINE__)
62
63// Local Variables:
64// mode: C++
65// fill-column: 76
66// c-file-style: "gnu"
67// indent-tabs-mode: nil
68// End:
69// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:
70
71#endif

Archive Download this file

Branches

Tags

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