]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/contract/example/mitchell02/dictionary.cpp
2 // Copyright (C) 2008-2018 Lorenzo Caminiti
3 // Distributed under the Boost Software License, Version 1.0 (see accompanying
4 // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
5 // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
7 //[mitchell02_dictionary
8 #include <boost/contract.hpp>
13 template<typename K
, typename T
>
15 friend class boost::contract::access
;
17 void invariant() const {
18 BOOST_CONTRACT_ASSERT(count() >= 0); // Non-negative count.
24 // Create empty dictionary.
26 boost::contract::check c
= boost::contract::constructor(this)
28 BOOST_CONTRACT_ASSERT(count() == 0); // Empty.
33 // Destroy dictionary.
34 virtual ~dictionary() {
36 boost::contract::check c
= boost::contract::destructor(this);
41 // Number of key entries.
44 boost::contract::check c
= boost::contract::public_function(this);
49 bool has(K
const& key
) const {
51 boost::contract::check c
= boost::contract::public_function(this)
54 if(count() == 0) BOOST_CONTRACT_ASSERT(!result
);
58 return result
= (items_
.find(key
) != items_
.end());
61 // Value for a given key.
62 T
const& value_for(K
const& key
) const {
63 boost::contract::check c
= boost::contract::public_function(this)
65 BOOST_CONTRACT_ASSERT(has(key
)); // Has key.
69 // Find != end because of precondition (no defensive programming).
70 return items_
.find(key
)->second
;
75 // Add value of a given key.
76 void put(K
const& key
, T
const& value
) {
77 boost::contract::old_ptr
<int> old_count
= BOOST_CONTRACT_OLDOF(count());
78 boost::contract::check c
= boost::contract::public_function(this)
80 BOOST_CONTRACT_ASSERT(!has(key
)); // Has not key already.
83 BOOST_CONTRACT_ASSERT(count() == *old_count
+ 1); // Count inc.
84 BOOST_CONTRACT_ASSERT(has(key
)); // Has key.
86 BOOST_CONTRACT_ASSERT(value_for(key
) == value
);
90 items_
.insert(std::make_pair(key
, value
));
93 // Remove value for given key.
94 void remove(K
const& key
) {
95 boost::contract::old_ptr
<int> old_count
= BOOST_CONTRACT_OLDOF(count());
96 boost::contract::check c
= boost::contract::public_function(this)
98 BOOST_CONTRACT_ASSERT(has(key
)); // Has key.
101 BOOST_CONTRACT_ASSERT(count() == *old_count
- 1); // Count dec.
102 BOOST_CONTRACT_ASSERT(!has(key
)); // Has not key.
110 std::map
<K
, T
> items_
;
114 std::string
const js
= "John Smith";
116 dictionary
<std::string
, int> ages
;
117 assert(!ages
.has(js
));
120 assert(ages
.value_for(js
) == 23);
123 assert(ages
.count() == 0);