Commits

vadimtsushko  committed e81013a

Repository moved to Git and GitHub

  • Participants
  • Parent commits bbeff6d

Comments (0)

Files changed (120)

File .children

-examples/types.dart
-lib/objectory/ObjectoryLib_vm.dart
-tests/allTests.dart
-tests/CursorTest.dart
-tests/DbCommandTest.dart
-tests/objectory/allObjectoryTests.dart
-tests/objectory/PersistentObjectTest.dart
-lib/objectory/objectory_server.dart
-lib/bson/bson.dart
-examples/queries.dart
-third_party/dart-crypto-lib/test/vm/tests.dart
-third_party/dart-crypto-lib/src/hash.dart
-tests/bson/BSonTypesTest.dart
-examples/russian.dart
-tests/bson/allBsonTests.dart
-examples/blog.dart
-third_party/dart-crypto-lib/src/sha1.dart
-third_party/unittest/dom_config.dart
-tests/DbCollectionTest.dart
-third_party/log4dart/LogLib.dart
-tests/DbTest.dart
-tests/bson/BsonObjectIdTest.dart
-third_party/unittest/html_config.dart
-examples/simpleUpdate.dart
-third_party/dart-crypto-lib/src/md5.dart
-lib/objectory/ObjectoryLib_ws.dart
-tests/bson/BsonImplTest.dart
-third_party/unittest/vm_config.dart
-tests/bson/ClientTest/ClientTest.dart
-third_party/unittest/html_enhanced_config.dart
-tests/ConnectionTest.dart
-third_party/dart-crypto-lib/test/browser/test.dart
-third_party/log4dart/test/TestRunner.dart
-third_party/unittest/unittest.dart
-examples/raw_queries.dart
-lib/networking/logger.dart
-lib/mongo.dart
-tests/objectory/ObjectoryImplVmTest.dart
-tests/bson/BsonBinaryTest.dart
-tests/SelectorBuilderTest.dart

File .hgignore

-syntax: glob
-*.txt

File .project

-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
-	<name>mongo-dart</name>
-	<comment></comment>
-	<projects>
-	</projects>
-	<buildSpec>
-		<buildCommand>
-			<name>com.google.dart.tools.core.dartBuilder</name>
-			<arguments>
-			</arguments>
-		</buildCommand>
-	</buildSpec>
-	<natures>
-		<nature>com.google.dart.tools.core.dartNature</nature>
-	</natures>
-</projectDescription>

File LICENSE

-(The MIT License)
-
-Copyright (c) 2012 Vadim Tsushko (vadimtsushko@gmail.com)
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-'Software'), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

File examples/blog.dart

-#import("../lib/mongo.dart");
-#import("dart:builtin");
-
-main(){
-  Db db = new Db("mongo-dart-blog");
-  print("Connecting to ${db.serverConfig.host}:${db.serverConfig.port}");
-  DbCollection collection;
-  DbCollection usersCollection;
-  DbCollection articlesCollection;
-  Map<String,Map> authors = new Map<String,Map>();
-  Map<String,Map> users = new Map<String,Map>();  
-  db.open().chain((o){
-    print(">> Dropping mongo-dart-blog db");
-    db.drop();
-    print("===================================================================================");
-    print(">> Adding Authors");
-    collection = db.collection("authors");
-    collection.insertAll(
-      [{'name':'William Shakespeare', 'email':'william@shakespeare.com', 'age':587},
-      {'name':'Jorge Luis Borges', 'email':'jorge@borges.com', 'age':123}]
-    );
-    return collection.find().each((v){authors[v["name"]] = v;});
-  }).chain((v){  
-    print("===================================================================================");
-    print(">> Authors ordered by age ascending");
-    return collection.find(orderBy:{'age':1}).each(
-      (auth)=>print("[${auth['name']}]:[${auth['email']}]:[${auth['age']}]"));
-  }).chain((v){
-    print("===================================================================================");
-    print(">> Adding Users");
-    usersCollection = db.collection("users");
-    usersCollection.insertAll([{'login':'jdoe', 'name':'John Doe', 'email':'john@doe.com'}, 
-       {'login':'lsmith', 'name':'Lucy Smith', 'email':'lucy@smith.com'}]);
-    return usersCollection.find().each((user)=>users[user["login"]] = user);      
-  }).chain((v){
-    print("===================================================================================");
-    print(">> Users ordered by login ascending");
-    return usersCollection.find(orderBy:{"login":1}).each(
-      (user)=>print("[${user['login']}]:[${user['name']}]:[${user['email']}]"));      
-  }).chain((v){
-    print("===================================================================================");
-    print(">> Adding articles");
-    articlesCollection = db.collection("articles");        
-    articlesCollection.insertAll([
-                                  { 'title':'Caminando por Buenos Aires', 
-                                    'body':'Las callecitas de Buenos Aires tienen ese no se que...', 
-                                    'author_id':authors['Jorge Luis Borges']["_id"]},
-                                  { 'title':'I must have seen thy face before', 
-                                    'body':'Thine eyes call me in a new way', 
-                                    'author_id':authors['William Shakespeare']["_id"], 
-                                    'comments':[{'user_id':users['jdoe']["_id"], 'body':"great article!"}]
-                                  }
-                                ]);
-    print("===================================================================================");
-    print(">> Articles ordered by title ascending");    
-    return articlesCollection.find(orderBy:{"title":1}).each((article){
-      print("[${article['title']}]:[${article['body']}]:[author_id: ${article['author_id']}]");
-    });      
-  }).then((dummy){
-    db.close();
-  });      
-}

File examples/queries.dart

-#import("../lib/mongo.dart");
-#import("dart:builtin");
-main(){  
-  Db db = new Db("mongo-dart-test");
-  var id;
-  DbCollection coll;
-  db.open().chain((c){
-    print('connection open');
-    coll = db.collection("simple_data");
-    coll.remove();
-    print('Packing data to insert into collection by Bson...');
-    for (var n = 0; n<1000; n++){  
-      coll.insert({"my_field":n,"str_field":"str_$n"});
-    }      
-    print('Done. Now sending it to MongoDb...');
-    return coll.findOne(query().eq("my_field", 17));
-  }).chain((val){
-      print("Filtered by my_field=17 $val");
-      id = val["_id"];
-      return coll.findOne(query().id(id));
-  }).chain((val){      
-      print("Filtered by _id=$id: $val");    
-      print("Removing doc with _id=$id");
-      coll.remove(query().id(id));
-      return coll.findOne(query().id(id));
-  }).chain((val){      
-      print("Filtered by _id=$id: $val. There more no such a doc");
-      return coll.find(query().gt("my_field", 995)).each((v)=>print(v));
-  }).chain((val){    
-    print("Filtered by my_field gt 700, lte 703");
-    return coll.find(
-      query().range("my_field", 700, 703, minInclude: false)
-        ).each((v)=>print(v));
-  }).chain((val){
-      print("Filtered by str_field match '^str_(5|7|8)17\$'");
-      return coll.find(
-        query().match('str_field', 'str_(5|7|8)17\$').sortBy("str_field",descending:true).sortBy("my_field")
-          ).each((v)=>print(v));
-  }).chain((val){
-    return coll.findOne(
-      query().match('str_field', 'str_(5|7|8)17\$').sortBy("str_field",descending:true).sortBy("my_field").explain());
-  }).chain((explanation){
-    print("Query explained: $explanation");
-    print('Now where clause with jscript code: where("this.my_field % 100 == 35")');
-    print(query().where("this.my_field == 517"));
-    return coll.find(query().where("this.my_field % 100 == 35")).each((v)=>print(v));
-  }).then((v){
-     db.close();        
-  });
-}

File examples/raw_queries.dart

