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

Archive Download this file

Branches

Tags

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