示例#1
0
        public void EqualityList()
        {
            // Make initial list
            BList testList = new BList();
            BString testString = new BString("Hello World");
            BInt testInt = new BInt(5);

            testList.Add(testString);
            testList.Add(testInt);

            // Make test list
            BList testList2 = new BList();
            BString testString2 = new BString("Hello World");
            BInt testInt2 = new BInt(5);

            testList2.Add(testString2);
            testList2.Add(testInt2);

            // Test equality recursive
            Assert.AreEqual(testList, testList2);

            // Test null list
            BList nullList = null;
            Assert.IsFalse(testList.Equals(nullList));

            // Test different counts
            testList2.Add(new BInt(10));
            Assert.IsFalse(testList.Equals(testList2));

            // Test different values
            testList.Add(new BInt(9));

            Assert.IsFalse(testList.Equals(testList2));
        }
示例#2
0
        public void DecodeList()
        {
            const string testString = "l1:a11:Hello Worlde";

            BList testExpected = new BList();
            testExpected.Add(new BString("a"));
            testExpected.Add(new BString("Hello World"));

            IBencodingType testResult = BencodingUtils.Decode(testString);

            Assert.AreEqual(testExpected, testResult);
        }
示例#3
0
        public void EncodeList()
        {
            BList testList = new BList();
            BString testString = new BString("Hello World");
            BInt testInt = new BInt(5);

            testList.Add(testString);
            testList.Add(testInt);

            string test = BencodingUtils.EncodeString(testList);

            Assert.AreEqual("l11:Hello Worldi5ee", test);
        }
示例#4
0
        public void BListSetNullValue()
        {
            BList list = new BList();

            list.Add(new BInt(0));
            list[0] = null;
        }
示例#5
0
        public void BListSetValue()
        {
            BList list = new BList();

            list.Add(new BInt(0));
            BInt newInt = new BInt(1);
            list[0] = newInt;

            Assert.AreEqual(newInt, list[0]);
        }
示例#6
0
        public void given_empty_blist_when_one_element_is_added_then_blist_iterator_should_return_element()
        {
            var count = 1;
            var expected = new int[count].Select(_ => _random.Next()).ToArray();

            var blist = new BList<int>();

            foreach (var item in expected)
                blist.Add(item);

            CollectionAssert.AreEqual(expected, blist);
        }
示例#7
0
        public void given_empty_blist_when_elements_are_added_individually_then_blist_count_should_equal_number_added()
        {
            var count = 1024;
            var expected = new int[count].Select(_ => _random.Next()).ToArray();

            var blist = new BList<int>();

            foreach (var item in expected)
                blist.Add(item);

            Assert.That(blist.Count, Is.EqualTo(count));
        }
示例#8
0
        public void given_empty_blist_when_one_element_is_added_then_blist_indexer_should_return_element()
        {
            var count = 1;
            var expected = new int[count].Select(_ => _random.Next()).ToArray();

            var blist = new BList<int>();

            foreach (var item in expected)
                blist.Add(item);

            Assert.That(expected[0], Is.EqualTo(blist[0]));
        }
示例#9
0
        // Adds metadata about how files are treated.
        private static void AddInfo(string torrentName, string directoryRoot, BDictionary info, int pieceLength,
                                    List <FileData> files, List <byte[]> pieces)
        {
            info.Add(TorrentKeys.InfoPieceLength, new BInteger(pieceLength));
            var bencodedPieces = new StringBuilder();

            foreach (var piece in pieces)
            {
                foreach (var data in piece)
                {
                    bencodedPieces.Append((char)data);
                }
            }
            info.Add(TorrentKeys.InfoPieces, new BString(bencodedPieces.ToString()));

            if (files.Count == 1)
            {
                info.Add(TorrentKeys.InfoName, new BString(torrentName));
                info.Add(TorrentKeys.InfoFilesLength, new BInteger(files[0].Length));
            }
            else if (files.Count > 1)
            {
                info.Add(TorrentKeys.InfoName, new BString(directoryRoot));
                var filesList = new BList();

                foreach (FileData inputFile in files)
                {
                    var aFile = new BDictionary();
                    aFile.Add(TorrentKeys.InfoFilesLength, new BInteger(inputFile.Length));

                    var filePath = new BList(inputFile.Path.Split());
                    aFile.Add(TorrentKeys.InfoFilesPath, filePath);
                    filesList.Add(aFile);
                }
                info.Add(TorrentKeys.InfoFiles, filesList);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(files));
            }
        }