-#import("../lib/mongo.dart");
-#import("../lib/bson/bson.dart");
-#import("dart:builtin");
-main(){
-  Db db = new Db("mongo-dart-test");
-  DbCollection coll;
-  ObjectId id;
-  db.open().chain((c){
-    print('connection open');
-    coll = db.collection("simple_data");
-    coll.remove();
-    for (var n = 0; n<1000; n++){  
-      coll.insert({"my_field":n,"str_field":"str_$n"});
-    }      
-    return coll.findOne({"my_field": 17});
-  }).chain((val){
-      print("Filtered by my_field=17 $val");
-      id = val["_id"];
-      return coll.findOne({"_id":id});
-  }).chain((val){      
-      print("Filtered by _id=$id: $val");    
-      print("Removing doc with _id=$id");
-      coll.remove({"_id":id});
-      return coll.findOne({"_id":id});
-  }).chain((val){      
-      print("Filtered by _id=$id: $val. There more no such a doc");
-      print("Filtered by {'str_field': {'\$regex': new BsonRegexp('^str_(5|7|8)17\$')}");
-      return coll.find({'str_field': {'\$regex': new BsonRegexp('^str_(5|7|8)17\$')}}).each((v)=>print(v));        
-  }).then((dummy){    
-      db.close();        
-  });
-}

File examples/russian.dart

-#import("../lib/mongo.dart");
-#import("../lib/bson/bson.dart");
-#import("dart:builtin");
-
-main(){
-  Db db = new Db("mongo-dart-test");
-  DbCollection collection;
-  print("Connecting to ${db.serverConfig.host}:${db.serverConfig.port}");
-  db.open().chain((c){  
-    collection = db.collection('test-utf8');
-    collection.remove();  
-    collection.insert({
-      'Имя': 'Вадим', 
-      'Фамилия':'Цушко',
-      'Профессия': 'Брадобрей',
-      'Шаблон': new BsonRegexp('^.adim\$')
-    });    
-    return collection.findOne();
-  }).chain((v){
-    print("Utf8 encoding demonstration. I18 strings may be used not only as values but also as keys");
-    print(v);    
-    return collection.findOne(query().eq('Имя', 'Вадим'));
-  }).chain((v){
-    print("Filtered by query().eq(): $v");
-    return collection.findOne(query().match('Имя', '^..ДИМ\$',caseInsensitive:true));    
-  }).then((v){    
-    print("Filtered by query().match(): $v");
-    db.close();  
-  });  
-}  

File examples/simpleUpdate.dart

-#import("../lib/mongo.dart");
-#import("dart:builtin");
-main(){
-  Db db = new Db('mongo-dart-test');
- 
-  simpleUpdate() {
-    DbCollection coll = db.collection('collection-for-save');
-    coll.remove();  
-    List toInsert = [
-                     {"name":"a", "value": 10},
-                     {"name":"b", "value": 20},
-                     {"name":"c", "value": 30},
-                     {"name":"d", "value": 40}
-                   ];
-    coll.insertAll(toInsert);
-    coll.findOne({"name":"c"}).chain((v1){
-      print("Record c: $v1");
-      v1["value"] = 31;    
-      coll.save(v1);
-      return coll.findOne({"name":"c"});
-    }).then((v2){
-      print("Record c after update: $v2");
-      db.close();
-    });   
-  };
-  
-  db.open().then((c)=>simpleUpdate()); 
-}

File examples/types.dart

-#import("../lib/mongo.dart");
-#import("../lib/bson/bson.dart");
-#import("dart:builtin");
-
-main(){
-  Db db = new Db("mongo-dart-blog");
-  print("Connecting to ${db.serverConfig.host}:${db.serverConfig.port}");
-  db.open().chain((c){  
-    DbCollection collection = db.collection('test-types');
-    collection.remove();  
-    collection.insert({
-      'array':[1,2,3], 
-      'string':'hello', 
-      'hash':{'a':1, 'b':2}, 
-      'date':new Date.now(),          // Stores only milisecond resolution
-      'oid':new ObjectId(),
-      'binary':new Binary.from([0x23,0x24,0x25]),
-      'int':42,
-      'float':33.3333,
-      'regexp': new BsonRegexp(".?dim"),
-      'boolean':true,
-      'where':new BsonCode('this.x == 3'),
-      'null':null
-    });
-    return collection.findOne();
-  }).then((v){    
-    print(v);  
-    db.close();  
-  });  
-}  

File lib/.children

-networking/logger.dart
-bson/bson.dart
-mongo.dart

File lib/.project

-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
-	<name>lib</name>
-	<comment></comment>
-	<projects>
-	</projects>
-	<buildSpec>
-		<buildCommand>
-			<name>com.google.dart.tools.core.dartBuilder</name>
-			<arguments>
-			</arguments>
-		</buildCommand>
-	</buildSpec>
-	<natures>
-		<nature>com.google.dart.tools.core.dartNature</nature>
-	</natures>
-</projectDescription>

File lib/bson/binary.dart

-class Binary extends BsonObject{
-  static final BUFFER_SIZE = 256;
-  static final SUBTYPE_DEFAULT = 0;
-  static final SUBTYPE_FUNCTION = 1;
-  static final SUBTYPE_BYTE_ARRAY = 2;
-  static final SUBTYPE_UUID = 3;
-  static final SUBTYPE_MD5 = 4;
-  static final SUBTYPE_USER_DEFINED = 128;
-  //static final minBits = [1,2,3,4];
-  ByteArray byteArray;
-  Uint8List byteList;
-  int offset;
-  int subType;
-  Binary(int length): byteList = new Uint8List(length), offset=0, subType=0{
-    byteArray = byteList.asByteArray();    
-  }
-  Binary.from(List from): byteList = new Uint8List(from.length),offset=0, subType=0 {    
-    byteList.setRange(0, from.length, from);
-    byteArray = byteList.asByteArray();    
-  }  
-  int get typeByte() => BSON.BSON_DATA_BINARY;  
-  String toHexString(){
-    StringBuffer stringBuffer = new StringBuffer();
-    for (final byte in byteList)
-    {      
-       if (byte < 16){
-        stringBuffer.add("0");
-       }       
-       stringBuffer.add(byte.toRadixString(16));
-    }
-    return stringBuffer.toString().toLowerCase();
-  }  
-  setIntExtended(int value, int numOfBytes){
-    Uint8List byteListTmp = new Uint8List(8);    
-    ByteArray byteArrayTmp = byteListTmp.asByteArray();
-    if (numOfBytes == 3){
-      byteArrayTmp.setInt32(0,value);
-    }
-    else if (numOfBytes > 4 && numOfBytes < 8){
-      byteArrayTmp.setInt64(0,value);
-    }
-    else {
-        throw new Exception("Unsupported num of bits: ${numOfBytes*8}");
-    }
-    byteList.setRange(offset,numOfBytes,byteListTmp);
-  }
-  reverse(int numOfBytes){
-    swap(int x, int y){
-      int t = byteList[x+offset];
-      byteList[x+offset] = byteList[y+offset];
-      byteList[y+offset] = t;
-    }
-    for(int i=0;i<=(numOfBytes-1)%2;i++){
-      swap(i,numOfBytes-1-i);
-    }
-  }
-  encodeInt(int position,int value, int numOfBytes, bool forceBigEndian, bool signed) {
-    int bits = numOfBytes << 3; 
-    int max = Statics.MaxBits(bits);
-
-    if (value >= max || value < -(max / 2)) {
-      throw new Exception("encodeInt::overflow");      
-    }
-    switch(bits) {
-      case 32:
-        byteArray.setInt32(position,value);        
-        break;
-      case 16: 
-        byteArray.setInt16(position,value);
-        break;
-      case 8: 
-        byteArray.setInt8(position,value);        
-        break;
-      case 24:        
-        setIntExtended(value,numOfBytes);
-        break;      
-      default:
-        throw new Exception("Unsupported num of bits: $bits");
-    }
-    if (forceBigEndian){
-      reverse(numOfBytes);
-    }
-  }
-  writeInt(int value, [int numOfBytes=4,bool forceBigEndian=false, bool signed=false]){
-    encodeInt(offset,value, numOfBytes,forceBigEndian,signed);
-    offset += numOfBytes;
-  }
-  writeByte(int value){
-    encodeInt(offset,value, 1,false,false);
-    offset += 1;
-  }
-  int writeDouble(double value){    
-    byteArray.setFloat64(offset, value);
-    offset+=8;
-  } 
-  int writeInt64(int value){    
-    byteArray.setInt64(offset, value);
-    offset+=8;
-  } 
-  int readByte(){    
-    return byteList[offset++];
-  }
-  int readInt32(){    
-    offset+=4;
-    return byteArray.getInt32(offset-4);    
-  }  
-  int readInt64(){    
-    offset+=8;
-    return byteArray.getInt64(offset-8);
-  }    
-  num readDouble(){    
-    offset+=8;
-    return byteArray.getFloat64(offset-8);
-  }    
-
-  String readCString(){ 
-    List<int> stringBytes = [];
-    while (byteList[offset++]!= 0){
-       stringBytes.add(byteList[offset-1]);
-    }
-    return decodeUtf8(stringBytes);
-  }
-  writeCString(String val){
-    final utfData = encodeUtf8(val);
-    byteList.setRange(offset,utfData.length,utfData);
-    offset += utfData.length;
-    writeByte(0);    
- }
-
-  int byteLength() => byteList.length+4+1;
-  bool atEnd() => offset == byteList.length;
-  rewind(){
-    offset = 0;
-  }
-  packValue(Binary buffer){
-    buffer.writeInt(byteList.length);
-    buffer.writeByte(subType);
-    buffer.byteList.setRange(buffer.offset,byteList.length,byteList);
-    buffer.offset += byteList.length;        
-  }  
-  unpackValue(Binary buffer){
-    int size = buffer.readInt32();
-    subType = buffer.readByte();
-    byteList = new Uint8List(size);
-    byteArray = byteList.asByteArray();
-    byteList.setRange(0,size,buffer.byteList,buffer.offset);
-    buffer.offset += size;  
-  }
-  get value()=>this;
-  String toString()=>"Binary(${toHexString()})";
-}

