public NvMemoryAllocator() { _tree.Add(PageSize, AddressSpaceSize); LinkedListNode <ulong> node = _list.AddFirst(PageSize); _dictionary[PageSize] = node; }
public static TreeDictionary <int, int> ProcessRanges(IEnumerable <Tuple <int, int> > ranges) { var summedRangeEdges = new TreeDictionary <int, int>(); foreach (var currentRange in ranges) { var currentRangeLeft = currentRange.Item1; var currentRangeRight = currentRange.Item2; // Add left boundary if it isn't already there, with its value set as the value of the summed range it is included in, otherwise zero // E.g.: 1 to 10 with value 1 becomes 1 to 5 with value 1, 5 to 10 with value 1 // Check if the node exists in the Tree if (!summedRangeEdges.Exists(x => x.Key == currentRangeLeft)) { summedRangeEdges.Add(currentRangeLeft, summedRangeEdges.TryPredecessor(currentRangeLeft, out var predecessor) ? predecessor.Value : 0); } // Increment the value of all summed range edges between the left boundary (inclusive) and the right boundary (exclusive) var summedRangesSubMap = summedRangeEdges.RangeFromTo(currentRangeLeft, currentRangeRight); var keys = new SortedArray <int>(); foreach (var key in summedRangesSubMap) { keys.Add(key.Key); } foreach (var key in keys) { summedRangeEdges[key]++; } // Add the right boundary // If there isn't a summed range edge to its left, use 0 for the value (should never happen as per the "put" above) // If the right boundary was already in the map, leave it as is // If the right boundary wasn't in the map, use the value to its left minus 1 (since this is a right boundary, which means a range was closed) if (summedRangeEdges.Exists(x => x.Key == currentRangeRight)) { continue; } { if (summedRangeEdges.TryPredecessor(currentRangeRight, out var predecessor)) { summedRangeEdges.Add(currentRangeRight, predecessor.Value - 1); } else { summedRangeEdges.Add(currentRangeRight, 0); } } } return(summedRangeEdges); }
public void Init() { ISortedDictionary <string, string> dict = new TreeDictionary <string, string>(new SC()); dict.Add("A", "1"); dict.Add("C", "2"); dict.Add("E", "3"); this.dict = new GuardedSortedDictionary <string, string>(dict); }
public void ItemRemove_Test() { treeDict = new TreeDictionary <int, int>(true); treeDict.Add(0, 44); treeDict.Add(1, 55); treeDict.Add(2, 66); treeDict.Add(3, 99); treeDict.Add(3, 101); treeDict.Add(4, 88); treeDict.Add(5, 77); treeDict.Add(8, 45); treeDict.Add(9, 34); treeDict.Remove(new KeyValuePair <int, int>(8, 45)); treeDict.Remove(new KeyValuePair <int, int>(3, 99)); treeDict.Remove(new KeyValuePair <int, int>(9, 34)); Assert.AreEqual(6, treeDict.Count); Assert.AreEqual(false, treeDict.ContainsKey(6), "Contains"); Assert.AreEqual(true, treeDict.Contains(new KeyValuePair <int, int>(0, 44))); Assert.AreEqual(true, treeDict.Contains(new KeyValuePair <int, int>(1, 55))); Assert.AreEqual(false, treeDict.Contains(new KeyValuePair <int, int>(8, 45)), "8, 45"); Assert.AreEqual(false, treeDict.Contains(new KeyValuePair <int, int>(3, 99)), "3, 99"); Assert.AreEqual(false, treeDict.Contains(new KeyValuePair <int, int>(9, 34)), "9, 34"); }
public static TreeDictionary <int, Page> DeepCopy(this TreeDictionary <int, Page> item) { var result = new TreeDictionary <int, Page>(); item.ForEach(i => result.Add(i.Key, i.Value)); return(result); }
public void Add(byte[] sortKey, T item) { object oldVal; if (m_index.TryGetValue(sortKey, out oldVal)) { // Seen this item before. Have we already changed to storing a set? var items = oldVal as HashSet <T>; if (items != null) { items.Add(item); // already called twice or more with this key; just add to set. } else { // second call with this key: make a set and store in the dictionary. items = new HashSet <T>(); m_index[sortKey] = items; items.Add((T)oldVal); items.Add(item); } } else // first item for this key, store the item itself as a singleton. { m_index.Add(sortKey, item); } }
public static void AddParts(string key, IPlace place) { key = key.ToLower(); autoCompleteList.Add(key, place); string[] parts = key.Split(new char[] { ' ' }); if (parts.Length > 1) { foreach (string part in parts) { if (!string.IsNullOrEmpty(part)) { autoCompleteList.Add(part, place); } } } }
public void KeyRemove_Test() { treeDict = new TreeDictionary <int, int>(true); treeDict.Add(0, 44); treeDict.Add(1, 55); treeDict.Add(1, 56); treeDict.Add(2, 66); treeDict.Add(3, 99); treeDict.Remove(1); Assert.AreEqual(3, treeDict.Count); Assert.AreEqual(true, treeDict.ContainsKey(2)); Assert.AreEqual(false, treeDict.Contains(new KeyValuePair <int, int>(3, 98))); Assert.AreEqual(true, treeDict.Contains(new KeyValuePair <int, int>(3, 99))); Assert.AreEqual(66, treeDict[2]); }
public void Add(T item) { Q key = toKey(item); if (!dict.Contains(key)) { dict.Add(key, new HashSet <T>(ReferenceEqualityComparer <T> .Default)); } dict[key].Add(item); }
public void TestIDictionary() { IDictionary dictionary = new TreeDictionary <int, int>(branchingFactor: 4); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); Assert.False(dictionary.IsSynchronized); Assert.Throws <ArgumentNullException>("key", () => dictionary.Add(key: null !, value: 1)); Assert.Throws <ArgumentException>("value", () => dictionary.Add(key: 1, value: null)); Assert.Throws <ArgumentException>("key", () => dictionary.Add(key: "string value", value: 0)); Assert.Throws <ArgumentException>("value", () => dictionary.Add(key: 0, value: "string value")); for (int i = 0; i < 11; i++) { dictionary.Add(i, i + 1); } Assert.Throws <ArgumentNullException>("key", () => dictionary[key: null !]);
public void Add(T item) { var key = _toKey(item); if (!_dictionary.Contains(key)) { _dictionary.Add(key, new HashSet <T>(EqualityComparer <T> .Default)); } _dictionary[key].Add(item); }
public void Add_Added() { //Arrange var d = new TreeDictionary <int, int>(new BinaryTree <int, int>()); //Act d.Add(100, 1500); //Assert Assert.Single(d); Assert.Equal(1500, d[100]); // ReSharper disable once xUnit2013 Assert.Single(d); }
public void TreeDictionary_Test() { var Dictionary = new TreeDictionary <int, int>(); int nodeCount = 1000; //insert test for (int i = 0; i <= nodeCount; i++) { Dictionary.Add(i, i); Assert.AreEqual(true, Dictionary.ContainsKey(i)); } for (int i = 0; i <= nodeCount; i++) { Dictionary.Remove(i); Assert.AreEqual(false, Dictionary.ContainsKey(i)); } var rnd = new Random(); var testSeries = Enumerable.Range(1, nodeCount).OrderBy(x => rnd.Next()).ToList(); foreach (var item in testSeries) { Dictionary.Add(item, item); Assert.AreEqual(true, Dictionary.ContainsKey(item)); } for (int i = 1; i <= nodeCount; i++) { Dictionary.Remove(i); Assert.AreEqual(false, Dictionary.ContainsKey(i)); } }
public void ContainsKey_InsertNull_ReturnsTrue() { //Arrange var dictionary = new TreeDictionary <string, string>(new BinaryTree <string, string>()); const string key = "testKey"; dictionary.Add(key, null); //Act var result = dictionary.ContainsKey(key); //Assert Assert.True(result); Assert.Single(dictionary); }
private OrderBook GetOrderBook(Message message) { var symbol = message.Symbol; if (_orderBooks.Find(ref symbol, out var orderBook)) { return(orderBook); } orderBook = new OrderBook(message.Symbol, _logger); _orderBooks.Add(symbol, orderBook); return(_orderBooks[symbol]); }
public void Add(TChild item) { var propValue = (TProperty)_propertyReader.ReadValue(item); if (_index.Contains(propValue)) { _index[propValue].Add(item); } else { _index.Add(propValue, new List <TChild> { item }); } }
void startJob(NifLoadJob job, TreeDictionary <long, NifLoadJob> runningList, KdTreeNode <float, SCG.List <NifLoadJob> >[] candidates) { lock (loadingCapsuleQueue) { loadingCapsuleQueue.Enqueue(job); }; lock (runningList) { runningList.Add(job.uid, job); } foreach (KdTreeNode <float, SCG.List <NifLoadJob> > n in candidates) { n.Value.Remove(job); } //Debug.Log("Start job:" + job.filename); job.Start((System.Threading.ThreadPriority)ProgramSettings.get("OBJECT_LOAD_THREAD_PRIORITY", (int)System.Threading.ThreadPriority.Normal)); }
public TPIHashReader(IServiceContainer ctx, byte[] hashData) : base(hashData) { TPIReader tpi = ctx.GetService <TPIReader>(); TPIHash hash = tpi.Header.Hash; switch (hash.HashKeySize) { case sizeof(UInt16): case sizeof(UInt32): break; default: throw new InvalidDataException(); } if (hash.TypeOffsets.Size > 0) { Position = hash.TypeOffsets.Offset; uint NumTiPairs = (uint)(hash.TypeOffsets.Size / Marshal.SizeOf <TIOffset>()); for (int i = 1; i < NumTiPairs; i++) { TIOffset tiOff = Read <TIOffset>(); TypeIndexToOffset.Add(tiOff.TypeIndex, tiOff.Offset); } } if (hash.HashValues.Size > 0) { Position = hash.HashValues.Offset; uint NumHashValues = hash.HashValues.Size / sizeof(UInt32); RecordHashValues = PerformAt(hash.HashValues.Offset, () => { return(Enumerable.Range(1, (int)NumHashValues) .Select(_ => ReadUInt32()) .ToArray()); }); } if (hash.HashHeadList.Size > 0) { Position = hash.HashHeadList.Offset; NameIndexToTypeIndex = Deserializers.ReadMap <UInt32, UInt32>(this); } }
public void Pred2() { dict.Add("A", "1"); dict.Add("C", "2"); dict.Add("E", "3"); KeyValuePair <String, String> res; Assert.IsTrue(dict.TryPredecessor("B", out res)); Assert.AreEqual("1", res.Value); Assert.IsTrue(dict.TryPredecessor("C", out res)); Assert.AreEqual("1", res.Value); //Assert.IsTrue(dict.TryWeakPredecessor("B", out res)); //Assert.AreEqual("1", res.Value); //Assert.IsTrue(dict.TryWeakPredecessor("C", out res)); //Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TrySuccessor("B", out res)); Assert.AreEqual("2", res.Value); Assert.IsTrue(dict.TrySuccessor("C", out res)); Assert.AreEqual("3", res.Value); //Assert.IsTrue(dict.TryWeakSuccessor("B", out res)); //Assert.AreEqual("2", res.Value); //Assert.IsTrue(dict.TryWeakSuccessor("C", out res)); //Assert.AreEqual("2", res.Value); Assert.IsFalse(dict.TryPredecessor("A", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); //Assert.IsFalse(dict.TryWeakPredecessor("@", out res)); //Assert.AreEqual(null, res.Key); //Assert.AreEqual(null, res.Value); Assert.IsFalse(dict.TrySuccessor("E", out res)); Assert.AreEqual(null, res.Key); Assert.AreEqual(null, res.Value); //Assert.IsFalse(dict.TryWeakSuccessor("F", out res)); //Assert.AreEqual(null, res.Key); //Assert.AreEqual(null, res.Value); }
public void Iteration_IteratesThroughCollection() { //Arrange var dictionary = new TreeDictionary <int, string>(new BinaryTree <int, string>()); var arr = new List <int> { 1, 2, 3, 4, 5, 6, 7 }; foreach (var i in arr) { dictionary.Add(i, i.ToString()); } //Act & Assert foreach (var p in dictionary) { Assert.Equal(p.Key, int.Parse(p.Value)); arr.Remove(p.Key); } Assert.Empty(arr); }
/// <summary> /// Tries to load a container from disk file. If this is a fresh database, will return a new container. /// </summary> /// <param name="address">The address of the container to get</param> /// <returns>A container from disk</returns> private BTreeContainer GetContainerFromDisk(BTreeAddress address) { Database2 db = _process.GetDatabase2(address.DatabaseId); DbStorage storage = db.Storage; var tree = new TreeDictionary <int, Page>(); TableSchema2 schema = db.GetTable(address.TableId).Schema; // get the first page Page page = storage.GetPage(1, address); // if this is a brand new table if (page == null) { page = new Page(1, address.TableId, address.DatabaseId, schema, _process); } tree.Add(page.Id, page); return(new BTreeContainer(address, tree, storage, schema, _process)); }
public void Insert(PointFr p, EventPoint ep) // Wstawia zdarzenie ep w punkcie p do bieżącej kolejki zdarzeń zdarzenia Right są dodawane na początku, pozostałe na końcu { var existing = new C5.LinkedList <EventPoint>(); if (_events.Exists(kvp => kvp.Key.Equals(p))) { existing = _events[p]; _events.Remove(p); } if (ep.Type == EventPointType.Right) // Zdarzenia 'Right' powinny byc na początku listy { existing.Insert(0, ep); } else { existing.Add(ep); } _events.Add(p, existing); }
public HashDataReader(TPIReader tpi, Stream stream) : base(stream) { TPIHash hash = tpi.Header.Hash; uint NumTiPairs = (uint)(hash.TypeOffsets.Size / Marshal.SizeOf <TPISlice>()); PerformAt(hash.TypeOffsets.Offset, () => { for (int i = 1; i < NumTiPairs; i++) { TIOffset tiOff = ReadStruct <TIOffset>(); TypeIndexToOffset.Add(tiOff.TypeIndex, tiOff.Offset); } }); uint NumHashValues = (uint)(hash.HashValues.Size / sizeof(UInt32)); RecordHashValues = PerformAt(hash.HashValues.Offset, () => { return(Enumerable.Range(1, (int)NumHashValues) .Select(_ => ReadUInt32()) .ToArray()); }); }
public void EnsureAddIntegrity() { TreeDictionary <int, int> dictionary = new TreeDictionary <int, int>(); Assert.AreEqual(dictionary.Count, 0); dictionary.Add(2, 7); dictionary.Add(1, 4); dictionary.Add(10, 2); dictionary.Add(4, 1); dictionary.Add(3, 2); dictionary.Add(11, 2); dictionary.Add(5, 2); Assert.AreEqual(dictionary.Count, 7); List <KeyValuePair <int, int> > list = dictionary.AsLevelOrderList(); /* * Tree Should Look as Follows After Rotations * * 2 * 1 4 * 3 10 * 5 11 * */ Assert.AreEqual(list.Count, dictionary.Count); Assert.AreEqual(list[0].Key, 2); Assert.AreEqual(list[1].Key, 1); Assert.AreEqual(list[2].Key, 4); Assert.AreEqual(list[3].Key, 3); Assert.AreEqual(list[4].Key, 10); Assert.AreEqual(list[5].Key, 5); Assert.AreEqual(list[6].Key, 11); }
public void Choose() { dict.Add("YES", "NO"); Assert.AreEqual(new System.Collections.Generic.KeyValuePair <string, string>("YES", "NO"), dict.Choose()); }
public void Choose() { dict.Add("YES", "NO"); Assert.AreEqual(new KeyValuePair <string, string>("YES", "NO"), dict.Choose()); }
void addChildrenToOpenSet(TreeDictionary<double, StateNode> dict, StateNode parent, GameState state, CombinedHeuristic heuristic) { var parentScore = stateNodeScorer (heuristic, parent); foreach (var input in Input.All.CartesianProduct(Input.All)) { var stateNode = new StateNode (parent, input, state); // var target1 = state.Goal; // var target2 = state.Goal; var targets = heuristic.cpas.NextPlatform (state.P1, state.P2, state.Goal, state.Goal); var target1 = targets.Item1; var target2 = targets.Item2; var score = parentScore + heuristic.EstimateScore (state, input.Item1, input.Item2, target1.Target, target2.Target); var noiseyScore = AStar.addNoise (score); dict.Add (noiseyScore, stateNode); } }
// public TreeDictionary<double, IEnumerable<B>> AStar<A, B>(Func<B, AStarNode<A, B>> nextState, A state) { // var openSet = new TreeDictionary<double, B>(); // Known, but unexplored // var closedSet = new TreeDictionary<double, B>(); // Fully explored // // AStarNode<A, B> parentStub = new AStarNode<A, B> (null, null, state); // addChildrenToOpenSet(openSet, parentStub, state, heuristic); // // int maxIters = 100; // int nRepetitions = 5; // // AStarNode<A, B> best; // // int i = 0; // do { // var bestKV = openSet.First (); // openSet.Remove(bestKV.Key); // // best = bestKV.Value; // // var bestNextMove = best.Input; // // // repeat the same input a few times // B resultState = best.Value; // for (int j = 0; j < nRepetitions; j++) { // resultState = nextState(new AStarNode<A, B>(best, bestNextMove, resultState)); // } // // addChildrenToOpenSet(openSet, best, resultState, heuristic); // // var stateNode = new AStarNode<A, B> (best, bestNextMove, resultState); // var score = AStar.addNoise(stateNodeScorer (heuristic, stateNode)); // // closedSet.Add(score, stateNode); // // } while(i++ < maxIters && closedSet.First().Key > 0 && openSet.Count > 0); // // return closedSet; // } // // public List<Tuple<Input, Input>> nextInputsList2(GameState state) { // // } public List<Tuple<Input, Input>> nextInputsList(GameState state) { var openSet = new TreeDictionary<double, StateNode>(); // Known, but unexplored var closedSet = new TreeDictionary<double, StateNode>(); // Fully explored StateNode parentStub = new StateNode (null, Tuple.Create(Input.Noop, Input.Noop), state); addChildrenToOpenSet(openSet, parentStub, state, heuristic); int maxIters = 100; int nRepetitions = 5; StateNode bestOpen; int i = 0; do { var bestOpenKV = openSet.First (); openSet.Remove(bestOpenKV.Key); bestOpen = bestOpenKV.Value; var bestNextMove = bestOpen.Input; // repeat the same input a few times GameState resultState = bestOpen.Value; for (int j = 0; j < nRepetitions; j++) { resultState = AStar.nextState(forwardModel, resultState, bestNextMove.Item1, bestNextMove.Item2); } addChildrenToOpenSet(openSet, bestOpen, resultState, heuristic); var stateNode = new StateNode (bestOpen, bestNextMove, resultState); var score = AStar.addNoise(stateNodeScorer (heuristic, stateNode)); closedSet.Add(score, stateNode); } while(i++ < maxIters && !closedSet.First().Value.Value.PlayStatus.isWon() && openSet.Count > 0); // Debug.WriteLine ("closedSet size: {0}", closedSet.Count); // int k = 0; // foreach (var pth in closedSet) { // var pathStr = string.Join(", ", pth.Value.ToPath().Select(tup1 => tup1.Item1.Item1 + "|" + tup1.Item1.Item2)); // Debug.WriteLine("closedSet[{0}]: {1} - {2}", k++, pth.Key, pathStr); // } lock (allPaths) { allPaths = closedSet; } var path = closedSet.First().Value.ToPath (); var deRooted = path.Count > 1 ? path.Skip (1) : path; // Ignore the root node // Debug.Print("bestPath1: {0}", moveListStr(deRooted.Select(x => x.Item1.Item1))); // Debug.Print("bestPath2: {0}", moveListStr(deRooted.Select(x => x.Item1.Item2))); var res = deRooted .SelectMany (t => Enumerable.Repeat(t.Item1,nRepetitions)).ToList(); return res; }
public TableColumnMap(string StoragePath, string TableName, string ColumnName, StringLengthAttribute StringLength, MaxLengthAttribute MaxLength) { int stringLength = StringLength != null ? StringLength.MaximumLength : 0; int stringArrayLength = MaxLength != null ? MaxLength.Length : 0; if (stringLength > 0) { MapRowSizeNoPosition = stringLength; if (stringArrayLength > 0) { MapRowSizeNoPosition *= stringArrayLength; } MapRowSizeNoPosition += 4; } else { MapRowSizeNoPosition = Marshal.SizeOf(typeof(T)); } MapRowSize = MapRowSizeNoPosition + 8; DeleteBuffer = Common.CreateDefaultArray(DeleteChar, MapRowSize); ColumnMap = $"{TableName}_{ColumnName}"; ColumnMapFile = $"{StoragePath}{ColumnMap}.map"; if (File.Exists(ColumnMapFile)) { FileInfo fi = new FileInfo(ColumnMapFile); CurrentColumnMapperSize = fi.Length; } MemoryMappedColumnMapFile = MemoryMappedFile.CreateFromFile(ColumnMapFile, FileMode.OpenOrCreate, ColumnMap, CurrentColumnMapperSize); MemoryMappedColumnMapStream = MemoryMappedColumnMapFile.CreateViewStream(0, CurrentColumnMapperSize); MemoryMappedColumnMapCountAccessor = MemoryMappedColumnMapFile.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Write); byte[] buffer = new byte[4]; MemoryMappedColumnMapStream.Read(buffer, 0, 4); int ExpectedMappings = BitConverter.ToInt32(buffer, 0); if (ExpectedMappings > 0) { for (long position = 0; position < MemoryMappedColumnMapStream.Length; position += MapRowSize) { buffer = new byte[MapRowSizeNoPosition]; MemoryMappedColumnMapStream.Read(buffer, 0, MapRowSizeNoPosition); if (!buffer.StartsWith(DeleteChar, MapRowSizeNoPosition)) { T key = ION.DeserializeObject <T>(buffer); buffer = new byte[8]; MemoryMappedColumnMapStream.Read(buffer, 0, 8); long filePosition = BitConverter.ToInt64(buffer, 0); ColumnMapper.Add(key, new MapperFilePostion(filePosition, position)); ExpectedMappings--; if (ExpectedMappings == 0) { break; } } else { //Skip Position MemoryMappedColumnMapStream.Position += MapRowSize; } } if (ExpectedMappings > 0) { throw new Exception("Mapping File Corrupt!"); } } }
public void TestIDictionaryT() { IDictionary <int, int> dictionary = new TreeDictionary <int, int>(branchingFactor: 4); for (int i = 0; i < 10; i++) { dictionary.Add(i, i); } Assert.Equal(10, dictionary.Count); Assert.False(dictionary.IsReadOnly); Assert.Equal(10, dictionary.Keys.Count); Assert.False(dictionary.Keys.IsReadOnly); Assert.Equal(10, dictionary.Values.Count); Assert.False(dictionary.Values.IsReadOnly); Assert.Equal(Enumerable.Range(0, 10), dictionary.Keys); Assert.Equal(Enumerable.Range(0, 10), dictionary.Values); Assert.Throws <NotSupportedException>(() => dictionary.Values.Remove(9)); Assert.False(dictionary.Keys.Remove(10)); Assert.True(dictionary.Keys.Remove(9)); Assert.Equal(9, dictionary.Count); Assert.Equal(9, dictionary.Keys.Count); Assert.False(dictionary.Keys.IsReadOnly); Assert.Equal(9, dictionary.Values.Count); Assert.False(dictionary.Values.IsReadOnly); Assert.Equal(Enumerable.Range(0, 9), dictionary.Keys); Assert.Equal(Enumerable.Range(0, 9), dictionary.Values); Assert.Throws <NotSupportedException>(() => dictionary.Keys.Add(0)); Assert.Throws <ArgumentNullException>("array", () => dictionary.Keys.CopyTo(null !, 0)); Assert.Throws <ArgumentOutOfRangeException>("arrayIndex", () => dictionary.Keys.CopyTo(new int[dictionary.Count], -1)); Assert.Throws <ArgumentOutOfRangeException>("arrayIndex", () => dictionary.Keys.CopyTo(new int[dictionary.Count], dictionary.Count + 1)); Assert.Throws <ArgumentException>(() => dictionary.Keys.CopyTo(new int[dictionary.Count], 1)); IEnumerator <int> keyEnumerator = dictionary.Keys.GetEnumerator(); Assert.NotNull(keyEnumerator); Assert.True(keyEnumerator.MoveNext()); Assert.Equal(0, keyEnumerator.Current); Assert.True(keyEnumerator.MoveNext()); Assert.Equal(1, keyEnumerator.Current); keyEnumerator.Reset(); Assert.True(keyEnumerator.MoveNext()); Assert.Equal(0, keyEnumerator.Current); Assert.Throws <NotSupportedException>(() => dictionary.Values.Add(0)); Assert.Throws <ArgumentNullException>("array", () => dictionary.Values.CopyTo(null !, 0)); Assert.Throws <ArgumentOutOfRangeException>("arrayIndex", () => dictionary.Values.CopyTo(new int[dictionary.Count], -1)); Assert.Throws <ArgumentOutOfRangeException>("arrayIndex", () => dictionary.Values.CopyTo(new int[dictionary.Count], dictionary.Count + 1)); Assert.Throws <ArgumentException>(() => dictionary.Values.CopyTo(new int[dictionary.Count], 1)); IEnumerator <int> valueEnumerator = dictionary.Values.GetEnumerator(); Assert.NotNull(valueEnumerator); Assert.True(valueEnumerator.MoveNext()); Assert.Equal(0, valueEnumerator.Current); Assert.True(valueEnumerator.MoveNext()); Assert.Equal(1, valueEnumerator.Current); valueEnumerator.Reset(); Assert.True(valueEnumerator.MoveNext()); Assert.Equal(0, valueEnumerator.Current); IReadOnlyDictionary <int, int> readOnlyDictionary = (IReadOnlyDictionary <int, int>)dictionary; Assert.Equal(dictionary.Keys, readOnlyDictionary.Keys); Assert.Equal(dictionary.Values, readOnlyDictionary.Values); dictionary.Add(new KeyValuePair <int, int>(11, 11)); Assert.Equal(11, dictionary[11]); Assert.True(dictionary.Contains(new KeyValuePair <int, int>(11, 11))); Assert.False(dictionary.Contains(new KeyValuePair <int, int>(11, 12))); Assert.False(dictionary.Contains(new KeyValuePair <int, int>(12, 12))); Assert.False(dictionary.Remove(new KeyValuePair <int, int>(11, 12))); Assert.True(dictionary.Contains(new KeyValuePair <int, int>(11, 11))); Assert.True(dictionary.Remove(new KeyValuePair <int, int>(11, 11))); Assert.False(dictionary.Contains(new KeyValuePair <int, int>(11, 11))); Assert.NotEmpty(dictionary); dictionary.Keys.Clear(); Assert.Empty(dictionary); Assert.Empty(dictionary.Keys); Assert.Empty(dictionary.Values); dictionary[0] = 1; Assert.NotEmpty(dictionary); dictionary.Values.Clear(); Assert.Empty(dictionary); Assert.Empty(dictionary.Keys); Assert.Empty(dictionary.Values); }
public void Indexer_Test() { treeDict.Add(0, 00); treeDict.Add(1, 11); treeDict.Add(2, 33); treeDict.Add(3, 88); treeDict[2] = 77; Assert.AreEqual(4, treeDict.Count); Assert.AreEqual(11, treeDict[1]); Assert.AreEqual(33, treeDict[2]); }
public void TestIDictionary() { IDictionary dictionary = new TreeDictionary <int, int>(branchingFactor: 4); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); Assert.False(dictionary.IsSynchronized); Assert.Throws <ArgumentNullException>("key", () => dictionary.Add(key: null, value: 1)); Assert.Throws <ArgumentException>("value", () => dictionary.Add(key: 1, value: null)); Assert.Throws <ArgumentException>("key", () => dictionary.Add(key: "string value", value: 0)); Assert.Throws <ArgumentException>("value", () => dictionary.Add(key: 0, value: "string value")); for (int i = 0; i < 11; i++) { dictionary.Add(i, i + 1); } Assert.Throws <ArgumentNullException>("key", () => dictionary[key: null]); Assert.Null(dictionary["string key"]); Assert.Equal(11, dictionary[10]); Assert.Throws <ArgumentNullException>("key", () => dictionary[key: null] = 12); Assert.Throws <ArgumentException>("key", () => dictionary["string key"] = 12); Assert.Throws <ArgumentException>("value", () => dictionary[10] = null); Assert.Throws <ArgumentException>("value", () => dictionary[10] = "string value"); dictionary[10] = 12; Assert.Equal(12, dictionary[10]); dictionary[10] = 11; TestCollection(dictionary, i => new KeyValuePair <int, int>(i, i + 1)); var entries = new DictionaryEntry[dictionary.Count]; dictionary.CopyTo(entries, 0); Assert.Equal(entries.Select(i => i.Key), dictionary.Keys.Cast <object>()); Assert.Equal(entries.Select(i => i.Value), dictionary.Values.Cast <object>()); Assert.Throws <ArgumentNullException>(() => dictionary.Contains(null)); Assert.False(dictionary.Contains("string value")); Assert.True(dictionary.Contains(10)); Assert.Throws <ArgumentNullException>(() => dictionary.Remove(null)); Assert.Equal(11, dictionary.Count); dictionary.Remove("string value"); Assert.Equal(11, dictionary.Count); dictionary.Remove(10); Assert.Equal(10, dictionary.Count); Assert.False(dictionary.Contains(10)); IDictionaryEnumerator enumerator = dictionary.GetEnumerator(); Assert.NotNull(enumerator); Assert.True(enumerator.MoveNext()); Assert.Equal(0, enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Key); Assert.Equal(2, enumerator.Value); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal(enumerator.Entry, enumerator.Current); enumerator.Reset(); Assert.True(enumerator.MoveNext()); Assert.Equal(0, enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal(enumerator.Entry, enumerator.Current); ICollection keys = dictionary.Keys; TestCollection(keys, i => i); ICollection values = dictionary.Values; TestCollection(values, i => i + 1); dictionary.Clear(); Assert.Empty(dictionary); Assert.Empty(keys); Assert.Empty(values); void TestCollection <T>(ICollection collection, Func <int, T> indexToExpectedValue) { Assert.NotNull(collection); Assert.False(collection.IsSynchronized); Assert.Same(dictionary.SyncRoot, collection.SyncRoot); Assert.Throws <ArgumentNullException>("array", () => collection.CopyTo(null, 0)); Assert.Throws <ArgumentException>(() => collection.CopyTo(new int[collection.Count, 1], 0)); Assert.Throws <ArgumentException>(() => collection.CopyTo(Array.CreateInstance(typeof(int), lengths: new[] { collection.Count }, lowerBounds: new[] { 1 }), 0)); Assert.Throws <ArgumentOutOfRangeException>("index", () => collection.CopyTo(new int[collection.Count], -1)); Assert.Throws <ArgumentOutOfRangeException>("index", () => collection.CopyTo(new int[collection.Count], collection.Count + 1)); Assert.Throws <ArgumentException>(() => collection.CopyTo(new int[collection.Count], 1)); var elements = new T[collection.Count]; collection.CopyTo(elements, 0); Assert.Equal(elements, collection); var objects = new object[collection.Count]; collection.CopyTo(objects, 0); Assert.Equal(objects, collection); Assert.Throws <ArgumentException>(() => collection.CopyTo(new string[collection.Count], 0)); Assert.Throws <ArgumentException>(() => collection.CopyTo(new byte[collection.Count], 0)); IEnumerator collectionEnumerator = collection.GetEnumerator(); Assert.NotNull(collectionEnumerator); Assert.True(collectionEnumerator.MoveNext()); Assert.Equal(indexToExpectedValue(0), collectionEnumerator.Current); Assert.True(collectionEnumerator.MoveNext()); Assert.Equal(indexToExpectedValue(1), collectionEnumerator.Current); collectionEnumerator.Reset(); Assert.True(collectionEnumerator.MoveNext()); Assert.Equal(indexToExpectedValue(0), collectionEnumerator.Current); } }