summaryrefslogtreecommitdiff
path: root/src/mongo/bson/mutable/algorithm.h
blob: 9e4ffd278e45705450d9900e9093c4cba4fc4256 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/* Copyright 2013 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

#pragma once

#include <algorithm>
#include <cstddef>
#include <vector>

#include "mongo/base/string_data_comparator_interface.h"
#include "mongo/bson/mutable/const_element.h"
#include "mongo/bson/mutable/element.h"
#include "mongo/util/mongoutils/str.h"

namespace mongo {
namespace mutablebson {

/** For an overview of mutable BSON, please see the file document.h in this directory.
 *
 *  This file defines, in analogy with <algorithm>, a collection of useful algorithms for
 *  use with mutable BSON classes. In particular, algorithms for searching, sorting,
 *  indexed access, and counting are included.
 */

/** 'findElement' searches rightward among the sibiling Elements of 'first', returning an
 *  Element representing the first item matching the predicate 'predicate'. If no Element
 *  matches, then the 'ok' method on the returned Element will return false.
 */
template <typename ElementType, typename Predicate>
inline ElementType findElement(ElementType first, Predicate predicate) {
    while (first.ok() && !predicate(first))
        first = first.rightSibling();
    return first;
}

/** A predicate for findElement that matches on the field name of Elements. */
struct FieldNameEquals {
    // The lifetime of this object must be a subset of the lifetime of 'fieldName'.
    explicit FieldNameEquals(StringData fieldName) : fieldName(fieldName) {}

    bool operator()(const ConstElement& element) const {
        return (fieldName == element.getFieldName());
    }

    StringData fieldName;
};

/** An overload of findElement that delegates to the special implementation
 *  Element::findElementNamed to reduce traffic across the Element API.
 */
template <typename ElementType>
inline ElementType findElement(ElementType first, FieldNameEquals predicate) {
    return first.ok() ? first.findElementNamed(predicate.fieldName) : first;
}

/** A convenience wrapper around findElement<ElementType, FieldNameEquals>. */
template <typename ElementType>
inline ElementType findElementNamed(ElementType first, StringData fieldName) {
    return findElement(first, FieldNameEquals(fieldName));
}

/** Finds the first child under 'parent' that matches the given predicate. If no such child
 *  Element is found, the returned Element's 'ok' method will return false.
 */
template <typename ElementType, typename Predicate>
inline ElementType findFirstChild(ElementType parent, Predicate predicate) {
    return findElement(parent.leftchild(), predicate);
}

/** An overload of findFirstChild that delegates to the special implementation
 *  Element::findFirstChildNamed to reduce traffic across the Element API.
 */
template <typename ElementType>
inline ElementType findFirstChild(ElementType parent, FieldNameEquals predicate) {
    return parent.ok() ? parent.findFirstChildNamed(predicate.fieldName) : parent;
}

/** Finds the first child under 'parent' that matches the given field name. If no such child
 *  Element is found, the returned Element's 'ok' method will return false.
 */
template <typename ElementType>
inline ElementType findFirstChildNamed(ElementType parent, StringData fieldName) {
    return findFirstChild(parent, FieldNameEquals(fieldName));
}

/** A less-than ordering for Elements that compares based on the Element field names. */
class FieldNameLessThan {
    // TODO: This should possibly derive from std::binary_function.
public:
    inline bool operator()(const ConstElement& left, const ConstElement& right) const {
        return left.getFieldName() < right.getFieldName();
    }
};

/** Sort any children of Element 'parent' by way of Comparator 'comp', which should provide
 *  an operator() that takes two const Element&'s and implements a strict weak ordering.
 */
template <typename Comparator>
void sortChildren(Element parent, Comparator comp) {
    // TODO: The following works, but obviously is not ideal.

    // First, build a vector of the children.
    std::vector<Element> children;
    Element current = parent.leftChild();
    while (current.ok()) {
        children.push_back(current);
        current = current.rightSibling();
    }

    // Then, sort the child vector with our comparator.
    std::sort(children.begin(), children.end(), comp);

    // Finally, reorder the children of parent according to the ordering established in
    // 'children'.
    std::vector<Element>::iterator where = children.begin();
    const std::vector<Element>::iterator end = children.end();
    for (; where != end; ++where) {
        // Detach from its current location.
        where->remove().transitional_ignore();
        // Make it the new rightmost element.
        parent.pushBack(*where).transitional_ignore();
    }
}

/** Remove any consecutive children that compare as identical according to 'comp'. The
 *  children must be sorted (see sortChildren, above), and the equality comparator here
 *  must be compatible with the comparator used for the sort.
 */
template <typename EqualityComparator>
void deduplicateChildren(Element parent, EqualityComparator equal) {
    Element current = parent.leftChild();
    while (current.ok()) {
        Element next = current.rightSibling();
        if (next.ok() && equal(current, next)) {
            next.remove().transitional_ignore();
        } else {
            current = next;
        }
    }
}