File lib/bson/bson.dart

-#library("bson.dart");
-#import("dart:utf");
-#import("dart:uri");
-#source("bson_type.dart");
-#source("objectid.dart");
-#source("timestamp.dart");
-#source("binary.dart");
-#source("statics.dart");
-#source("min_max_keys.dart");
-#source("bson_int.dart");
-#source("bson_string.dart");
-#source("bson_map.dart");
-#source("bson_array.dart");
-#source("bson_impl.dart");
-#source("bson_double.dart");
-#source("bson_null.dart");
-#source("bson_boolean.dart");
-#source("bson_date.dart");
-#source("bson_regexp.dart");
-
-

File lib/bson/bson_array.dart

-class BsonArray extends BsonObject{
-  List data;
-  int _dataSize;
-  int dataSize(){
-    if (_dataSize === null){
-      _dataSize = 0;
-      for(var i = 0; i < data.length; i++) {
-        _dataSize += elementSize(i.toString(), data[i]);
-      }
-    }    
-    return _dataSize;
-  }
-
-  BsonArray(this.data);
-  get value()=>data;
-  byteLength()=>dataSize()+1+4;
-  int get typeByte() => BSON.BSON_DATA_ARRAY;  
-  packValue(Binary buffer){
-    buffer.writeInt(byteLength());
-      for(var i = 0; i < data.length; i++) {
-         bsonObjectFrom(data[i]).packElement(i.toString() ,buffer);
-      }
-     buffer.writeByte(0);
-  }  
-
-  unpackValue(Binary buffer){
-    data = [];        
-    buffer.offset += 4;
-    int typeByte = buffer.readByte();    
-    while (typeByte != 0){
-      BsonObject bsonObject = bsonObjectFromTypeByte(typeByte);
-      var element = bsonObject.unpackElement(buffer);
-      data.add(element.value);    
-      typeByte = buffer.readByte();
-    }    
-  }
-
-}

File lib/bson/bson_boolean.dart

-class BsonBoolean extends BsonObject{
-  bool data;
-  BsonBoolean(this.data);
-  get value()=>data;
-  byteLength()=>1;
-  int get typeByte() => BSON.BSON_DATA_BOOLEAN;
-  packValue(Binary buffer){
-     buffer.writeByte(data?1:0);
-  }
-  unpackValue(Binary buffer){
-     var b = buffer.readByte();
-     if (b == 1){
-       data = true;
-     }
-     else{
-       data = false;
-     }
-  }
-}

File lib/bson/bson_date.dart

-class BsonDate extends BsonObject{
-  Date data;
-  BsonDate(this.data);
-  get value()=>data;
-  byteLength()=>8;
-  int get typeByte() => BSON.BSON_DATA_DATE;
-  packValue(Binary buffer){
-     buffer.writeInt64(data.value);
-  }
-  unpackValue(Binary buffer){
-     data = new Date.fromEpoch(buffer.readInt64(), new TimeZone.local());
-  }
-}

File lib/bson/bson_double.dart

-class BsonDouble extends BsonObject{
-  double data;
-  BsonDouble(this.data);
-  get value()=>data;
-  byteLength()=>8;
-  int get typeByte() => BSON.BSON_DATA_NUMBER;
-  packValue(Binary buffer){
-     buffer.writeDouble(data);
-  }
-  unpackValue(Binary buffer){
-     data = buffer.readDouble();
-  }
-}

File lib/bson/bson_impl.dart

-class BSON {
-
-  static final BSON_INT32_MAX = 0x7FFFFFFF;
-  static final BSON_INT32_MIN = -0x80000000;
-
-  //static final BSON_INT64_MAX = Math.pow(2, 63) - 1;
-  //static final BSON_INT64_MIN = -Math.pow(2, 63);
-
-  // JS MAX PRECISE VALUES
-  static final JS_INT_MAX = 0x20000000000000;  // Any integer up to 2^53 can be precisely represented by a double.
-  static final JS_INT_MIN = -0x20000000000000;  // Any integer down to -2^53 can be precisely represented by a double.
-
-  // Internal long versions
-  static final JS_INT_MAX_LONG = 0x20000000000000;  // Any integer up to 2^53 can be precisely represented by a double.
-  static final JS_INT_MIN_LONG = -0x20000000000000;  // Any integer down to -2^53 can be precisely represented by a double.
-
-  /**
-   * Number BSON Type
-   *  
-   * @classconstant BSON_DATA_NUMBER
-   **/
-  static final BSON_DATA_NUMBER = 1;
-  /**
-   * String BSON Type
-   *  
-   * @classconstant BSON_DATA_STRING
-   **/
-  static final BSON_DATA_STRING = 2;
-  /**
-   * Object BSON Type
-   *  
-   * @classconstant BSON_DATA_OBJECT
-   **/
-  static final BSON_DATA_OBJECT = 3;
-  /**
-   * Array BSON Type
-   *  
-   * @classconstant BSON_DATA_ARRAY
-   **/
-  static final BSON_DATA_ARRAY = 4;
-  /**
-   * Binary BSON Type
-   *  
-   * @classconstant BSON_DATA_BINARY
-   **/
-  static final BSON_DATA_BINARY = 5;
-  /**
-   * ObjectID BSON Type
-   *  
-   * @classconstant BSON_DATA_OID
-   **/
-  static final BSON_DATA_OID = 7;
-  /**
-   * Boolean BSON Type
-   *  
-   * @classconstant BSON_DATA_BOOLEAN
-   **/
-  static final BSON_DATA_BOOLEAN = 8;
-  /**
-   * Date BSON Type
-   *  
-   * @classconstant BSON_DATA_DATE
-   **/
-  static final BSON_DATA_DATE = 9;
-  /**
-   * null BSON Type
-   *  
-   * @classconstant BSON_DATA_NULL
-   **/
-  static final BSON_DATA_NULL = 10;
-  /**
-   * RegExp BSON Type
-   *  
-   * @classconstant BSON_DATA_REGEXP
-   **/
-  static final BSON_DATA_REGEXP = 11;
-  /**
-   * Code BSON Type
-   *  
-   * @classconstant BSON_DATA_CODE
-   **/
-  static final BSON_DATA_CODE = 13;
-  /**
-   * Symbol BSON Type
-   *  
-   * @classconstant BSON_DATA_SYMBOL
-   **/
-  static final BSON_DATA_SYMBOL = 14;
-  /**
-   * Code with Scope BSON Type
-   *  
-   * @classconstant BSON_DATA_CODE_W_SCOPE
-   **/
-  static final BSON_DATA_CODE_W_SCOPE = 15;
-  /**
-   * 32 bit Integer BSON Type
-   *  
-   * @classconstant BSON_DATA_INT
-   **/
-  static final BSON_DATA_INT = 16;
-  /**
-   * Timestamp BSON Type
-   *  
-   * @classconstant BSON_DATA_TIMESTAMP
-   **/
-  static final BSON_DATA_TIMESTAMP = 17;
-  /**
-   * Long BSON Type
-   *  
-   * @classconstant BSON_DATA_LONG
-   **/
-  static final BSON_DATA_LONG = 18;
-  /**
-   * MinKey BSON Type
-   *  
-   * @classconstant BSON_DATA_MIN_KEY
-   **/
-  static final BSON_DATA_MIN_KEY = 0xff;
-  /**
-   * MaxKey BSON Type
-   *  
-   * @classconstant BSON_DATA_MAX_KEY
-   **/
-  static final BSON_DATA_MAX_KEY = 0x7f;
-
-  /**
-   * Binary Default Type
-   *  
-   * @classconstant BSON_BINARY_SUBTYPE_DEFAULT
-   **/
-  static final BSON_BINARY_SUBTYPE_DEFAULT = 0;
-  /**
-   * Binary Function Type
-   *  
-   * @classconstant BSON_BINARY_SUBTYPE_FUNCTION
-   **/
-  static final BSON_BINARY_SUBTYPE_FUNCTION = 1;
-  /**
-   * Binary Byte Array Type
-   *  
-   * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
-   **/
-  static final BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
-  /**
-   * Binary UUID Type
-   *  
-   * @classconstant BSON_BINARY_SUBTYPE_UUID
-   **/
-  static final BSON_BINARY_SUBTYPE_UUID = 3;
-  /**
-   * Binary MD5 Type
-   *  
-   * @classconstant BSON_BINARY_SUBTYPE_MD5
-   **/
-  static final BSON_BINARY_SUBTYPE_MD5 = 4;
-  /**
-   * Binary User Defined Type
-   *  
-   * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
-   **/
-  static final BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
-
-
-  Binary serialize(var object, [int offset = 0]) {
-    if (!((object is Map) || (object is List))){
-      throw new Exception("Invalid value for BSON serialize: $object");
-    }
-    BsonObject bsonObject = bsonObjectFrom(object);    
-    Binary buffer = new Binary(bsonObject.byteLength()+offset);
-    buffer.offset = offset;
-    bsonObjectFrom(object).packValue(buffer);
-    return buffer;  
-  }
-  deserialize(Binary buffer){
-    if(buffer.byteList.length < 5){
-      throw new Exception("corrupt bson message < 5 bytes long");
-    }    
-    var bsonMap = new BsonMap(null);
-    bsonMap.unpackValue(buffer);
-    return bsonMap.value;
-  }
-}

