Esempio n. 1
0
 /// <summary>
 /// Creates an empty BSON document.
 /// <param name="useStringTable">Whether or not to generate and use a string table.</param>
 /// </summary>
 public BsonDocument(
     BsonStringTableMode mode = BsonStringTableMode.None,
     Dictionary <int, string> reverseStringTable = null)
 {
     _stringTableMode    = mode;
     _stringTable        = new Dictionary <string, int>();
     _reverseStringTable = reverseStringTable;
     Top = new BsonItem();
 }
Esempio n. 2
0
        private void WriteItem(EasyWriter writer, BsonItem item, string name, bool isTop = false, bool isArray = false)
        {
            if (!isTop)
            {
                writer.Write(item.Type);
                writer.Write(isArray ? name : GetKeyName(name), Encoding.UTF8, true);
            }

            if (item.HasValues) // object or array - we need to write a document
            {
                var stream  = new MemoryStream();
                var vWriter = new EasyWriter(stream);
                foreach (string key in item.Keys)
                {
                    WriteItem(vWriter, item[key], key, false, item.IsArray);
                }
                vWriter.Close();
                var data = stream.ToArray();
                // length of data + length of length + null terminator
                writer.Write(data.Length + 4 + 1);
                writer.Write(data);
                writer.Write((byte)0x00);
                return;
            }

            switch (item.Type)
            {
            case 0x01:     // double
                writer.Write((double)item.Value);
                break;

            case 0x02:                          // string
                var bytes = Encoding.UTF8.GetBytes(GetKeyName((string)item.Value, true));
                writer.Write(bytes.Length + 1); // includes null terminator
                writer.WriteBytes(bytes);
                writer.Write((byte)0x00);
                break;

            case 0x05:     // binary
                var byteArray = (byte[])item.Value;
                writer.Write(byteArray.Length);
                writer.Write((byte)0x00);
                writer.Write(byteArray);
                break;

            case 0x07:     // objectid
                writer.Write((byte[])item.Value);
                break;

            case 0x08:     // bool
                writer.Write((bool)item.Value);
                break;

            case 0x09:     // UTC datetime
            case 0x11:     // timestamp
            case 0x12:     // 64 bit int
                writer.Write((long)item.Value);
                break;

            case 0x10:     // 32 bit int
                writer.Write((int)item.Value);
                break;

            default:
                throw new NotSupportedException($"Item type {item.Type} not supported.");
            }
        }