/** A less-than ordering for Elements that compares based on woCompare */
class woLess {
    // TODO: This should possibly derive from std::binary_function.
public:
    woLess(const StringData::ComparatorInterface* comparator, bool considerFieldName = true)
        : _comp(comparator), _considerFieldName(considerFieldName) {}

    inline bool operator()(const ConstElement& left, const ConstElement& right) const {
        return left.compareWithElement(right, _comp, _considerFieldName) < 0;
    }

private:
    const StringData::ComparatorInterface* _comp = nullptr;
    const bool _considerFieldName;
};

/** A greater-than ordering for Elements that compares based on woCompare */
class woGreater {
    // TODO: This should possibly derive from std::binary_function.
public:
    woGreater(const StringData::ComparatorInterface* comparator, bool considerFieldName = true)
        : _comp(comparator), _considerFieldName(considerFieldName) {}

    inline bool operator()(const ConstElement& left, const ConstElement& right) const {
        return left.compareWithElement(right, _comp, _considerFieldName) > 0;
    }

private:
    const StringData::ComparatorInterface* _comp = nullptr;
    const bool _considerFieldName;
};

/** An equality predicate for elements that compares based on woCompare */
class woEqual {
    // TODO: This should possibly derive from std::binary_function.
public:
    woEqual(const StringData::ComparatorInterface* comparator, bool considerFieldName = true)
        : _comp(comparator), _considerFieldName(considerFieldName) {}

    inline bool operator()(const ConstElement& left, const ConstElement& right) const {
        return left.compareWithElement(right, _comp, _considerFieldName) == 0;
    }

private:
    const StringData::ComparatorInterface* _comp = nullptr;
    const bool _considerFieldName;
};

/** An equality predicate for elements that compares based on woCompare */
class woEqualTo {
    // TODO: This should possibly derive from std::binary_function.
public:
    woEqualTo(const ConstElement& value,
              const StringData::ComparatorInterface* comparator,
              bool considerFieldName = true)
        : _value(value), _comp(comparator), _considerFieldName(considerFieldName) {}

    inline bool operator()(const ConstElement& elt) const {
        return _value.compareWithElement(elt, _comp, _considerFieldName) == 0;
    }

private:
    const ConstElement _value;
    const StringData::ComparatorInterface* _comp = nullptr;
    const bool _considerFieldName;
};

// NOTE: Originally, these truly were algorithms, in that they executed the loop over a
// generic ElementType. However, these operations were later made intrinsic to
// Element/Document for performance reasons. These functions hare here for backward
// compatibility, and just delegate to the appropriate Element or ConstElement method of
// the same name.

/** Return the element that is 'n' Elements to the left in the sibling chain of 'element'. */
template <typename ElementType>
ElementType getNthLeftSibling(ElementType element, std::size_t n) {
    return element.leftSibling(n);
}

/** Return the element that is 'n' Elements to the right in the sibling chain of 'element'. */
template <typename ElementType>
ElementType getNthRightSibling(ElementType element, std::size_t n) {
    return element.rightSibling(n);
}

/** Move 'n' Elements left or right in the sibling chain of 'element' */
template <typename ElementType>
ElementType getNthSibling(ElementType element, int n) {
    return (n < 0) ? getNthLeftSibling(element, -n) : getNthRightSibling(element, n);
}

/** Get the child that is 'n' Elements to the right of 'element's left child. */
template <typename ElementType>
ElementType getNthChild(ElementType element, std::size_t n) {
    return element.findNthChild(n);
}

/** Returns the number of valid siblings to the left of 'element'. */
template <typename ElementType>
std::size_t countSiblingsLeft(ElementType element) {
    return element.countSiblingsLeft();
}

/** Returns the number of valid siblings to the right of 'element'. */
template <typename ElementType>
std::size_t countSiblingsRight(ElementType element) {
    return element.countSiblingsRight();
}

/** Return the number of children of 'element'. */
template <typename ElementType>
std::size_t countChildren(ElementType element) {
    return element.countChildren();
}

/** Return the full (path) name of this element separating each name with the delim string. */
template <typename ElementType>
std::string getFullName(ElementType element, char delim = '.') {
    std::vector<StringData> names;
    ElementType curr = element;
    while (curr.ok() && curr.parent().ok()) {
        names.push_back(curr.getFieldName());
        curr = curr.parent();
    }

    mongoutils::str::stream name;
    bool first = true;
    for (std::vector<StringData>::reverse_iterator it = names.rbegin(); it != names.rend(); ++it) {
        if (!first)
            name << delim;
        name << *it;
        first = false;
    }
    return name;
}
}  // namespace mutablebson
}  // namespace mongo