File lib/bson/bson_int.dart

-class BsonInt extends BsonObject{
-  int data;
-  BsonInt(this.data);
-  get value()=>data;
-  byteLength()=>4;
-  int get typeByte() => BSON.BSON_DATA_INT;
-  packValue(Binary buffer){
-     buffer.writeInt(data);
-  }
-  unpackValue(Binary buffer){
-     data = buffer.readInt32();
-  }
-}

File lib/bson/bson_map.dart

-class BsonMap extends BsonObject{
-  Map data;
-  Map utfKeys;
-  int _dataSize;
-  int dataSize(){
-    if (_dataSize === null){
-      _dataSize = 0;
-      data.forEach((String key, var value)
-        {
-           _dataSize += elementSize(key, value);
-        });
-    }    
-    return _dataSize;
-  }
-  BsonMap(this.data);
-  get value()=>data;
-  byteLength()=>dataSize()+1+4;
-  int get typeByte() => BSON.BSON_DATA_OBJECT;  
-  packValue(Binary buffer){
-    buffer.writeInt(byteLength());
-    data.forEach((var key, var value)
-      {
-         bsonObjectFrom(value).packElement(key ,buffer);
-      });     
-     buffer.writeByte(0);
-  }
-  unpackValue(Binary buffer){
-    data = {};    
-    buffer.offset += 4;    
-    int typeByte = buffer.readByte();
-    while (typeByte != 0){
-      BsonObject bsonObject = bsonObjectFromTypeByte(typeByte);
-      var element = bsonObject.unpackElement(buffer);
-      data[element.name] = element.value;    
-      typeByte = buffer.readByte();
-    }    
-  }
-}

File lib/bson/bson_null.dart

-class BsonNull extends BsonObject{  
-  BsonNull();
-  get value()=>null;
-  byteLength()=>0;
-  int get typeByte() => BSON.BSON_DATA_NULL;
-  packValue(Binary buffer){     
-  }
-  unpackValue(Binary buffer){  
-  }
-}

File lib/bson/bson_regexp.dart

-class BsonRegexp extends BsonObject{
-  String pattern;
-  String options;
-  BsonCString bsonPattern;
-  BsonCString bsonOptions;
-
-  bool multiLine;
-  bool caseInsensitive;
-  bool verbose;
-  bool dotAll;
-  bool extended;
-  BsonRegexp(this.pattern,[this.multiLine=false,this.caseInsensitive=false,this.dotAll=false,this.extended=false]):options=""{
-    createOptionsString();    
-    bsonPattern = new BsonCString(pattern,false);
-    bsonOptions = new BsonCString(options,false);
-  }  
-  get value()=>this;
-  int get typeByte() => BSON.BSON_DATA_REGEXP;  
-  byteLength()=>bsonPattern.byteLength()+bsonOptions.byteLength();
-  unpackValue(Binary buffer){
-    pattern = buffer.readCString();
-    options = buffer.readCString();     
-  }   
-  createOptionsString(){
-    var buffer = new StringBuffer();
-    if (caseInsensitive === true){
-      buffer.add("i");
-    }
-    if (multiLine === true){
-      buffer.add("m");
-    }    
-    if (dotAll === true){
-      buffer.add("s");
-    }    
-    if (extended === true){
-      buffer.add("x");
-    }    
-    options = buffer.toString();
-  }
-  toString()=>"BsonRegexp('$pattern',options:'$options')";
-  packValue(Binary buffer){     
-     bsonPattern.packValue(buffer);
-     bsonOptions.packValue(buffer);
-  }  
-}

File lib/bson/bson_string.dart

-class BsonString extends BsonObject{
-  String data;
-  List<int> _utfData;  
-  List<int> get utfData(){
-    if (_utfData === null){
-      _utfData = encodeUtf8(data);
-    }
-    return _utfData;
-  }  
-  BsonString(this.data);
-  get value()=>data;
-  byteLength()=>utfData.length+1+4;
-  int get typeByte() => BSON.BSON_DATA_STRING;  
-  packValue(Binary buffer){
-     buffer.writeInt(utfData.length+1);
-     buffer.byteList.setRange(buffer.offset,utfData.length,utfData);
-     buffer.offset += utfData.length;
-     buffer.writeByte(0);
-  }
-  unpackValue(Binary buffer){
-     int size = buffer.readInt32()-1; 
-     data = decodeUtf8(buffer.byteList,buffer.offset,size);
-     buffer.offset += size+1;
-  }
-}
-class BsonCode extends BsonString{
-  get value()=>this;
-  int get typeByte() => BSON.BSON_DATA_CODE;
-  BsonCode(String data):super(data);
-  String toString()=>"BsonCode('$data')";  
-}
-class BsonCString extends BsonString{
-  bool useKeyCash;
-  int get typeByte(){
-   throw "Function typeByte of BsonCString must not be called";
-  }   
-  BsonCString(String data, [this.useKeyCash = true]): super(data);
-  List<int> get utfData(){
-    if (useKeyCash){
-      return Statics.getKeyUtf8(data);
-    }
-    else {
-      return super.utfData;
-    }    
-  }  
-
-  byteLength()=>utfData.length+1;
-  packValue(Binary buffer){
-     buffer.byteList.setRange(buffer.offset,utfData.length,utfData);
-     buffer.offset += utfData.length;
-     buffer.writeByte(0);
-  }  
-}

