MongoDB  2.5.0
ordering.h
1 // ordering.h
2 
3 /* Copyright 2009 10gen Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 namespace mongo {
21 
22  // todo: ideally move to db/ instead of bson/, but elim any dependencies first
23 
29  class Ordering {
30  unsigned bits;
31  Ordering(unsigned b) : bits(b) { }
32  public:
33  Ordering(const Ordering& r) : bits(r.bits) { }
34  void operator=(const Ordering& r) {
35  bits = r.bits;
36  }
37 
42  int get(int i) const {
43  return ((1 << i) & bits) ? -1 : 1;
44  }
45 
46  // for woCompare...
47  unsigned descending(unsigned mask) const { return bits & mask; }
48 
49  /*operator std::string() const {
50  StringBuilder buf;
51  for ( unsigned i=0; i<nkeys; i++)
52  buf.append( get(i) > 0 ? "+" : "-" );
53  return buf.str();
54  }*/
55 
56  static Ordering make(const BSONObj& obj) {
57  unsigned b = 0;
58  BSONObjIterator k(obj);
59  unsigned n = 0;
60  while( 1 ) {
61  BSONElement e = k.next();
62  if( e.eoo() )
63  break;
64  uassert( 13103, "too many compound keys", n <= 31 );
65  if( e.number() < 0 )
66  b |= (1 << n);
67  n++;
68  }
69  return Ordering(b);
70  }
71  };
72 
73 }