public override int Add(BList <int> blist, int item, int preferredIndex) { int i = blist.FindLowerBound(item); blist.Add(item); return(i); }
public static BDictionary CreateGetPeersResponse( BString transactionID, byte[] nid, byte[] infoHash, IList <IDHTPeer> peersList, IList <DHTNode> nodesList) { BList values = DHTHelper.CompactPeers(peersList); var nodes = new BString(DHTHelper.CompactNodes(nodesList)); BDictionary sendData = new BDictionary(); sendData.Add("t", transactionID); sendData.Add("y", "r"); var r = new BDictionary(); r.Add("id", new BString(nid)); r.Add("token", new BString(infoHash.Take(2))); if (values != null) { r.Add("values", values); } r.Add("nodes", nodes); sendData.Add("r", r); return(sendData); }
public void TestUpperAndLowerBound() { BList <int> blist = NewList(); blist.AddRange(new int[] { 0, 0, 10, 10, 20, 20, 25, 30, 30, 40, 40, 50, 50 }); int item = 25; Assert.AreEqual(blist.FindUpperBound(item), 1 + blist.FindLowerBound(item)); item = 10; Assert.That(blist.FindUpperBound(ref item) == 4 && item == 20); item = 0; Assert.That(blist.FindUpperBound(ref item) == 2 && item == 10); item = 999; Assert.That(blist.FindUpperBound(ref item) == blist.Count && item == 999); bool found; item = 5; Assert.That(blist.FindLowerBound(ref item, out found) == 2 && item == 10 && !found); item = 20; Assert.That(blist.FindLowerBound(ref item, out found) == 4 && item == 20 && found); item = 0; Assert.That(blist.FindLowerBound(ref item, out found) == 0 && item == 0 && found); item = 999; Assert.That(blist.FindLowerBound(ref item, out found) == blist.Count && item == 999 && !found); }
public override int AddToBoth(BList <int> blist, List <int> list, int item, int preferredIndex) { int i = Add(blist, item, preferredIndex); list.Insert(i, item); return(i); }
public void CanEncode_Complex() { var blist = new BList { "spam", 666, new BList { "foo", "bar", 123, new BDictionary { { "more spam", "more eggs" } } }, "foobar", new BDictionary { { "numbers", new BList { 1, 2, 3 } } } }; var bencode = blist.EncodeAsString(); bencode.Should().Be("l4:spami666el3:foo3:bari123ed9:more spam9:more eggsee6:foobard7:numbersli1ei2ei3eeee"); }
public void CanEncode_EmptyList() { var blist = new BList(); var bencode = blist.EncodeAsString(); bencode.Should().Be("le"); }
public void Add_Null_ThrowsArgumentNullException() { var blist = new BList(); Action action = () => blist.Add((IBObject)null); action.ShouldThrow <ArgumentNullException>(); }
private void UpdateTorrentPeerList(BList lIPPortString, BString transactionID) { byte[] ip = new byte[4]; byte[] port = new byte[2]; byte[] arr2 = BencodingUtils.ExtendedASCIIEncoding.GetBytes(transactionID.Value); for (int k = 0; k < lIPPortString.Count; k++) { byte[] transID = new byte[4] { 0, 0, 0, 0 }; Array.Copy(arr2, 0, transID, 2, 2); BString tempBS = (BString)lIPPortString[k]; byte[] arr = BencodingUtils.ExtendedASCIIEncoding.GetBytes(tempBS.Value); Array.Copy(arr, 0, ip, 0, 4); Array.Copy(arr, 4, port, 0, 2); Array.Copy(arr2, 0, transID, 2, 2); Array.Reverse(port); IPEndPoint ipEndP = new IPEndPoint((Int64)BitConverter.ToUInt32(ip, 0), (Int32)BitConverter.ToUInt16(port, 0)); lock (lockTorrentPeers) { if (!lTorrentPeers[BitConverter.ToInt32(transID, 0)].Contains(ipEndP)) { lTorrentPeers[BitConverter.ToInt32(transID, 0)].Add(ipEndP); } } } }
static void Main(string[] args) { string test = @"C:\Users\dotnet\Downloads\torr.torrent"; Console.WriteLine("Torrent file path:"); String torrentfile = test; TorrentFile torrent = Bencode.DecodeTorrentFile(torrentfile); Console.WriteLine("Info in torrentfile:"); Console.WriteLine(torrent.Announce); foreach (var St in torrent.AnnounceList) { Console.WriteLine(St.ToString()); } Console.WriteLine(torrent.Comment); Console.WriteLine(torrent.CreatedBy); Console.WriteLine(torrent.CreationDate); Console.WriteLine(torrent.Encoding); BDictionary info = (BDictionary)torrent["info"]; BList files = (BList)info["files"]; foreach (BDictionary v in files) { BList path = (BList)v["path"]; Console.WriteLine("Path: {0}, length: {1}", path[0], v["length"]); } Console.ReadLine(); }
/// <summary> /// 将 Peer 集合的数据转换为 BT 协议规定的格式 /// </summary> private void HandlePeersData(BDictionary resultDict, IReadOnlyList <Peer> peers, AnnounceInputParameters inputParameters) { var total = Math.Min(peers.Count, inputParameters.PeerWantCount); //var startIndex = new Random().Next(total); // 判断当前 BT 客户端是否需要紧凑模式的数据。 if (inputParameters.IsEnableCompact) { var compactResponse = new byte[total * 6]; for (int index = 0; index < total; index++) { var peer = peers[index]; Buffer.BlockCopy(peer.ToBytes(), 0, compactResponse, (total - 1) * 6, 6); } resultDict.Add(TrackerServerConsts.PeersKey, new BString(compactResponse)); } else { var nonCompactResponse = new BList(); for (int index = 0; index < total; index++) { var peer = peers[index]; nonCompactResponse.Add(peer.ToEncodedDictionary()); } resultDict.Add(TrackerServerConsts.PeersKey, nonCompactResponse); } }
public override void ParseUpvalues(BinaryReaderEx reader, BHeader header, LFunctionParseState s) { BList <LUpvalue> upvalues = header.Upvalue.ParseList(reader, header); s.LenUpvalues = upvalues.Length.AsInt(); s.Upvalues = upvalues.AsArray(new LUpvalue[s.LenUpvalues]); }
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)); }
public void BListSetNullValue() { BList list = new BList(); list.Add(new BInt(0)); list[0] = null; }
public void FillTrackersFromInfo(BDictionary torrent) { string tracker = null; BList trackersBList = null; if (torrent["announce"] != null) { tracker = ((BString)torrent["announce"]).ToString(); } if (torrent["announce-list"] != null) { trackersBList = (BList)torrent["announce-list"]; } if (trackersBList != null) { for (int i = 0; i < trackersBList.Count; i++) { file.trackers.Add(new Uri(((BString)((BList)trackersBList[i])[0]).ToString())); } } if (tracker != null) { file.trackers.Add(new Uri(tracker)); } }
public void getTasks() { //loading xml file XmlDocument doc = new XmlDocument(); doc.Load(taskPath); XmlNodeList bNodeList = doc.GetElementsByTagName("BackupAndUploadTask"); XmlNodeList fNodeList = doc.GetElementsByTagName("UploadFolderTask"); foreach (XmlNode backup in bNodeList) { BList.Add(new BackupTask() { DBFName = backup.SelectSingleNode("DropBoxFolderName").Attributes["Value"].Value, DBClear = Int32.Parse(backup.SelectSingleNode("DropboxClear").Attributes["Value"].Value), DType = backup.SelectSingleNode("DatabaseType").Attributes["Value"].Value, SQLCString = backup.SelectSingleNode("SqlConnectionString").Attributes["Value"].Value, SQLDName = backup.SelectSingleNode("SqlDatabaseName").Attributes["Value"].Value, BFolder = backup.SelectSingleNode("BackupsFolder").Attributes["Value"].Value, RFolder = backup.SelectSingleNode("RemoteFolder").Attributes["Value"].Value, LFolder = backup.SelectSingleNode("LocalFolder").Attributes["Value"].Value, BF1 = backup.SelectSingleNode("BackupFolder1").Attributes["Value"].Value, BF2 = backup.SelectSingleNode("BackupFolder2").Attributes["Value"].Value, CBFolder = Int32.Parse(backup.SelectSingleNode("ClearBackupsFolder").Attributes["Value"].Value), CRFolder = Int32.Parse(backup.SelectSingleNode("ClearRemoteFolder").Attributes["Value"].Value), CLFolder = Int32.Parse(backup.SelectSingleNode("ClearLocalFolder").Attributes["Value"].Value), CBF1 = Int32.Parse(backup.SelectSingleNode("ClearBackupFolder1").Attributes["Value"].Value), CBF2 = Int32.Parse(backup.SelectSingleNode("ClearBackupFolder2").Attributes["Value"].Value), Name = backup.SelectSingleNode("Name").Attributes["Value"].Value, TaskActive = Convert.ToBoolean(backup.SelectSingleNode("TaskActive").Attributes["Value"].Value), TaskStart = backup.SelectSingleNode("TaskStart").Attributes["Value"].Value, TaskEnd = backup.SelectSingleNode("TaskEnd").Attributes["Value"].Value, TaskRepeat = Int32.Parse(backup.SelectSingleNode("TaskRepeat").Attributes["Value"].Value), TaskLast = backup.SelectSingleNode("TaskLast").Attributes["Value"].Value }); //textBox.Text = backup.SelectSingleNode("Name").Attributes["Value"].Value; // SelectionChanged = "backupListBox_SelectionChanged" } backupListBox.ItemsSource = BList; foreach (XmlNode folder in fNodeList) { FList.Add(new FolderTask() { DBFName = folder.SelectSingleNode("DropBoxFolderName").Attributes["Value"].Value, DBClear = Int32.Parse(folder.SelectSingleNode("DropboxClear").Attributes["Value"].Value), FPath = folder.SelectSingleNode("FolderPath").Attributes["Value"].Value, Name = folder.SelectSingleNode("Name").Attributes["Value"].Value, TaskActive = Convert.ToBoolean(folder.SelectSingleNode("TaskActive").Attributes["Value"].Value), TaskStart = folder.SelectSingleNode("TaskStart").Attributes["Value"].Value, TaskEnd = folder.SelectSingleNode("TaskEnd").Attributes["Value"].Value, TaskRepeat = Int32.Parse(folder.SelectSingleNode("TaskRepeat").Attributes["Value"].Value), TaskLast = folder.SelectSingleNode("TaskLast").Attributes["Value"].Value }); //textBox.Text = folder.SelectSingleNode("Name").Attributes["Value"].Value; } folderListBox.ItemsSource = FList; }
public static List <IPEndPoint> ParseValuesList(BList data) { var result = new List <IPEndPoint>(); foreach (var item in data) { var str = item as BString; var itemBytes = str.Value; if (itemBytes.Length == 6) { var ip = new IPAddress(itemBytes.Take(4).ToArray()); var port = BitConverter.ToUInt16(itemBytes, 4); var xnode = new IPEndPoint(PrepareAddress(ip), port); result.Add(xnode); } else if (itemBytes.Length == 18) { var ip = new IPAddress(itemBytes.Take(16).ToArray()); var port = BitConverter.ToUInt16(itemBytes, 16); var xnode = new IPEndPoint(PrepareAddress(ip), port); result.Add(xnode); } else { } } return(result); }
/// <summary> /// Creates a bencoded string of metadata representing the .torrent file. /// </summary> /// <param name="name">The name of the torrent.</param> /// <param name="files">A list of FileData objects representing the files to be tracked.</param> /// <param name="directory">The parent directory of the torrent.</param> /// <param name="tracker">Tracker announce url to use.</param> /// <param name="trackers">A list of announce urls</param> /// <param name="pieceLength">the size of individual pieces to be used.</param> /// <param name="pieces">A list of sha1 hashes representing the files to be delivered.</param> /// <returns></returns> public static string MakeTorrent(string name, List <FileData> files, string directory, string tracker, List <string> trackers, int pieceLength, List <byte[]> pieces) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (files == null) { throw new ArgumentNullException(nameof(files)); } if (files.Count < 1) { throw new ArgumentOutOfRangeException(); } if (tracker == null) { throw new ArgumentNullException(nameof(tracker)); } if (pieces == null) { throw new ArgumentNullException(nameof(pieces)); } var fileData = new BDictionary(); var info = new BDictionary(); var aList = new BList(trackers); AddInfo(name, directory, info, pieceLength, files, pieces); AddDictFields(fileData, aList, info, tracker); return(fileData.BencodedString); }
private bool ProcessValuesStr(DHTNode remoteNode, BList valuesList, BString token) { bool result = false; if (valuesList != null && valuesList.Count != 0) { var values = DHTNode.ParseValuesList(valuesList); if (values.Count > 0) { #if DEBUG_DHT_INTERNALS fLogger.WriteDebug("Receive {0} values (peers) from {1}", values.Count, remoteNode.EndPoint); #endif foreach (var peer in values) { fLogger.WriteDebug("Receive peer {0} from {1}", peer, remoteNode.EndPoint); if (peer.Address.Equals(PublicEndPoint.Address)) { result = true; } } if (PeersFound != null) { PeersFound(this, new PeersFoundEventArgs(values)); } } } return(result); }
public void Encode_UTF8() { var blist = new BList { "æøå äö èéê ñ" }; Assert.AreEqual("l21:æøå äö èéê ñe", blist.Encode()); Assert.AreEqual("l21:æøå äö èéê ñe", blist.Encode(Encoding.UTF8)); Assert.AreEqual(blist.Encode(), blist.Encode(Encoding.UTF8)); }
public static bool MoveBalls(BList balls, float safeDistance) { changeSpecialMoveToFalse = specialMove; playing = true; BListObject actualBall = balls.InitEnumerationFromLeftBListObject(); if (actualBall != null) { do { if (!specialMove || actualBall.value.GetComponent <BallScript>().ballObj.specialMove) { MoveBall(actualBall); } } while ((actualBall = balls.NextBListObject()) != null); } if (changeSpecialMoveToFalse) { changeSpecialMoveToFalse = false; specialMove = false; CheckBallsCorrectDestinations(balls); CheckBallsCorrectDistances(balls, GameManagerScript.spawningSafeDistance); } //CheckBallsCorrectDistances(balls, GameManagerScript.spawningSafeDistance); return(playing); }
public static List <string> GetPathsFromInfo(BDictionary info) { BList files = (BList)info["files"]; if (files == null) { return(null); } List <string> fileNames = new List <string>(); for (int i = 0; i < files.Count; i++) { BDictionary bdic = (BDictionary)files[i]; BList path = (BList)bdic["path"]; string fileName = ""; for (int l = 0; l < path.Count; l++) { fileName += path[l] + "\\"; } fileNames.Add(fileName.Substring(0, fileName.Length - 1)); } return(fileNames); }
public void Encode_Complex() { var blist = new BList { "spam", 666, new BList { "foo", "bar", 123, new BDictionary { {"more spam", "more eggs"} } }, "foobar", new BDictionary { {"numbers", new BList {1, 2, 3}} } }; var expected = "l4:spami666el3:foo3:bari123ed9:more spam9:more eggsee6:foobard7:numbersli1ei2ei3eeee"; var actual = blist.Encode(); Assert.AreEqual(expected, actual); }
public void GetSizeInBytes() { var blist = new BList { 1, 2, "abc" }; blist.GetSizeInBytes().Should().Be(13); }
// Adds metadata about the client, torrent creator and announce urls. private static void AddDictFields(BDictionary fileData, BList alist, BDictionary info, string announceUrl) { fileData.Add(TorrentKeys.Announce, new BString(announceUrl)); fileData.Add(TorrentKeys.AnnounceList, alist); fileData.Add(TorrentKeys.Creator, new BString($"RowTorrent/{GlobalData.APIVersion}")); fileData.Add(TorrentKeys.CreationDate, new BInteger(Util.Time.GetUnixTime())); fileData.Add(TorrentKeys.Encoding, new BString("UTF-8")); fileData.Add(TorrentKeys.Info, info); }
private void bDeleteButton_Click(object sender, RoutedEventArgs e) { BList.Remove((BackupTask)backupListBox.SelectedItem); backupListBox.ItemsSource = null; backupListBox.ItemsSource = BList; saveButton.Background = Brushes.Blue; backupItemListView.ItemsSource = null; }
public void Encode_Simple() { var blist = new BList {"hello world", 987, "foobar"}; var expected = "l11:hello worldi987e6:foobare"; var actual = blist.Encode(); Assert.AreEqual(expected, actual); }
public void AsType_ContainingWrongType_ThrowsInvalidCastException() { var blist = new BList { 1, "2", 3 }; Action action = () => blist.AsType <BNumber>(); action.ShouldThrow <InvalidCastException>(); }
public void CanEncode_UTF8() { var blist = new BList { "æøå äö èéê ñ" }; var bencode = blist.EncodeAsString(); bencode.Should().Be("l21:æøå äö èéê ñe"); }
public void AsStrings_ContainingNonBStringType_ThrowsInvalidCastException() { var blist = new BList { "a", "b", 3 }; Action action = () => blist.AsStrings(); action.ShouldThrow <InvalidCastException>(); }
public void Indexer_Set_Null_ThrowsArgumentNullException() { var blist = new BList { 0 }; Action action = () => blist[0] = null; action.ShouldThrow <ArgumentNullException>(); }
public void AsNumbers_ContainingNonBNumberType_ThrowsInvalidCastException() { var blist = new BList { 1, 2, "3" }; Action action = () => blist.AsNumbers(); action.ShouldThrow <InvalidCastException>(); }
public void CanEncode_Simple() { var blist = new BList { "hello world", 987, "foobar" }; var bencode = blist.EncodeAsString(); bencode.Should().Be("l11:hello worldi987e6:foobare"); }
public void DecodeList_Empty() { const string testString = "le"; BList testExpected = new BList(); IBencodingType testResult = BencodingUtils.Decode(testString); Assert.AreEqual(testExpected, testResult); }
public void Encode_ISO88591() { var encoding = Encoding.GetEncoding("ISO-8859-1"); var blist = new BList { new BString("æøå äö èéê ñ", encoding) }; Assert.AreNotEqual("l12:æøå äö èéê ñe", blist.Encode()); Assert.AreEqual("l12:æøå äö èéê ñe", blist.Encode(encoding)); Assert.AreNotEqual(blist.Encode(), blist.Encode(encoding)); }
public void AsStrings_ConvertsToListOfStrings() { var blist = new BList { "a", "b", "c" }; var strings = blist.AsStrings(); strings.Should().HaveCount(3); strings.Should().ContainInOrder("a", "b", "c"); }
public void AsNumbers_ConvertsToListOfLongs() { var blist = new BList { 1, 2, 3 }; var numbers = blist.AsNumbers(); numbers.Should().HaveCount(3); numbers.Should().ContainInOrder(1L, 2L, 3L); }
private void OnRecvGetPeersResponse(DHTNode remoteNode, BString nodesStr, BList valuesList, BString token) { // according to bep_0005, get_peers response can contain a list of nodes ProcessNodesStr(remoteNode, nodesStr); if (!ProcessValuesStr(remoteNode, valuesList, token)) { SendAnnouncePeerQuery(remoteNode, fSearchInfoHash, 0, PublicEndPoint.Port, token); } }
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]); }
given_empty_blist_when_one_element_is_inserted_at_zero_index_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.Insert(0, item); CollectionAssert.AreEqual(expected, blist); }
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])); }
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)); }
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); }
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); }
public void ListDecode_EmptyList_Positive() { BList expectedList = new BList() { Value = new IBObject[] { } }; var inputBytes = "le".GetASCIIBytes(); var inputStream = new MemoryStream(inputBytes); var transform = new ListTransform(new BObjectTransform()); BList actualList = transform.Decode(inputStream); Assert.AreEqual<BObjectType>(expectedList.BType, actualList.BType); Assert.AreEqual<int>(actualList.Value.Length, expectedList.Value.Length); }
public void ListDecode_NestedList_Positive() { BList expectedList = new BList() { Value = new IBObject[] { new BList() { Value = new IBObject[] { } } } }; var inputBytes = "llee".GetASCIIBytes(); var inputStream = new MemoryStream(inputBytes); var transform = new ListTransform(new BObjectTransform()); BList actualList = transform.Decode(inputStream); // Validate outer list: Assert.AreEqual<BObjectType>(expectedList.BType, actualList.BType); Assert.AreEqual<int>(1, actualList.Value.Length); // Validate nested list: Assert.AreEqual<BObjectType>(BObjectType.List, actualList.Value[0].BType); Assert.AreEqual<int>(0, ((BList)actualList.Value[0]).Value.Length); }
public void AddNullValue() { var blist = new BList(); blist.Add((IBObject)null); }
/// <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; }
public void given_empty_blist_when_multiple_elements_added_then_blist_iteractor_should_return_elements() { var expected = new int[512].Select(_ => _random.Next()).ToArray(); var blist = new BList<int>(); blist.AddRange(expected); CollectionAssert.AreEqual(expected, blist); }
given_existing_blist_when_multiple_elements_inserted_at_zero_then_blist_iteractor_should_return_elements() { var initial = new int[256].Select(_ => _random.Next()).ToArray(); var expected = initial.Concat(initial).ToArray(); var blist = new BList<int>(); blist.AddRange(initial); blist.InsertRange(initial, 0); CollectionAssert.AreEqual(expected, blist); }
given_existing_blist_when_multiple_elements_replaced_at_index_zero_then_blist_iteractor_should_return_elements () { var initial = new int[256].Select(_ => _random.Next()).ToArray(); var replace = new int[32].Select(_ => _random.Next()).ToArray(); var expected = replace.Concat(initial.Skip(32)).ToArray(); var blist = new BList<int>(); blist.AddRange(initial); blist.ReplaceRange(replace, 0); CollectionAssert.AreEqual(expected, blist); }
public void given_blist_when_clear_is_called_then_collectionchanged_raised() { var blist = new BList<int>(); blist.AddRange(new int[32].Select(_ => _random.Next()).ToArray()); NotifyCollectionChangedEventArgs args = null; blist.CollectionChanged += (_, a) => args = a; blist.Clear(); Assert.That(args, Is.Not.Null); Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Reset)); }
public void given_blist_when_item_added_then_collectionchanged_raised() { var blist = new BList<int>(); var initial = new int[32].Select(_ => _random.Next()).ToArray(); var expected = _random.Next(); blist.AddRange(initial); NotifyCollectionChangedEventArgs args = null; blist.CollectionChanged += (_, a) => args = a; blist.Insert(16, expected); Assert.That(args, Is.Not.Null); Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Add)); Assert.That(args.NewStartingIndex, Is.EqualTo(16)); Assert.That(args.NewItems[0], Is.EqualTo(expected)); }
public void given_blist_when_item_replaced_then_collectionchanged_raised() { var blist = new BList<int>(); var index = 10; var initial = new int[32].Select(_ => _random.Next()).ToArray(); var expectedNew = _random.Next(); var expectedOld = initial[index]; blist.AddRange(initial); NotifyCollectionChangedEventArgs args = null; blist.CollectionChanged += (_, a) => args = a; blist[index] = expectedNew; Assert.That(args, Is.Not.Null); Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Replace)); Assert.That(args.NewStartingIndex, Is.EqualTo(10)); Assert.That(args.OldStartingIndex, Is.EqualTo(10)); Assert.That(args.NewItems[0], Is.EqualTo(expectedNew)); Assert.That(args.OldItems[0], Is.EqualTo(expectedOld)); }
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")); }
public void Encode_EmptyList() { var blist = new BList(); Assert.AreEqual("le", blist.Encode()); }
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])); } }
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); }
public void Encode(BList input, Stream outputStream) { if (input == null) throw new ArgumentNullException("input"); if (outputStream == null) throw new ArgumentNullException("outputStream"); outputStream.WriteByte(Definitions.ASCII_l); foreach (IBObject item in input.Value) { objectTransform.EncodeObject(item, outputStream); } outputStream.WriteByte(Definitions.ASCII_e); }
public void SetNullValue() { var blist = new BList(); blist.Add(0); blist[0] = null; }
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); }