File lib/bson/bson_type.dart

-class _ElementPair{
-  String name;
-  var value;
-  _ElementPair([this.name,this.value]);
-}
-class BsonObject {  
-  int get typeByte(){ throw const Exception("must be implemented");}
-  int byteLength() => 0;
-  packElement(String name, var buffer){
-    buffer.writeByte(typeByte);
-    if (name !== null){
-      new BsonCString(name).packValue(buffer);
-    }
-    packValue(buffer);
-  } 
-  packValue(var buffer){ throw const Exception("must be implemented");}
-  _ElementPair unpackElement(buffer){
-    _ElementPair result = new _ElementPair();
-    result.name = buffer.readCString();    
-    unpackValue(buffer);
-    result.value = value;
-    return result;
-  }
-  unpackValue(var buffer){ throw const Exception("must be implemented");}
-  get value()=>null;
-}
-int elementSize(String name, value) {
-  int size = 1;
-  if (name !== null){
-    size += Statics.getKeyUtf8(name).length + 1;
-  } 
-  size += bsonObjectFrom(value).byteLength();
-  return size;
-}
-BsonObject bsonObjectFrom(var value){
-  if (value is BsonObject){
-    return value;
-  }
-  if (value is int){
-    return new BsonInt(value);
-  }    
-  if (value is num){
-    return new BsonDouble(value);
-  } 
-
-  if (value is String){
-    return new BsonString(value);
-  }        
-  if (value is Map){
-    return new BsonMap(value);
-  }        
-  if (value is List){
-    return new BsonArray(value);
-  }        
-  if (value === null){
-    return new BsonNull();
-  }
-  if (value is Date){
-    return new BsonDate(value);
-  }  
-  if (value === true || value === false){
-    return new BsonBoolean(value);
-  }
-  if (value is BsonRegexp){
-    return value;
-  }  
-  throw new Exception("Not implemented for $value");           
-}  
-
-BsonObject bsonObjectFromTypeByte(int typeByte){
-  switch(typeByte){
-    case BSON.BSON_DATA_INT:
-      return new BsonInt(null);
-    case BSON.BSON_DATA_NUMBER:
-      return new BsonDouble(null);
-    case BSON.BSON_DATA_STRING:
-      return new BsonString(null);
-    case BSON.BSON_DATA_ARRAY:
-      return new BsonArray([]);
-    case BSON.BSON_DATA_OBJECT:
-      return new BsonMap({});
-    case BSON.BSON_DATA_OID:
-      return new ObjectId();
-    case BSON.BSON_DATA_NULL:
-      return new BsonNull();
-    case BSON.BSON_DATA_BOOLEAN:
-      return new BsonBoolean(false);
-    case BSON.BSON_DATA_BINARY:
-      return new Binary(0);
-    case BSON.BSON_DATA_DATE:
-      return new BsonDate(null);
-    case BSON.BSON_DATA_CODE:
-      return new BsonCode(null);
-    case BSON.BSON_DATA_REGEXP:
-      return new BsonRegexp(null);      
-    default:
-      throw new Exception("Not implemented for BSON TYPE $typeByte");           
-  }  
-}
-

File lib/bson/min_max_keys.dart

-class MinKey extends BsonObject{
-
-}
-class MaxKey extends BsonObject{  
-}

File lib/bson/objectid.dart

-class ObjectId extends BsonObject{  
-  Binary id;
-  factory ObjectId(){
-    Timestamp ts = new Timestamp(null,0);    
-    return new ObjectId.fromSeconds(ts.seconds);
-  }
-  ObjectId.fromSeconds(int seconds): id=new Binary(12){
-    id.writeInt(seconds,4,forceBigEndian:true);
-    /* Todo - restore whan Math.random would work
-    id.writeInt(Statics.MachineId,3);
-    id.writeInt(Statics.Pid,2);    
-    */
-    id.writeInt((seconds & 0xFFFFFF).floor().toInt(),3);
-    id.writeInt((seconds & 0xFFFF).floor().toInt(),2);
-    id.writeInt(Statics.nextIncrement,3,forceBigEndian:true);
-  }  
-  String toString()=>"ObjectId(${id.toHexString()})";
-  int get typeByte() => BSON.BSON_DATA_OID;
-  get value() => this;
-  int byteLength() => 12;
-  unpackValue(Binary buffer){
-     id.byteList.setRange(0,12,buffer.byteList,buffer.offset);
-     buffer.offset += 12;
-  }
-  packValue(Binary buffer){
-    buffer.byteList.setRange(buffer.offset,12,id.byteList);
-    buffer.offset += 12;
-  } 
-}

File lib/bson/statics.dart

-class Statics{
-  static Stopwatch _stopwatch;  
-  static startStopwatch() => _stopwatch = new Stopwatch.start();
-  static stopStopwatch() => _stopwatch.stop();
-  static Duration getElapsedTime(){
-    _stopwatch.stop();
-    return new Duration(milliseconds: _stopwatch.elapsedInMs());        
-  }
-  static int _current_increment;
-  static int get nextIncrement()
-  {
-    if (_current_increment === null)
-    {
-      _current_increment = 0;
-    } 
-    return _current_increment++;
-  }   
-  static int _requestId;
-  static int get nextRequestId()
-  {
-    if (_requestId === null)
-    {
-      _requestId = 1;
-    } 
-    return ++_requestId;
-  }   
-
-  static List<int> _maxBits;  
-  static int MaxBits(int bits){    
-    int res;
-    if (_maxBits === null){
-      _maxBits = new List<int>(65);
-      _maxBits[0] = 0;
-      for (var i = 1; i < 65; i++) {
-        _maxBits[i]=(2 << i-1);
-      }
-    }
-    return _maxBits[bits];
-  }
-  static num _MashineId;
-  static num get MachineId(){
-    if (_MashineId === null){
-       _MashineId = (Math.random() * 0xFFFFFFFF).floor().toInt();
-    }
-    return _MashineId;
-  }
-  static num _Pid;
-  static num get Pid(){
-    if (_Pid === null){
-       _Pid = (Math.random() * 0xFFFF).floor().toInt();
-    }
-    return _Pid;
-  }
-  static Map<String,List<int>> _keys;
-  static Map<String,List<int>> get keys(){
-    if (_keys === null){
-       _keys = new Map<String,List<int>>();
-    }
-    return _keys;
-  }
-  static getKeyUtf8(String key){
-    if (!keys.containsKey(key)){      
-      keys[key] = encodeUtf8(key);    
-    }
-    return keys[key];
-  }
-}

File lib/bson/timestamp.dart

-class Timestamp extends BsonObject{  
-  int seconds;
-  int increment;  
-  Timestamp([this.seconds,this.increment]){
-    if (seconds === null){
-      seconds = (new Date.now().value / 1000).toInt();
-    }
-    if (increment === null){
-      increment = Statics.nextIncrement;
-    }          
-  }
-  String toString()=>"Timestamp(seconds: $seconds, increment: $increment)";
-  int byteLength() => 8;  
-}

File lib/cursor.dart

