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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
|
// bsoninlines.h
/* Copyright 2009 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <map>
#include "util/atomic_int.h"
namespace mongo {
inline BSONObj BSONElement::embeddedObjectUserCheck() const {
uassert( 10065 , "invalid parameter: expected an object", isABSONObj() );
return BSONObj(value());
}
inline BSONObj BSONElement::embeddedObject() const {
assert( isABSONObj() );
return BSONObj(value());
}
inline BSONObj BSONElement::codeWScopeObject() const {
assert( type() == CodeWScope );
int strSizeWNull = *(int *)( value() + 4 );
return BSONObj( value() + 4 + 4 + strSizeWNull );
}
inline BSONObj BSONObj::copy() const {
char *p = (char*) malloc(objsize());
memcpy(p, objdata(), objsize());
return BSONObj(p, true);
}
// wrap this element up as a singleton object.
inline BSONObj BSONElement::wrap() const {
BSONObjBuilder b(size()+6);
b.append(*this);
return b.obj();
}
inline BSONObj BSONElement::wrap( const char * newName ) const {
BSONObjBuilder b(size()+6+(int)strlen(newName));
b.appendAs(*this,newName);
return b.obj();
}
inline bool BSONObj::hasElement(const char *name) const {
if ( !isEmpty() ) {
BSONObjIterator it(*this);
while ( it.moreWithEOO() ) {
BSONElement e = it.next();
if ( strcmp(name, e.fieldName()) == 0 )
return true;
}
}
return false;
}
inline BSONElement BSONObj::getField(const char *name) const {
BSONObjIterator i(*this);
while ( i.more() ) {
BSONElement e = i.next();
if ( strcmp(e.fieldName(), name) == 0 )
return e;
}
return BSONElement();
}
/* add all the fields from the object specified to this object */
inline BSONObjBuilder& BSONObjBuilder::appendElements(BSONObj x) {
BSONObjIterator it(x);
while ( it.moreWithEOO() ) {
BSONElement e = it.next();
if ( e.eoo() ) break;
append(e);
}
return *this;
}
inline bool BSONObj::isValid(){
int x = objsize();
return x > 0 && x <= 1024 * 1024 * 8;
}
inline bool BSONObj::getObjectID(BSONElement& e) const {
BSONElement f = getField("_id");
if( !f.eoo() ) {
e = f;
return true;
}
return false;
}
inline BSONObjBuilderValueStream::BSONObjBuilderValueStream( BSONObjBuilder * builder ) {
_fieldName = 0;
_builder = builder;
}
template<class T>
inline BSONObjBuilder& BSONObjBuilderValueStream::operator<<( T value ) {
_builder->append(_fieldName, value);
_fieldName = 0;
return *_builder;
}
inline BSONObjBuilder& BSONObjBuilderValueStream::operator<<( const BSONElement& e ) {
_builder->appendAs( e , _fieldName );
_fieldName = 0;
return *_builder;
}
inline Labeler BSONObjBuilderValueStream::operator<<( const Labeler::Label &l ) {
return Labeler( l, this );
}
inline void BSONObjBuilderValueStream::endField( const char *nextFieldName ) {
if ( _fieldName && haveSubobj() ) {
_builder->append( _fieldName, subobj()->done() );
}
_subobj.reset();
_fieldName = nextFieldName;
}
inline BSONObjBuilder *BSONObjBuilderValueStream::subobj() {
if ( !haveSubobj() )
_subobj.reset( new BSONObjBuilder() );
return _subobj.get();
}
template<class T> inline
BSONObjBuilder& Labeler::operator<<( T value ) {
s_->subobj()->append( l_.l_, value );
return *s_->_builder;
}
inline
BSONObjBuilder& Labeler::operator<<( const BSONElement& e ) {
s_->subobj()->appendAs( e, l_.l_ );
return *s_->_builder;
}
// {a: {b:1}} -> {a.b:1}
void nested2dotted(BSONObjBuilder& b, const BSONObj& obj, const string& base="");
inline BSONObj nested2dotted(const BSONObj& obj){
BSONObjBuilder b;
nested2dotted(b, obj);
return b.obj();
}
// {a.b:1} -> {a: {b:1}}
void dotted2nested(BSONObjBuilder& b, const BSONObj& obj);
inline BSONObj dotted2nested(const BSONObj& obj){
BSONObjBuilder b;
dotted2nested(b, obj);
return b.obj();
}
inline BSONObjIterator BSONObjBuilder::iterator() const {
const char * s = _b.buf() + _offset;
const char * e = _b.buf() + _b.len();
return BSONObjIterator( s , e );
}
/* WARNING: nested/dotted conversions are not 100% reversible
* nested2dotted(dotted2nested({a.b: {c:1}})) -> {a.b.c: 1}
* also, dotted2nested ignores order
*/
typedef map<string, BSONElement> BSONMap;
inline BSONMap bson2map(const BSONObj& obj){
BSONMap m;
BSONObjIterator it(obj);
while (it.more()){
BSONElement e = it.next();
m[e.fieldName()] = e;
}
return m;
}
struct BSONElementFieldNameCmp {
bool operator()( const BSONElement &l, const BSONElement &r ) const {
return strcmp( l.fieldName() , r.fieldName() ) <= 0;
}
};
typedef set<BSONElement, BSONElementFieldNameCmp> BSONSortedElements;
inline BSONSortedElements bson2set( const BSONObj& obj ){
BSONSortedElements s;
BSONObjIterator it(obj);
while ( it.more() )
s.insert( it.next() );
return s;
}
inline string BSONObj::toString( bool isArray ) const {
if ( isEmpty() ) return "{}";
stringstream s;
s << ( isArray ? "[ " : "{ " );
BSONObjIterator i(*this);
bool first = true;
while ( 1 ) {
massert( 10327 , "Object does not end with EOO", i.moreWithEOO() );
BSONElement e = i.next( true );
massert( 10328 , "Invalid element size", e.size() > 0 );
massert( 10329 , "Element too large", e.size() < ( 1 << 30 ) );
int offset = (int) (e.rawdata() - this->objdata());
massert( 10330 , "Element extends past end of object",
e.size() + offset <= this->objsize() );
e.validate();
bool end = ( e.size() + offset == this->objsize() );
if ( e.eoo() ) {
massert( 10331 , "EOO Before end of object", end );
break;
}
if ( first )
first = false;
else
s << ", ";
s << e.toString( !isArray );
}
s << ( isArray ? " ]" : " }" );
return s.str();
}
extern unsigned getRandomNumber();
inline void BSONElement::validate() const {
switch( type() ) {
case DBRef:
case Code:
case Symbol:
case mongo::String: {
int x = valuestrsize();
if ( x > 0 && valuestr()[x-1] == 0 )
return;
StringBuilder buf;
buf << "Invalid dbref/code/string/symbol size: " << x << " strnlen:" << strnlen( valuestr() , x );
massert( 10321 , buf.str() , 0 );
break;
}
case CodeWScope: {
int totalSize = *( int * )( value() );
massert( 10322 , "Invalid CodeWScope size", totalSize >= 8 );
int strSizeWNull = *( int * )( value() + 4 );
massert( 10323 , "Invalid CodeWScope string size", totalSize >= strSizeWNull + 4 + 4 );
massert( 10324 , "Invalid CodeWScope string size",
strSizeWNull > 0 &&
strSizeWNull - 1 == strnlen( codeWScopeCode(), strSizeWNull ) );
massert( 10325 , "Invalid CodeWScope size", totalSize >= strSizeWNull + 4 + 4 + 4 );
int objSize = *( int * )( value() + 4 + 4 + strSizeWNull );
massert( 10326 , "Invalid CodeWScope object size", totalSize == 4 + 4 + strSizeWNull + objSize );
// Subobject validation handled elsewhere.
}
case Object:
// We expect Object size validation to be handled elsewhere.
default:
break;
}
}
inline int BSONElement::size( int maxLen ) const {
if ( totalSize >= 0 )
return totalSize;
int remain = maxLen - fieldNameSize() - 1;
int x = 0;
switch ( type() ) {
case EOO:
case Undefined:
case jstNULL:
case MaxKey:
case MinKey:
break;
case mongo::Bool:
x = 1;
break;
case NumberInt:
x = 4;
break;
case Timestamp:
case mongo::Date:
case NumberDouble:
case NumberLong:
x = 8;
break;
case jstOID:
x = 12;
break;
case Symbol:
case Code:
case mongo::String:
massert( 10313 , "Insufficient bytes to calculate element size", maxLen == -1 || remain > 3 );
x = valuestrsize() + 4;
break;
case CodeWScope:
massert( 10314 , "Insufficient bytes to calculate element size", maxLen == -1 || remain > 3 );
x = objsize();
break;
case DBRef:
massert( 10315 , "Insufficient bytes to calculate element size", maxLen == -1 || remain > 3 );
x = valuestrsize() + 4 + 12;
break;
case Object:
case mongo::Array:
massert( 10316 , "Insufficient bytes to calculate element size", maxLen == -1 || remain > 3 );
x = objsize();
break;
case BinData:
massert( 10317 , "Insufficient bytes to calculate element size", maxLen == -1 || remain > 3 );
x = valuestrsize() + 4 + 1/*subtype*/;
break;
case RegEx:
{
const char *p = value();
size_t len1 = ( maxLen == -1 ) ? strlen( p ) : strnlen( p, remain );
massert( 10318 , "Invalid regex string", len1 != -1 );
p = p + len1 + 1;
size_t len2 = ( maxLen == -1 ) ? strlen( p ) : strnlen( p, remain - len1 - 1 );
massert( 10319 , "Invalid regex options string", len2 != -1 );
x = (int) (len1 + 1 + len2 + 1);
}
break;
default: {
stringstream ss;
ss << "BSONElement: bad type " << (int) type();
string msg = ss.str();
massert( 10320 , msg.c_str(),false);
}
}
totalSize = x + fieldNameSize() + 1; // BSONType
return totalSize;
}
inline string BSONElement::toString( bool includeFieldName ) const {
stringstream s;
if ( includeFieldName && type() != EOO )
s << fieldName() << ": ";
switch ( type() ) {
case EOO:
return "EOO";
case mongo::Date:
s << "new Date(" << date() << ')';
break;
case RegEx:
{
s << "/" << regex() << '/';
const char *p = regexFlags();
if ( p ) s << p;
}
break;
case NumberDouble:
{
stringstream tmp;
tmp.precision( 16 );
tmp << number();
string n = tmp.str();
s << n;
// indicate this is a double:
if( strchr(n.c_str(), '.') == 0 && strchr(n.c_str(), 'E') == 0 && strchr(n.c_str(), 'N') == 0 )
s << ".0";
}
break;
case NumberLong:
s << _numberLong();
break;
case NumberInt:
s << _numberInt();
break;
case mongo::Bool:
s << ( boolean() ? "true" : "false" );
break;
case Object:
s << embeddedObject().toString();
break;
case mongo::Array:
s << embeddedObject().toString( true );
break;
case Undefined:
s << "undefined";
break;
case jstNULL:
s << "null";
break;
case MaxKey:
s << "MaxKey";
break;
case MinKey:
s << "MinKey";
break;
case CodeWScope:
s << "CodeWScope( "
<< codeWScopeCode() << ", " << codeWScopeObject().toString() << ")";
break;
case Code:
if ( valuestrsize() > 80 )
s << string(valuestr()).substr(0, 70) << "...";
else {
s << valuestr();
}
break;
case Symbol:
case mongo::String:
if ( valuestrsize() > 80 )
s << '"' << string(valuestr()).substr(0, 70) << "...\"";
else {
s << '"' << valuestr() << '"';
}
break;
case DBRef:
s << "DBRef('" << valuestr() << "',";
{
mongo::OID *x = (mongo::OID *) (valuestr() + valuestrsize());
s << *x << ')';
}
break;
case jstOID:
s << "ObjectId('";
s << __oid() << "')";
break;
case BinData:
s << "BinData";
break;
case Timestamp:
s << "Timestamp " << timestampTime() << "|" << timestampInc();
break;
default:
s << "?type=" << type();
break;
}
return s.str();
}
/* return has eoo() true if no match
supports "." notation to reach into embedded objects
*/
inline BSONElement BSONObj::getFieldDotted(const char *name) const {
BSONElement e = getField( name );
if ( e.eoo() ) {
const char *p = strchr(name, '.');
if ( p ) {
string left(name, p-name);
BSONObj sub = getObjectField(left.c_str());
return sub.isEmpty() ? BSONElement() : sub.getFieldDotted(p+1);
}
}
return e;
}
inline BSONObj BSONObj::getObjectField(const char *name) const {
BSONElement e = getField(name);
BSONType t = e.type();
return t == Object || t == Array ? e.embeddedObject() : BSONObj();
}
inline int BSONObj::nFields() const {
int n = 0;
BSONObjIterator i(*this);
while ( i.moreWithEOO() ) {
BSONElement e = i.next();
if ( e.eoo() )
break;
n++;
}
return n;
}
inline BSONObj::BSONObj() {
/* LITTLE ENDIAN */
static char p[] = { 5, 0, 0, 0, 0 };
_objdata = p;
}
inline BSONObj BSONElement::Obj() const { return embeddedObjectUserCheck(); }
inline BSONElement BSONElement::operator[] (const string& field) const {
BSONObj o = Obj();
return o[field];
}
inline void BSONObj::elems(vector<BSONElement> &v) const {
BSONObjIterator i(*this);
while( i.more() )
v.push_back(i.next());
}
inline void BSONObj::elems(list<BSONElement> &v) const {
BSONObjIterator i(*this);
while( i.more() )
v.push_back(i.next());
}
template <class T>
void BSONObj::Vals(vector<T>& v) const {
BSONObjIterator i(*this);
while( i.more() ) {
T t;
i.next().Val(t);
v.push_back(t);
}
}
template <class T>
void BSONObj::Vals(list<T>& v) const {
BSONObjIterator i(*this);
while( i.more() ) {
T t;
i.next().Val(t);
v.push_back(t);
}
}
template <class T>
void BSONObj::vals(vector<T>& v) const {
BSONObjIterator i(*this);
while( i.more() ) {
try {
T t;
i.next().Val(t);
v.push_back(t);
} catch(...) { }
}
}
template <class T>
void BSONObj::vals(list<T>& v) const {
BSONObjIterator i(*this);
while( i.more() ) {
try {
T t;
i.next().Val(t);
v.push_back(t);
} catch(...) { }
}
}
inline ostream& operator<<( ostream &s, const BSONObj &o ) {
return s << o.toString();
}
inline ostream& operator<<( ostream &s, const BSONElement &e ) {
return s << e.toString();
}
inline void BSONElement::Val(BSONObj& v) const { v = Obj(); }
}
|