00001 // ordering.h 00002 00003 /* Copyright 2009 10gen Inc. 00004 * 00005 * Licensed under the Apache License, Version 2.0 (the "License"); 00006 * you may not use this file except in compliance with the License. 00007 * You may obtain a copy of the License at 00008 * 00009 * http://www.apache.org/licenses/LICENSE-2.0 00010 * 00011 * Unless required by applicable law or agreed to in writing, software 00012 * distributed under the License is distributed on an "AS IS" BASIS, 00013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00014 * See the License for the specific language governing permissions and 00015 * limitations under the License. 00016 */ 00017 00018 #pragma once 00019 00020 namespace mongo { 00021 00026 class Ordering { 00027 const unsigned bits; 00028 const unsigned nkeys; 00029 Ordering(unsigned b,unsigned n) : bits(b),nkeys(n) { } 00030 public: 00035 int get(int i) const { 00036 return ((1 << i) & bits) ? -1 : 1; 00037 } 00038 00039 // for woCompare... 00040 unsigned descending(unsigned mask) const { return bits & mask; } 00041 00042 operator string() const { 00043 StringBuilder buf(32); 00044 for ( unsigned i=0; i<nkeys; i++) 00045 buf.append( get(i) > 0 ? "+" : "-" ); 00046 return buf.str(); 00047 } 00048 00049 static Ordering make(const BSONObj& obj) { 00050 unsigned b = 0; 00051 BSONObjIterator k(obj); 00052 unsigned n = 0; 00053 while( 1 ) { 00054 BSONElement e = k.next(); 00055 if( e.eoo() ) 00056 break; 00057 uassert( 13103, "too many compound keys", n <= 31 ); 00058 if( e.number() < 0 ) 00059 b |= (1 << n); 00060 n++; 00061 } 00062 return Ordering(b,n); 00063 } 00064 }; 00065 00066 }