-typedef MonadicBlock(var value);
-class Cursor{
-/**
- * Init state
- *  
- * @classconstant INIT
- **/
-static final INIT = 0;
-
-/**
- * Cursor open
- *  
- * @classconstant OPEN
- **/
-static final OPEN = 1;
-
-/**
- * Cursor closed
- *  
- * @classconstant CLOSED
- **/
-static final CLOSED = 2;
-
-
-  int state = INIT;
-  int cursorId = 0;
-  Db db;
-  Queue items;
-  DbCollection collection;
-  Map selector;
-  Map fields;
-  int skip;
-  int limit;
-  Map sort;
-  Map hint;
-  MonadicBlock eachCallback;
-  var eachComplete;
-  bool explain;
-  int flags = 0;  
-  Cursor(this.db, this.collection, [this.selector, this.fields, this.skip=0, this.limit=0
-  , this.sort, this.hint, this.explain]){
-    if (selector === null){
-      selector = {};
-    } else{
-      if (!selector.containsKey("query")){
-        selector = {"query": selector};
-      }          
-    }
-    if (sort !== null){
-      selector["orderby"] = sort;
-    }
-    items = new Queue();
-  }
-  MongoQueryMessage generateQueryMessage(){
-    return new  MongoQueryMessage(collection.fullName(),
-            flags,
-            skip,
-            limit,
-            selector,
-            fields);
-  }
-  MongoGetMoreMessage generateGetMoreMessage(){
-    return new  MongoGetMoreMessage(collection.fullName(),
-            cursorId);
-  }
-  
-  
-  Map getNextItem(){
-    return items.removeFirst();
-  }
-  Future<Map> nextObject(){
-    if (state == INIT){
-      Completer<Map> nextItem = new Completer<Map>();
-      MongoQueryMessage qm = generateQueryMessage();
-      Future<MongoReplyMessage> reply = db.executeQueryMessage(qm);
-      reply.then((replyMessage){
-        state = OPEN;
-        //print("${replyMessage.cursorId}");
-        cursorId = replyMessage.cursorId;
-        items.addAll(replyMessage.documents);
-        if (items.length > 0){
-          Map nextDoc = getNextItem();
-          debug("Cursor getNextItem $nextDoc");
-          nextItem.complete(nextDoc);
-        }
-        else{
-          nextItem.complete(null);
-        }
-      });
-      return nextItem.future;
-    }  
-    else if (state == OPEN && items.length > 0){
-      return new Future.immediate(getNextItem());
-    }
-    else if (state == OPEN && cursorId > 0){
-      Completer nextItem = new Completer();
-      var qm = generateGetMoreMessage();
-      Future<MongoReplyMessage> reply = db.executeQueryMessage(qm);
-      reply.then((replyMessage){
-        state = OPEN;
-        cursorId = replyMessage.cursorId;
-        items.addAll(replyMessage.documents);
-        if (items.length > 0){
-          nextItem.complete(getNextItem());
-        }
-        else{
-          state = CLOSED;          
-          nextItem.complete(null);
-        }
-      });
-      return nextItem.future;
-    }    
-    else {
-      state = CLOSED;
-      return new Future.immediate(null);
-    }
-  }
-  nextEach(){
-    nextObject().then((val){
-      if (val === null){
-        eachCallback = null;
-        eachComplete.complete(true);
-      } else {
-        eachCallback(val);
-        nextEach();
-      }            
-    });
-  }
-  
-  Future<bool> each(MonadicBlock callback){
-    eachCallback = callback; 
-    eachComplete = new Completer();
-    nextEach();
-    return eachComplete.future;
-  }
-  Future<List<Map>> toList(){
-    List<Map> result = [];
-    Completer completer = new Completer();
-    this.each((v)=>result.addLast(v)).then((v)=>completer.complete(result));
-    return completer.future;    
-  }
-  close(){
-    debug("Closing cursor, cursorId = $cursorId");
-    if (cursorId != 0){      
-      MongoKillCursorsMessage msg = new MongoKillCursorsMessage(cursorId);
-      db.executeMessage(msg);
-      cursorId = 0;
-    } 
-    state = CLOSED;
-  }
-}

File lib/db.dart

-class Db{
-  String databaseName;
-  ServerConfig serverConfig;
-  Connection connection;
-  validateDatabaseName(String dbName) {
-    if(dbName.length === 0) throw "database name cannot be the empty string";  
-    var invalidChars = [" ", ".", "\$", "/", "\\"];
-    for(var i = 0; i < invalidChars.length; i++) {
-      if(dbName.indexOf(invalidChars[i]) != -1) throw new Exception("database names cannot contain the character '" + invalidChars[i] + "'");
-    }
-  }    
-  Db(this.databaseName, [this.serverConfig]){
-     if (serverConfig === null) {
-      serverConfig = new ServerConfig();
-     }
-    connection = new Connection(serverConfig);
-  }      
-  DbCollection collection(String collectionName){
-      return new DbCollection(this,collectionName);
-  }
-  Future<MongoReplyMessage> executeQueryMessage(MongoMessage queryMessage){
-    return connection.query(queryMessage);
-  }  
-  executeMessage(MongoMessage message){
-    connection.execute(message);
-  }    
-  Future<bool> open(){
-//    print("opening db");
-    if (connection.connected){
-      connection.close();
-      connection = new Connection(serverConfig);
-    }
-    return connection.connect();
-  }
-  Future<Map> executeDbCommand(MongoMessage message){
-      Completer<Map> result = new Completer();
-      //print("executeDbCommand.message = ${message}");
-      connection.query(message).then((replyMessage){
-        //print("replyMessage = ${replyMessage}");
-        //print("replyMessage.documents = ${replyMessage.documents}");
-        
-        String errMsg;
-        if (replyMessage.documents.length == 0) {
-          errMsg = "Error executing Db command, Document length 0 $replyMessage";
-          print("Error: $errMsg");
-          var m = new Map();
-          m["errmsg"]=errMsg;
-          result.complete(m);
-        } else  if (replyMessage.documents[0]["ok"] == 1.0){
-          result.complete(replyMessage.documents[0]);
-        } else {
-          errMsg = "Error executing Db command";
-          if (replyMessage.documents[0].containsKey("errmsg")){
-            errMsg = replyMessage.documents[0]["errmsg"];
-          }
-          print("Error: $errMsg");
-          result.complete(replyMessage.documents[0]);
-        }         
-      });
-    return result.future;        
-  }
-  Future<bool> dropCollection(String collectionName){
-    Completer completer = new Completer();
-    collectionsInfoCursor(collectionName).toList().then((v){
-      if (v.length == 1){
-        executeDbCommand(DbCommand.createDropCollectionCommand(this,collectionName))
-          .then((res)=>completer.complete(res));
-        } else{
-          completer.complete(true);
-        }  
-    });    
-    return completer.future;    
-  }
-  Future<Map> drop(){
-    Completer completer = new Completer();
-    executeDbCommand(DbCommand.createDropDatabaseCommand(this))
-      .then((res)=>completer.complete(res));
-    return completer.future;    
-  }
-  
-  removeFromCollection(String collectionName, [Map selector = const {}]){
-    connection.execute(new MongoRemoveMessage("$databaseName.$collectionName", selector));    
-  }    
-  
-  Future<Map> getLastError(){    
-    return executeDbCommand(DbCommand.createGetLastErrorCommand(this));
-  }
-  Future<Map> getNonce(){    
-    return executeDbCommand(DbCommand.createGetNonceCommand(this));
-  }
-
-  Future<Map> wait(){
-    return getLastError();
-  }
-  close(){
-//    print("closing db");
-    connection.close();
-  }
-  
-  Cursor collectionsInfoCursor([String collectionName]) {
-    Map selector = {};
-    // If we are limiting the access to a specific collection name
-    if(collectionName !== null){
-      selector["name"] = this.databaseName + "." + collectionName;
-    }  
-    // Return Cursor
-      return new Cursor(this, new DbCollection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector);      
-  }    
-}

File lib/dbcollection.dart

-class DbCollection{
-  Db db;
-  String collectionName;
-  DbCollection(this.db, this.collectionName){}  
-  String fullName() => "${db.databaseName}.$collectionName";
-  save(Map document){
-    var id;
-    bool createId = false;
-    if (document.containsKey("_id")){
-      id = document["_id"];      
-      if (id === null){
-        createId = true;
-      }
-    }
-    if (id !== null){
-      update({"_id": id}, document);
-    } 
-    else{
-      if (createId) {
-        document["_id"] = new ObjectId();
-      }     
-      insert(document);
-    }
-  }
-  insertAll(List<Map> documents){
-    MongoInsertMessage insertMessage = new MongoInsertMessage(fullName(),documents);
-    return db.executeDbCommand(insertMessage);   
-  }
-  update(Map selector, Map document){
-    MongoUpdateMessage message = new MongoUpdateMessage(fullName(),selector, document, 0);
-    return db.executeMessage(message);   
-  }
-  
-  insert(Map document){
-    return insertAll([document]);
-  } 
-  Cursor find([Map selector = const {}, Map fields = null, Map orderBy, int skip = 0,int limit = 0, bool hint = false, bool explain = false] ){
-    return new Cursor(db, this, selector: selector, fields: fields, skip: skip, limit: limit, sort: orderBy);//, [selector, skip, limit,sort, hint, explain]);
-  }
-  Future<Map> findOne([Map selector = const {}, Map fields = null, Map orderBy, int skip = 0,int limit = 0, bool hint = false, bool explain = false] ){
-    Cursor cursor = find(selector,fields,orderBy,skip,limit,hint,explain);
-    Future<Map> result = cursor.nextObject();
-    cursor.close();
-    return result;
-  }
-  Future drop() => db.dropCollection(collectionName);
-  remove([Map selector = const {}]) => db.removeFromCollection(collectionName, selector);
-  Future count([Map selector = const {}]){
-    Completer completer = new Completer();
-    db.executeDbCommand(DbCommand.createCountCommand(db,collectionName,selector)).then((reply){       
-      //print("reply = ${reply}");
-      completer.complete(reply["n"]);      
-    });
-    return completer.future;
-  }
-}