示例#10
0
        public static DHTMessage CreateFindNodeQuery(BString transactionID, byte[] nodeId)
        {
            BDictionary sendData = new BDictionary();

            sendData.Add("t", transactionID);
            sendData.Add("y", "q");
            sendData.Add("q", "find_node");

            #if IP6
            var want = new BList();
            want.Add("n6");
            sendData.Add("want", want);
            #endif

            var args = new BDictionary();
            args.Add("id", new BString(nodeId));
            args.Add("target", new BString(DHTHelper.GetRandomHashID()));
            sendData.Add("a", args);

            return(new DHTMessage(MessageType.Query, QueryType.FindNode, sendData));
        }
示例#11
0
        public static DHTMessage CreateFindNodeQuery(BString transactionID, DHTId nodeId, DHTId targetNodeId)
        {
            BDictionary sendData = new BDictionary();

            sendData.Add("t", transactionID);
            sendData.Add("y", "q");
            sendData.Add("q", "find_node");

            #if IP6
            var want = new BList();
            want.Add("n6");
            sendData.Add("want", want);
            #endif

            var args = new BDictionary();
            args.Add("id", nodeId.ToBencodedString());
            args.Add("target", targetNodeId.ToBencodedString());
            sendData.Add("a", args);

            return(new DHTMessage(MessageType.Query, QueryType.FindNode, sendData));
        }
示例#12
0
        public static DHTMessage CreateGetPeersQuery(BString transactionID, DHTId nodeId, DHTId infoHash)
        {
            BDictionary sendData = new BDictionary();

            sendData.Add("t", transactionID);
            sendData.Add("y", "q");
            sendData.Add("q", "get_peers");

            #if IP6
            var want = new BList();
            want.Add("n6");
            sendData.Add("want", want);
            #endif

            var args = new BDictionary();
            args.Add("id", nodeId.ToBencodedString());
            args.Add("info_hash", infoHash.ToBencodedString());
            sendData.Add("a", args);

            return(new DHTMessage(MessageType.Query, QueryType.GetPeers, sendData));
        }
示例#13
0
        public static BDictionary CreateGetPeersQuery(BString transactionID, byte[] nid, byte[] infoHash)
        {
            BDictionary sendData = new BDictionary();

            sendData.Add("t", transactionID);
            sendData.Add("y", "q");
            sendData.Add("q", "get_peers");

#if IP6
            var want = new BList();
            want.Add("n6");
            sendData.Add("want", want);
#endif

            var args = new BDictionary();
            args.Add("id", new BString(nid));
            args.Add("info_hash", new BString(infoHash));
            sendData.Add("a", args);

            return(sendData);
        }
示例#14
0
        public override BDictionary Construct()
        {
            BDictionary arguments = new BDictionary
            {
                { "id", new BString(QueriedNode.Bytes) },
                { "token", new BString(Token.Bytes) }
            };

            if (Peers != null)
            {
                BList peers = new BList(Peers.Length);
                for (int i = 0; i < Peers.Length; i++)
                {
                    peers.Add(new BString(Peers[i].Encode()));
                }
                arguments.Add("values", peers);
            }
            else
            {
                if (Nodes != null)
                {
                    byte[] nodes = new byte[IPv4Node.CompactInfoSize * Nodes.Length];
                    for (int i = 0; i < Nodes.Length; i++)
                    {
                        Nodes[i].Encode(((Span <byte>)nodes).Slice(i * IPv4Node.CompactInfoSize));
                    }
                    arguments.Add("nodes", new BString(nodes));
                }
                if (Nodes6 != null)
                {
                    byte[] nodes6 = new byte[IPv6Node.CompactInfoSize * Nodes6.Length];
                    for (int i = 0; i < Nodes6.Length; i++)
                    {
                        Nodes6[i].Encode(((Span <byte>)nodes6).Slice(i * IPv6Node.CompactInfoSize));
                    }
                    arguments.Add("nodes6", new BString(nodes6));
                }
            }
            return(ConstructResponse(arguments));
        }
