/src/valijson/include/valijson/constraints/constraint.hpp
Line | Count | Source |
1 | | #pragma once |
2 | | |
3 | | #include <memory> |
4 | | #include <type_traits> |
5 | | |
6 | | namespace valijson { |
7 | | namespace constraints { |
8 | | |
9 | | class ConstraintVisitor; |
10 | | |
11 | | /** |
12 | | * @brief Interface that must be implemented by concrete constraint types. |
13 | | * |
14 | | * @todo Consider using something like the boost::cloneable concept here. |
15 | | */ |
16 | | struct Constraint |
17 | | { |
18 | | /// Typedef for custom new-/malloc-like function |
19 | | typedef void * (*CustomAlloc)(size_t size); |
20 | | |
21 | | /// Typedef for custom free-like function |
22 | | typedef void (*CustomFree)(void *); |
23 | | |
24 | | /// Deleter type to be used with std::unique_ptr / std::shared_ptr |
25 | | /// @tparam T Const or non-const type (same as the one used in unique_ptr/shared_ptr) |
26 | | template<typename T> |
27 | | struct CustomDeleter |
28 | | { |
29 | | CustomDeleter(CustomFree freeFn) |
30 | 432k | : m_freeFn(freeFn) { } |
31 | | |
32 | | void operator()(T *ptr) const |
33 | 432k | { |
34 | 432k | auto *nonconst = const_cast<typename std::remove_const<T>::type *>(ptr); |
35 | 432k | nonconst->~T(); |
36 | 432k | m_freeFn(nonconst); |
37 | 432k | } |
38 | | |
39 | | private: |
40 | | CustomFree m_freeFn; |
41 | | }; |
42 | | |
43 | | /// Exclusive-ownership pointer to automatically handle deallocation |
44 | | typedef std::unique_ptr<const Constraint, CustomDeleter<const Constraint>> OwningPointer; |
45 | | |
46 | | /** |
47 | | * @brief Virtual destructor. |
48 | | */ |
49 | 926k | virtual ~Constraint() = default; |
50 | | |
51 | | /** |
52 | | * @brief Perform an action on the constraint using the visitor pattern. |
53 | | * |
54 | | * Note that Constraints cannot be modified by visitors. |
55 | | * |
56 | | * @param visitor Reference to a ConstraintVisitor object. |
57 | | * |
58 | | * @returns the boolean value returned by one of the visitor's visit |
59 | | * functions. |
60 | | */ |
61 | | virtual bool accept(ConstraintVisitor &visitor) const = 0; |
62 | | |
63 | | /** |
64 | | * @brief Make a copy of a constraint. |
65 | | * |
66 | | * Note that this should be a deep copy of the constraint. |
67 | | * |
68 | | * @returns an owning-pointer to the new constraint. |
69 | | */ |
70 | | virtual OwningPointer clone(CustomAlloc, CustomFree) const = 0; |
71 | | |
72 | | }; |
73 | | |
74 | | } // namespace constraints |
75 | | } // namespace valijson |