File lib/helpers/MapProxy.dart

-class MapProxy<K,V> implements Map<K,V>{
-  LinkedHashMap map;
-  Queue keys;
-  MapProxy(): map = new LinkedHashMap();
-  bool containsValue(V value)=>map.containsValue(value);
-  
-  bool containsKey(K key)=>map.containsKey(key);
-  
-  V operator [](K key)=>map[key];
-  
-  void operator []=(K key, V value){
-   map[key]=value;
-  } 
-
-  V putIfAbsent(K key, V ifAbsent())=>map.putIfAbsent(key, ifAbsent);
-  
-  V remove(K key)=>map.remove(key);
-  
-  void clear()=>map.clear();
-
-  void forEach(void f(K key, V value))=>map.forEach(f);
-  
-  Collection<K> getKeys()=>map.getKeys();
-  
-  Collection<V> getValues()=>map.getValues();
-  
-  int get length() => map.length;
-
-  bool isEmpty()=>map.isEmpty();  
-}

File lib/helpers/SelectorBuilder.dart

-SelectorBuilder query(){
-  return new SelectorBuilder();
-}
-class SelectorBuilder<K,V> extends MapProxy<K,V>{
-  toString()=>"SelectorBuilder($map)";
-  SelectorBuilder eq(String fieldName,value){
-    map[fieldName] = value;
-    return this;
-  }
-  SelectorBuilder id(value){
-    map["_id"] = value;
-    return this;
-  }
-  SelectorBuilder ne(String fieldName, value){
-    map[fieldName] = {"\$ne":value};
-    return this;
-  }
-  SelectorBuilder gt(String fieldName,value){
-    map[fieldName] = {"\$gt":value};
-    return this;
-  }
-  SelectorBuilder lt(String fieldName,value){
-    map[fieldName] = {"\$lt":value};
-    return this;
-  }
-  SelectorBuilder gte(String fieldName,value){
-    map[fieldName] = {"\$gte":value};
-    return this;
-  }
-  SelectorBuilder lte(String fieldName,value){    
-    map[fieldName] = {"\$lte":value};
-    return this;
-  }
-  SelectorBuilder all(String fieldName, List values){
-    map[fieldName] = {"\$all":values};
-    return this;
-  }
-  SelectorBuilder nin(String fieldName, List values){
-    map[fieldName] = {"\$nin":values};
-    return this;
-  }
-  SelectorBuilder oneFrom(String fieldName, List values){
-    map[fieldName] = {"\$in":values};
-    return this;
-  } 
-  SelectorBuilder exists(String fieldName){
-    map[fieldName] = {"\$exists":true};
-    return this;    
-  }
-  SelectorBuilder notExists(String fieldName){
-    map[fieldName] = {"\$exists":false};
-    return this;    
-  }
-  SelectorBuilder mod(String fieldName, int value){
-    map[fieldName] = {"\$mod":[value,0]};
-    return this;    
-  }
-  SelectorBuilder match(String fieldName, String pattern,[bool multiLine, bool caseInsensitive, bool dotAll, bool extended]){        
-    map[fieldName] = {'\$regex': new BsonRegexp(pattern,multiLine:multiLine, caseInsensitive:caseInsensitive,
-        dotAll:dotAll,extended:extended)};
-    return this;    
-  }
-  SelectorBuilder range(String fieldName, min, max, [bool minInclude=true, bool maxInclude=true]){
-    Map rangeMap = {};
-    if (minInclude){
-      rangeMap["\$gte"] = min;
-    }
-    else{
-      rangeMap["\$gt"] = min;
-    }
-    if (maxInclude){
-      rangeMap["\$lte"] = max;
-    }
-    else{
-      rangeMap["\$gt"] = max;
-    }
-    map[fieldName] = rangeMap;
-    return this;    
-  }
-  _internQueryMap(){
-    if (!map.containsKey("query")){
-      LinkedHashMap queryMap = new LinkedHashMap.from(map);
-      map.clear();
-      map["query"] = queryMap;
-    }    
-  }
-  SelectorBuilder sortBy(String fieldName, [bool descending=false]){
-    _internQueryMap();
-    if (!map.containsKey("orderby")){
-      map["orderby"] = new LinkedHashMap();  
-    }
-    int order = 1;
-    if (descending){
-      order = -1;
-    }
-    map["orderby"][fieldName] = order;      
-    return this;    
-  }
-  SelectorBuilder comment(String commentStr){
-    _internQueryMap();  
-    map["\$comment"] = commentStr;      
-    return this;    
-  }
-  SelectorBuilder explain(){
-    _internQueryMap();  
-    map["\$explain"] = true;      
-    return this;    
-  }
-  SelectorBuilder snapshot(){
-    _internQueryMap();  
-    map["\$snapshot"] = true;      
-    return this;    
-  }
-  SelectorBuilder showDiskLoc(){
-    _internQueryMap();  
-    map["\$showDiskLoc"] = true;      
-    return this;    
-  }
-  SelectorBuilder returnKey(){
-    _internQueryMap();  
-    map["\$sreturnKey"] = true;      
-    return this;    
-  }  
-  SelectorBuilder where(String javaScriptCode){
-    map["\$where"] = new BsonCode(javaScriptCode);
-    return this;
-  }
-}

File lib/helpers/utils.dart

-logger() { 
-  Utils.setVerboseState(); 
-  Utils.getLogger();  
-}
-setVerboseState(){
-  Utils.setVerboseState();  
-}
-info(String s){
-  Utils.getLogger().info(s);
-}
-warn(String s){
-  Utils.getLogger().warn(s);
-}
-error(String s){
-  Utils.getLogger().error(s);
-}
-debug(String s){
-  Utils.getLogger().debug(s);
-}
-_loggerBuilder(name) {
-  if(name == "Verbose"){
-    File file = new File("log.txt");
-    if (file.existsSync()){
-      file.deleteSync();  
-    }      
-    return new LoggerImpl(name, debugEnabled: true, errorEnabled:true, infoEnabled:true, warnEnabled:true,appenders:[new FileAppender("log.txt")]); 
-  }         
-  // default logger for the rest
-  return new LoggerImpl(name, debugEnabled: false, errorEnabled:true, infoEnabled:false, warnEnabled:true);
-}
-class Utils{
-  static Logger logger;
-  static Logger getLogger(){
-    if (logger === null){
-      LoggerFactory.builder = _loggerBuilder;      
-      logger = LoggerFactory.getLogger("Runtime");
-    } 
-    return logger;
-  }
-  static setVerboseState(){
-    LoggerFactory.builder = _loggerBuilder;    
-    logger = LoggerFactory.getLogger("Verbose");    
-  }
-}

File lib/mongo.dart

-#library("mongo");
-#import("dart:io");
-#import("bson/bson.dart");
-#import("../third_party/log4dart/LogLib.dart");
-#source("networking/connection.dart");
-#source("networking/mongo_message.dart");
-#source("networking/mongo_query_message.dart");
-#source("networking/mongo_reply_message.dart");
-#source("networking/mongo_insert_message.dart");
-#source("networking/mongo_remove_message.dart");
-#source("networking/mongo_getmore_message.dart");
-#source("networking/mongo_kill_cursors_message.dart");
-#source("networking/mongo_update_message.dart");
-#source("networking/server_config.dart");
-#source("networking/dbcommand.dart");
-#source("db.dart");
-#source("dbcollection.dart");
-#source("cursor.dart");
-#source("helpers/utils.dart");
-#source("helpers/MapProxy.dart");
-#source("helpers/SelectorBuilder.dart");