示例#15
0
        public static BDictionary GetInfoDictionary(TorrentInfo info)
        {
            var infoDic = new BDictionary
            {
                { Constants.InfoPieceLengthKey, info.PieceLength },
                { Constants.InfoPiecesKey, info.Pieces }
            };

            if (info.Name != null)
            {
                infoDic.Add(Constants.InfoNameKey, info.Name);
            }

            foreach (var(key, value) in info.Extensions)
            {
                infoDic.Add(key, value);
            }

            if (info.Files.Count == 1)
            {
                var(path, len) = info.Files[0];
                infoDic.Add(Constants.InfoLengthKey, len);
            }
            else
            {
                var lst = new BList(info.Files.Count);
                foreach (var(key, value) in info.Files)
                {
                    var fdic = new BDictionary
                    {
                        { Constants.InfoFilePathKey, key },
                        { Constants.InfoFileLengthKey, value }
                    };
                    lst.Add(fdic);
                }
                infoDic.Add(Constants.InfoFilesKey, lst);
            }

            return(infoDic);
        }
示例#16
0
 public void SetNullValue()
 {
     var blist = new BList();
     blist.Add(0);
     blist[0] = null;
 }
示例#17
0
            given_existing_blist_when_elements_are_inserted_at_index_zero_then_blist_iterator_should_return_correct_latest_elements
            ()
        {
            var initial = new int[512].Select(_ => _random.Next()).ToArray();
            var insertzero = new int[256].Select(_ => _random.Next()).ToArray();
            var expected = insertzero.Reverse().Concat(initial).ToArray();

            var blist = new BList<int>();

            foreach (var item in initial)
                blist.Add(item);

            foreach (var item in insertzero)
                blist.Insert(0, item);

            CollectionAssert.AreEqual(expected, blist);
        }
        private static BList ReadList(BinaryReader binaryReader)
        {
            Contract.Requires(binaryReader != null);

            byte i = binaryReader.ReadByte();
            if (i != 'l')
            {
                throw Error();
            }

            BList lst = new BList();

            try
            {
                for (int c = binaryReader.PeekChar(); ; c = binaryReader.PeekChar())
                {
                    if (c == -1) throw Error();
                    if (c == 'e')
                    {
                        binaryReader.ReadByte();
                        break;
                    }
                    lst.Add(ReadElement(binaryReader));
                }
            }
            catch (BencodingException) { throw; }
            catch (Exception e) { throw Error(e); }

            return lst;
        }
示例#19
0
 public void AddNullValue()
 {
     var blist = new BList();
     blist.Add((IBObject)null);
 }
示例#20
0
        /// <summary>
        /// Creates the 'info' part of the torrent.
        /// </summary>
        /// <param name="encoding">The encoding used for writing strings</param>
        /// <returns>A <see cref="BDictionary"/> of the 'info' part of the torrent</returns>
        protected virtual BDictionary CreateInfoDictionary(Encoding encoding)
        {
            var info = new BDictionary();

            if (PieceSize > 0)
                info[TorrentInfoFields.PieceLength] = (BNumber) PieceSize;

            if (Pieces?.Length > 0)
                info[TorrentInfoFields.Pieces] = new BString(Pieces, encoding);

            if (IsPrivate)
                info[TorrentInfoFields.Private] = (BNumber)1;

            if (FileMode == TorrentFileMode.Single)
            {
                info[TorrentInfoFields.Name] = new BString(File.FileName, encoding);
                info[TorrentInfoFields.Length] = (BNumber)File.FileSize;

                if (File.Md5Sum != null)
                    info[TorrentInfoFields.Md5Sum] = new BString(File.Md5Sum, encoding);

            }
            else if (FileMode == TorrentFileMode.Multi)
            {
                info[TorrentInfoFields.Name] = new BString(Files.DirectoryName, encoding);

                var files = new BList<BDictionary>();
                foreach (var file in Files)
                {
                    var fileDictionary = new BDictionary
                    {
                        [TorrentFilesFields.Length] = (BNumber)file.FileSize,
                        [TorrentFilesFields.Path] = new BList(file.Path)
                    };

                    if (file.Md5Sum != null)
                        fileDictionary[TorrentFilesFields.Md5Sum] = new BString(file.Md5Sum, encoding);

                    files.Add(fileDictionary);
                }

                info[TorrentInfoFields.Files] = files;
            }

            return info;
        }
示例#21
0
        public void BListAddNullValue()
        {
            BList list = new BList();

            list.Add(null);
        }