File lib/networking/connection.dart

-class Connection{
-  Map<int,Completer<MongoReplyMessage>> replyCompleters;
-  Binary lengthBuffer;
-  ServerConfig serverConfig;
-  Binary bufferToSend;
-  Queue<MongoMessage> sendQueue;
-  Binary messageBuffer;
-  Socket socket;
-  bool connected = false;
-  Connection([this.serverConfig]){
-    if (serverConfig === null){
-      serverConfig = new ServerConfig();
-    }    
-  }
-  Future<bool> connect(){
-    replyCompleters = new Map();
-    sendQueue = new Queue();
-    socket = new Socket(serverConfig.host, serverConfig.port);
-    Completer completer = new Completer();
-    if (socket is! Socket) {
-      completer.completeException(new Exception( "can't get send socket"));
-    } else {
-      lengthBuffer = new Binary(4);
-      socket.onError = (e) {  
-        print("connect exception ${e}");
-        completer.completeException(e);
-      };
-      socket.onConnect = () {
-        connected = true;
-        completer.complete(true);
-      };
-      return completer.future;
-    }
-    
-  }
-  close(){
-    while (!sendQueue.isEmpty()){
-      sendBuffer("From close");
-    }
-    socket.onData = null;
-    socket.onWrite = null;
-    socket.onError = null;
-    socket.close();
-    replyCompleters.clear();    
-  }
-  getNextBufferToSend(){
-    if (bufferToSend === null || bufferToSend.atEnd()){
-      if(!sendQueue.isEmpty()){
-        MongoMessage message = sendQueue.removeFirst();
-        debug(message.toString());
-        //print(message.toString());
-        bufferToSend = message.serialize();
-        debug(bufferToSend.toHexString());
-      } else {
-        bufferToSend = null;  
-      } 
-    }
-  }
-  sendBufferFromTimer() => sendBuffer("from Timer");
-  sendBufferFromOnWrite() => sendBuffer("from OnWrite");
-  sendBuffer(String origin){
-    debug("sendBuffer($origin)");
-    getNextBufferToSend();
-    if (bufferToSend !== null){      
-      bufferToSend.offset += socket.writeList(bufferToSend.byteList,
-        bufferToSend.offset,bufferToSend.byteList.length-bufferToSend.offset);
-      if (!bufferToSend.atEnd()){        
-       debug("Buffer not send fully, offset: ${bufferToSend.offset}");
-      }
-      new Timer(0,(t)=>sendBufferFromTimer());              
-//      sendBuffer("From sendBuffer");
-    }        
-    else {
-      //print("setting onwrite to null");
-      socket.onWrite = null;        
-    }    
-  }  
-   void receiveData() {
-    if (messageBuffer === null){
-      int numBytes = socket.readList(lengthBuffer.byteList, 0, 4);
-      if (numBytes == 0) {
-        return;
-      }
-      int messageLength = lengthBuffer.readInt32();      
-      messageBuffer = new Binary(messageLength);
-      messageBuffer.writeInt(messageLength);
-    }
-    messageBuffer.offset += socket.readList(messageBuffer.byteList,messageBuffer.offset,messageBuffer.byteList.length-messageBuffer.offset);
-    //print("messageBuffer = ${messageBuffer}");
-    if (messageBuffer.atEnd()){
-      MongoReplyMessage reply = new MongoReplyMessage();
-      messageBuffer.rewind();
-      //print("messageBuffer = ${messageBuffer.byteList}");
-      reply.deserialize(messageBuffer);
-      debug(reply.toString());
-      //print(reply.toString());
-      //print("messageBuffer = ${messageBuffer}");
-      messageBuffer = null;
-      lengthBuffer.rewind();
-      Completer completer = replyCompleters.remove(reply.responseTo);      
-      if (completer !== null){
-        //print("messageBuffer = ${messageBuffer}");
-        completer.complete(reply);       
-      }
-      else {
-        warn("Unexpected respondTo: ${reply.responseTo} ${reply.documents[0]}");
-      }  
-    }   
-  }
-  Future<MongoReplyMessage> query(MongoMessage queryMessage){
-    Completer completer = new Completer();
-    replyCompleters[queryMessage.requestId] = completer;
-    socket.onData = receiveData;
-    sendQueue.addLast(queryMessage);
-//    sendBuffer("From query");
-    socket.onWrite = sendBufferFromOnWrite;    
-    return completer.future;
-  }
-  execute(MongoMessage message){
-    sendQueue.addLast(message);    
-    socket.onWrite = sendBufferFromOnWrite;
-  }
-}

File lib/networking/dbcommand.dart

-class DbCommand extends MongoQueryMessage{
-  // Constants
-  static final SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
-  static final SYSTEM_INDEX_COLLECTION = "system.indexes";
-  static final SYSTEM_PROFILE_COLLECTION = "system.profile";
-  static final SYSTEM_USER_COLLECTION = "system.users";
-  static final SYSTEM_COMMAND_COLLECTION = "\$cmd";
-
-  Db db;  
-  DbCommand(this.db, collectionName, flags, numberToSkip, numberToReturn, query, fields)
-    :super(collectionName,flags, numberToSkip, numberToReturn, query, fields){      
-    _collectionFullName = new BsonCString("${db.databaseName}.$collectionName");      
-  }
-  static DbCommand createDropCollectionCommand(Db db, String collectionName) {
-    return new DbCommand(db,SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'drop':collectionName}, null);
-  }
-  static DbCommand createDropDatabaseCommand(Db db) {
-    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'dropDatabase':1}, null);
-  }
-  static DbCommand createQueryDBCommand(Db db, Map command) {
-    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, 1, command, null);
-  }
-  static DbCommand createDBSlaveOKCommand(Db db, Map command) {
-    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT | MongoQueryMessage.OPTS_SLAVE, 0, -1, command, null);
-  }
-  
-  static DbCommand createPingCommand(Db db) {
-    return createQueryDBCommand(db, {'ping':1});
-  }
-  static DbCommand createGetNonceCommand(Db db) {
-    return createQueryDBCommand(db, {'getnonce':1});
-  }
-
-  static DbCommand createGetLastErrorCommand(Db db) {
-    return createQueryDBCommand(db, {"getlasterror":1});
-  }  
-  static DbCommand createCountCommand(Db db, String collectionName, [Map selector = const {}]) {
-    var finalQuery = new Map();
-    finalQuery["query"] = selector;    
-    finalQuery["count"] = collectionName;
-    return new DbCommand(db, SYSTEM_COMMAND_COLLECTION, MongoQueryMessage.OPTS_NO_CURSOR_TIMEOUT, 0, -1, finalQuery, null);
-  }
-
-}

File lib/networking/logger.dart

-class Logger {
-  
-}

File lib/networking/mongo_getmore_message.dart

-class MongoGetMoreMessage extends MongoMessage{
-  BsonCString _collectionFullName;
-  int cursorId;    
-  int numberToReturn;
-  MongoGetMoreMessage(String collectionFullName,
-            this.cursorId,
-            [this.numberToReturn = 20]
-            ){
-    _collectionFullName = new BsonCString(collectionFullName);    
-    opcode = MongoMessage.GetMore;
-  }
-  int get messageLength(){
-    return 16+4+_collectionFullName.byteLength()+4+8;
-  }
-  Binary serialize(){
-    Binary buffer = new Binary(messageLength);
-    writeMessageHeaderTo(buffer);
-    buffer.writeInt(0);
-    _collectionFullName.packValue(buffer);
-    buffer.writeInt(numberToReturn);
-    buffer.writeInt64(cursorId);
-    buffer.offset = 0;
-    return buffer;
-  }
-  String toString(){
-    return "MongoGetMoreMessage($requestId, ${_collectionFullName.value}, $cursorId)";