示例#22
0
        static void HandleMessage(BDictionary message, TcpClient client)
        {
            var opValue  = message["op"];
            var opString = opValue as BString;
            var autoCompletionSupportEnabled = RT.booleanCast(((IPersistentMap)configVar.invoke()).valAt(Keyword.intern("nrepl-auto-completion")));

            if (opString != null)
            {
                var session = GetSession(message);
                switch (opString.ToString())
                {
                case "clone":
                    var newSession = CloneSession(session);
                    SendMessage(
                        new BDictionary
                    {
                        { "id", message["id"] },
                        { "status", new BList {
                              "done"
                          } },
                        { "new-session", newSession.ToString() }
                    }, client);
                    break;

                case "describe":
                    // TODO include arcadia version
                    var clojureVersion     = (IPersistentMap)RT.var("clojure.core", "*clojure-version*").deref();
                    var clojureMajor       = (int)clojureVersion.valAt(Keyword.intern("major"));
                    var clojureMinor       = (int)clojureVersion.valAt(Keyword.intern("minor"));
                    var clojureIncremental = (int)clojureVersion.valAt(Keyword.intern("incremental"));
                    var clojureQualifier   = (string)clojureVersion.valAt(Keyword.intern("qualifier"));
                    var supportedOps       = new BDictionary {
                        { "eval", 1 },
                        { "load-file", 1 },
                        { "describe", 1 },
                        { "clone", 1 },
                        { "info", 1 },
                        { "eldoc", 1 },
                        { "classpath", 1 },
                    };
                    // Debug.Log("Autocomplete support is enabled?: " + autoCompletionSupportEnabled);
                    if (autoCompletionSupportEnabled)
                    {
                        supportedOps.Add("complete", 1);
                    }
                    SendMessage(
                        new BDictionary
                    {
                        { "id", message["id"] },
                        { "session", session.ToString() },
                        { "status", new BList {
                              "done"
                          } },
                        { "ops", supportedOps },
                        {
                            "versions",
                            new BDictionary
                            {
                                {
                                    "clojure", new BDictionary
                                    {
                                        { "major", clojureMajor },
                                        { "minor", clojureMinor },
                                        { "incremental", clojureIncremental },
                                        { "qualifier", clojureQualifier }
                                    }
                                },
                                {
                                    "nrepl", new BDictionary
                                    {
                                        { "major", 0 },
                                        { "minor", 2 },
                                        { "incremental", 3 }
                                    }
                                }
                            }
                        }
                    }, client);
                    break;

                case "eval":
                    var fn = new EvalFn(message, client);
                    addCallbackVar.invoke(fn);
                    break;

                case "load-file":
                    message["code"] = new BString("(do " + message["file"].ToString() + " )");
                    var loadFn = new EvalFn(message, client);
                    addCallbackVar.invoke(loadFn);
                    break;

                case "eldoc":
                case "info":

                    String symbolStr = message["symbol"].ToString();

                    // Editors like Calva that support doc-on-hover sometimes will ask about empty strings or spaces
                    if (symbolStr == "" || symbolStr == null || symbolStr == " ")
                    {
                        break;
                    }

                    IPersistentMap symbolMetadata = null;
                    try
                    {
                        symbolMetadata = (IPersistentMap)metaVar.invoke(nsResolveVar.invoke(
                                                                            findNsVar.invoke(symbolVar.invoke(message["ns"].ToString())),
                                                                            symbolVar.invoke(symbolStr)));
                    } catch (TypeNotFoundException) {
                        // We'll just ignore this call if the type cannot be found. This happens sometimes.
                        // TODO: One particular case when this happens is when querying info for a namespace.
                        //       That case should be handled separately (e.g., via `find-ns`?)
                    }


                    if (symbolMetadata != null)
                    {
                        var resultMessage = new BDictionary {
                            { "id", message["id"] },
                            { "session", session.ToString() },
                            { "status", new BList {
                                  "done"
                              } }
                        };

                        foreach (var entry in symbolMetadata)
                        {
                            if (entry.val() != null)
                            {
                                String keyStr = entry.key().ToString().Substring(1);
                                String keyVal = entry.val().ToString();
                                if (keyStr == "arglists")
                                {
                                    keyStr = "arglists-str";
                                }
                                if (keyStr == "forms")
                                {
                                    keyStr = "forms-str";
                                }
                                resultMessage[keyStr] = new BString(keyVal);
                            }
                        }
                        SendMessage(resultMessage, client);
                    }
                    else
                    {
                        SendMessage(
                            new BDictionary
                        {
                            { "id", message["id"] },
                            { "session", session.ToString() },
                            { "status", new BList {
                                  "done", "no-info"
                              } }
                        }, client);
                    }
                    break;

                case "complete":

                    // When autoCompletionSupportEnabled is false, we don't advertise auto-completion support.
                    // some editors seem to ignore this and request anyway, so we return an unknown op message.
                    if (!autoCompletionSupportEnabled)
                    {
                        SendMessage(
                            new BDictionary
                        {
                            { "id", message["id"] },
                            { "session", session.ToString() },
                            { "status", new BList {
                                  "done", "error", "unknown-op"
                              } }
                        }, client);
                        break;
                    }

                    Namespace ns = Namespace.find(Symbol.create(message["ns"].ToString()));
                    var       sessionBindings  = _sessions[session];
                    var       completeBindings = sessionBindings;
                    if (ns != null)
                    {
                        completeBindings = completeBindings.assoc(RT.CurrentNSVar, ns);
                    }

                    // Make sure to eval this in the right namespace
                    Var.pushThreadBindings(completeBindings);
                    BList completions = (BList)completeVar.invoke(message["symbol"].ToString());
                    Var.popThreadBindings();

                    SendMessage(new BDictionary
                    {
                        { "id", message["id"] },
                        { "session", session.ToString() },
                        { "status", new BList {
                              "done"
                          } },
                        { "completions", completions }
                    }, client);
                    break;

                case "classpath":
                    BList classpath = new BList();
                    foreach (String p in Environment.GetEnvironmentVariable("CLOJURE_LOAD_PATH").Split(System.IO.Path.PathSeparator))
                    {
                        if (p != "")
                        {
                            classpath.Add(Path.GetFullPath(p));
                        }
                    }

                    SendMessage(new BDictionary
                    {
                        { "id", message["id"] },
                        { "session", session.ToString() },
                        { "status", new BList {
                              "done"
                          } },
                        { "classpath", classpath },
                    }, client);
                    break;

                default:
                    SendMessage(
                        new BDictionary
                    {
                        { "id", message["id"] },
                        { "session", session.ToString() },
                        { "status", new BList {
                              "done", "error", "unknown-op"
                          } }
                    }, client);
                    break;
                }
            }
        }
        void multiFileTorrent(BDictionary info, TorrentCreationViewModel vm, List<FileInfo> files)
        {
            BList filesList = new BList();

            foreach (FileInfo file in files)
            {
                BDictionary fileDictionary = new BDictionary();
                fileDictionary["length"] = new BInteger(file.Length);

                BList pathList = new BList();

                String relativePath = file.FullName.Remove(0, vm.PathRoot.Length);
                foreach (String elem in relativePath.Split(new char[] { '\\' }))
                {
                    if (!String.IsNullOrEmpty(elem))
                    {
                        pathList.Add(elem);
                    }
                }

                fileDictionary["path"] = pathList;

                filesList.Add(fileDictionary);
            }
          
            info["name"] = new BString(vm.TorrentName);
            info["files"] = filesList;

        }
示例#24
0
        public void performance()
        {
            var stopwatch = new Stopwatch();

            var count = 2 << 16;

            Console.WriteLine($"Count: {count}");
            

            stopwatch.Reset();
            stopwatch.Start();
            {
                var blist = new BList<int>();

                for (int i = 0; i < count; i++)
                {
                    blist.Add(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"B-List - Add Last = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var blist = new BList<int>();

                for (int i = 0; i < count; i++)
                {
                    blist.Insert(blist.Count / 2, _random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"B-List - Add middle = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");


            stopwatch.Reset();
            stopwatch.Start();
            {
                var blist = new BList<int>();

                for (int i = 0; i < count; i++)
                {
                    blist.Insert(0, _random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"B-List - Add First = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");
            

            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new List<int>();

                for (int i = 0; i < count; i++)
                {
                    list.Add(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"List - Add Last = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new List<int>();

                for (int i = 0; i < count; i++)
                {
                    list.Insert(list.Count / 2, _random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"List - Add middle = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");


            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new List<int>();

                for (int i = 0; i < count; i++)
                {
                    list.Insert(0, _random.Next());
                }
            }
            
            stopwatch.Stop();
            Console.WriteLine($"List - Add First = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");


            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new LinkedList<int>();

                for (int i = 0; i < count; i++)
                {
                    list.AddFirst(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"Linked-List - Add Last = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var linkedlist = new LinkedList<int>();

                var last = linkedlist.AddFirst(_random.Next());

                for (int i = 0; i < count; i++)
                {
                    last = ((i & 1) == 1
                        ? linkedlist.AddAfter(last, _random.Next())
                        : linkedlist.AddBefore(last, _random.Next()));
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"Linked-List - Add middle = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

            stopwatch.Reset();
            stopwatch.Start();
            {
                var list = new LinkedList<int>();

                for (int i = 0; i < count; i++)
                {
                    list.AddLast(_random.Next());
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"Linked-List - Add First = {stopwatch.Elapsed.TotalMilliseconds:0.0}ms");

        }
示例#25
0
        public void given_empty_blist_when_elements_are_added_individually_then_blist_indexer_should_return_elements()
        {
            var count = 1024;
            var expected = new int[count].Select(_ => _random.Next()).ToArray();

            var blist = new BList<int>();

            foreach (var item in expected)
                blist.Add(item);

            for (int i = 0; i < count; i++)
            {
                Assert.That(expected[i], Is.EqualTo(blist[i]));
            }
        }
示例#26
0
            given_existing_blist_when_elements_are_replaced_in_middle_then_blist_iterator_should_return_correct_latest_elements
            ()
        {

            var initial = new int[1024].Select(_ => _random.Next()).ToArray();
            var replacement = new int[256].Select(_ => _random.Next()).ToArray();
            var expected = initial.Take(256).Concat(replacement).Concat(initial.Skip(512)).ToArray();

            var blist = new BList<int>();

            foreach (var item in initial)
                blist.Add(item);

            CollectionAssert.AreEqual(initial, blist);

            for (int i = 0; i < 256; i++)
                blist[256 + i] = replacement[i];

            CollectionAssert.AreEqual(expected, blist);
        }
示例#27
0
        public void given_blist_with_one_element_when_two_inserted_at_index_zero_then_3rd_element_should_not_be_null()
        {
            var blist = new BList<string>();

            blist.Add("Foo");
            blist.InsertRange(new string[] {"Hello", "World"}, 0);

            Assert.That(blist.Count, Is.EqualTo(3));

            Assert.That(blist[0], Is.EqualTo("Hello"));
            Assert.That(blist[1], Is.EqualTo("World"));
            Assert.That(blist[2], Is.EqualTo("Foo"));
        }
示例#28
0
            given_existing_blist_when_elements_are_inserted_in_middle_then_blist_iterator_should_return_correct_latest_elements
            ()
        {
            var initial = new int[768].Select(_ => _random.Next()).ToArray();
            var inserts = new int[256].Select(_ => _random.Next()).ToArray();
            var expected = initial.Take(256).Concat(inserts).Concat(initial.Skip(256)).ToArray();

            var blist = new BList<int>();

            foreach (var item in initial)
                blist.Add(item);

            for (int i = 0; i < 256; i++)
                blist.Insert(256 + i, inserts[i]);

            Assert.That(blist.Count, Is.EqualTo(1024));

            CollectionAssert.AreEqual(expected, blist);
        }
示例#29
0
            given_existing_blist_when_elements_are_removed_by_element_then_blist_iterator_should_return_correct_elements
            ()
        {
            var initial = new int[512].Select(_ => _random.Next()).ToArray();
            var expected = initial.Skip(32).ToArray();

            var blist = new BList<int>();

            foreach (var item in initial)
                blist.Add(item);

            for (int i = 0; i < 32; i++)
            {
                blist.Remove(initial[i]);
            }

            Assert.That(blist.Count, Is.EqualTo(480));

            CollectionAssert.AreEqual(expected, blist);
        }
示例#30
0
        public static BList DecodeList(BencodeStream stream, Encoding encoding)
        {
            if (stream == null) throw new ArgumentNullException("stream");
            if (encoding == null) throw new ArgumentNullException("encoding");

            if (stream.Length < 2)
                throw new BencodeDecodingException<BList>("Minimum valid length is 2 (an empty list: 'le')", stream.Position);

            // Lists must start with 'l'
            if (stream.ReadChar() != 'l')
                throw new BencodeDecodingException<BList>(string.Format("Must begin with 'l' but began with '{0}'.", stream.ReadPreviousChar()), stream.Position);

            var list = new BList();
            // Loop until next character is the end character 'e' or end of stream
            while (stream.Peek() != 'e' && stream.Peek() != -1)
            {
                // Decode next object in stream
                var bObject = Decode(stream, encoding);
                if (bObject == null)
                    throw new BencodeDecodingException<BList>(string.Format("Invalid object beginning with '{0}'", stream.PeekChar()), stream.Position);

                list.Add(bObject);
            }

            if (stream.ReadChar() != 'e')
                throw new BencodeDecodingException<BList>("Missing end character 'e'.", stream.Position);

            return list;
        }