Exemple #1
0
 protected void ContainsTestHelper <TKey, TValue>(IImmutableDictionary <TKey, TValue> map, TKey key, TValue value)
 {
     Assert.False(map.Contains(new KeyValuePair <TKey, TValue>(key, value)));
     Assert.False(map.Contains(key, value));
     Assert.True(map.Add(key, value).Contains(new KeyValuePair <TKey, TValue>(key, value)));
     Assert.True(map.Add(key, value).Contains(key, value));
 }
        private IImmutableDictionary <IActorRef, IImmutableList <string> > CreateAllocations(int aCount, int bCount = 0, int cCount = 0)
        {
            IImmutableDictionary <IActorRef, IImmutableList <string> > allocations = ImmutableDictionaryKeepOrder <IActorRef, IImmutableList <string> > .Empty;

            allocations = allocations.Add(regionA, shards.Take(aCount).ToImmutableList());
            allocations = allocations.Add(regionB, shards.Skip(aCount).Take(bCount).ToImmutableList());
            allocations = allocations.Add(regionC, shards.Skip(aCount + bCount).Take(cCount).ToImmutableList());
            return(allocations);
        }
Exemple #3
0
 /// <inheritdoc />
 public Task <bool> AddAsync(IActiveLock activeLock, CancellationToken cancellationToken)
 {
     if (_locks.ContainsKey(activeLock.StateToken))
     {
         return(Task.FromResult(false));
     }
     _locks = _locks.Add(activeLock.StateToken, activeLock);
     return(Task.FromResult(true));
 }
        protected void AddExistingKeySameValueTestHelper <TKey, TValue>(IImmutableDictionary <TKey, TValue> map, TKey key, TValue value1, TValue value2)
        {
            Assert.NotNull(map);
            Assert.NotNull(key);
            Assert.True(GetValueComparer(map).Equals(value1, value2));

            map = map.Add(key, value1);
            Assert.Same(map, map.Add(key, value2));
            Assert.Same(map, map.AddRange(new[] { new KeyValuePair <TKey, TValue>(key, value2) }));
        }
        public static void Create()
        {
            IImmutableDictionary <int, string> d = ImmutableDictionary.Create <int, string>();

            d = d.Add(1, "One");
            d = d.Add(2, "Two");
            d = d.Add(3, "Three");

            System.Console.WriteLine(d[2]);
        }
Exemple #6
0
        protected void AddExistingKeySameValueTestHelper <TKey, TValue>(IImmutableDictionary <TKey, TValue> map, TKey key, TValue value1, TValue value2)
        {
            Contract.Requires(map != null);
            Contract.Requires(key != null);
            Contract.Requires(GetValueComparer(map).Equals(value1, value2));

            map = map.Add(key, value1);
            Assert.Same(map, map.Add(key, value2));
            Assert.Same(map, map.AddRange(new[] { new KeyValuePair <TKey, TValue>(key, value2) }));
        }
Exemple #7
0
        public void TestAdd()
        {
            IImmutableDictionary <int, int> dictionary = CreateDictionary <int, int>();

            Assert.Empty(dictionary);

            dictionary = dictionary.Add(1, 1);
            Assert.Same(dictionary, dictionary.Add(1, 1));
            Assert.Throws <ArgumentException>(() => dictionary.Add(1, 2));
        }
Exemple #8
0
        private IImmutableDictionary <IActorRef, IImmutableList <string> > CreateAllocations(int aCount, int bCount = 0, int cCount = 0)
        {
            var shards = Enumerable.Range(1, (aCount + bCount + cCount)).Select(i => i.ToString("000"));

            IImmutableDictionary <IActorRef, IImmutableList <string> > allocations = ImmutableDictionaryKeepOrder <IActorRef, IImmutableList <string> > .Empty;

            allocations = allocations.Add(_regionA, shards.Take(aCount).ToImmutableList());
            allocations = allocations.Add(_regionB, shards.Skip(aCount).Take(bCount).ToImmutableList());
            allocations = allocations.Add(_regionC, shards.Skip(aCount + bCount).Take(cCount).ToImmutableList());
            return(allocations);
        }
        /// <summary>
        /// Verifies that adding a key-value pair where the key already is in the map but with a different value throws.
        /// </summary>
        /// <typeparam name="TKey">The type of key in the map.</typeparam>
        /// <typeparam name="TValue">The type of value in the map.</typeparam>
        /// <param name="map">The map to manipulate.</param>
        /// <param name="key">The key to add.</param>
        /// <param name="value1">The first value to add.</param>
        /// <param name="value2">The second value to add.</param>
        /// <remarks>
        /// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the
        /// semantic of "adding", either by just returning or mutating the value on the existing key.  Throwing is the only reasonable response.
        /// </remarks>
        protected void AddExistingKeyDifferentValueTestHelper <TKey, TValue>(IImmutableDictionary <TKey, TValue> map, TKey key, TValue value1, TValue value2)
        {
            Assert.NotNull(map);
            Assert.NotNull(key);
            Assert.False(GetValueComparer(map).Equals(value1, value2));

            var map1 = map.Add(key, value1);
            var map2 = map.Add(key, value2);

            AssertExtensions.Throws <ArgumentException>(null, () => map1.Add(key, value2));
            AssertExtensions.Throws <ArgumentException>(null, () => map2.Add(key, value1));
        }
Exemple #10
0
        /// <summary>
        /// Verifies that adding a key-value pair where the key already is in the map but with a different value throws.
        /// </summary>
        /// <typeparam name="TKey">The type of key in the map.</typeparam>
        /// <typeparam name="TValue">The type of value in the map.</typeparam>
        /// <param name="map">The map to manipulate.</param>
        /// <param name="key">The key to add.</param>
        /// <param name="value1">The first value to add.</param>
        /// <param name="value2">The second value to add.</param>
        /// <remarks>
        /// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the
        /// semantic of "adding", either by just returning or mutating the value on the existing key.  Throwing is the only reasonable response.
        /// </remarks>
        protected void AddExistingKeyDifferentValueTestHelper <TKey, TValue>(IImmutableDictionary <TKey, TValue> map, TKey key, TValue value1, TValue value2)
        {
            Contract.Requires(map != null);
            Contract.Requires(key != null);
            Contract.Requires(!GetValueComparer(map).Equals(value1, value2));

            var map1 = map.Add(key, value1);
            var map2 = map.Add(key, value2);

            Assert.Throws <ArgumentException>(() => map1.Add(key, value2));
            Assert.Throws <ArgumentException>(() => map2.Add(key, value1));
        }
Exemple #11
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case RequestTrackDevice trackMsg:
                if (groupIdToActor.TryGetValue(trackMsg.GroupId, out var actorRef))
                {
                    actorRef.Forward(trackMsg);
                }
                else
                {
                    Log.Info($"Creating device group actor for {trackMsg.GroupId}");
                    var groupActor = Context.ActorOf(DeviceGroup.Props(trackMsg.GroupId), $"group-{trackMsg.GroupId}");
                    Context.Watch(groupActor);
                    groupActor.Forward(trackMsg);
                    groupIdToActor = groupIdToActor.Add(trackMsg.GroupId, groupActor);
                    actorToGroupId = actorToGroupId.Add(groupActor, trackMsg.GroupId);
                }
                break;

            case Terminated t:
                var groupId = actorToGroupId[t.ActorRef];
                Log.Info($"Device group actor for {groupId} has been terminated");
                actorToGroupId = actorToGroupId.Remove(t.ActorRef);
                groupIdToActor = groupIdToActor.Remove(groupId);
                break;
            }
        }
        public override async Task <IImmutableDictionary <string, string> > GetGlobalPropertiesAsync(CancellationToken cancellationToken)
        {
            IImmutableDictionary <string, string> properties = Empty.PropertiesMap;

            // Check:
            //   - if this is an implicitly-triggered build
            //   - if there is a single startup project
            //   - if this is the startup project in question
            //   - if this is a cross targeting project, i.e. project configuration has a "TargetFramework" dimension
            //   - if the option to prefer single-target builds is turned on
            if (_implicitlyTriggeredBuildState.IsImplicitlyTriggeredBuild &&
                _implicitlyTriggeredBuildState.StartupProjectFullPaths.Length == 1 &&
                StringComparers.Paths.Equals(_implicitlyTriggeredBuildState.StartupProjectFullPaths[0], _configuredProject.UnconfiguredProject.FullPath) &&
                _configuredProject.ProjectConfiguration.IsCrossTargeting() &&
                await _projectSystemOptions.GetPreferSingleTargetBuildsForStartupProjectsAsync(cancellationToken))
            {
                // We only want to build this for the framework that we will launch.
                string?activeDebuggingFramework = await _activeDebugFrameworkServices.GetActiveDebuggingFrameworkPropertyAsync();

                if (activeDebuggingFramework is not null)
                {
                    properties = properties.Add(ConfigurationGeneral.TargetFrameworkProperty, activeDebuggingFramework);
                }
            }

            return(properties);
        }
Exemple #13
0
        /// <summary>
        /// Writes a <see cref="Packet"/> object to the currrent stream.
        /// </summary>
        /// <param name="packet">The <see cref="Packet"/> object.</param>
        public void Write(Packet packet)
        {
            var range = new Range <long>();

            range.Minimum = BaseStream.Position;

            packet.Header.CopyTo(BaseStream);
            packet.Body.CopyTo(BaseStream);

            range.Maximum = BaseStream.Position - 1;

            var overwrittenPackets = packets
                                     .Where(x => range.IsInsideRange(new Range <long>
            {
                Minimum = x.Key,
                Maximum = x.Key + x.Value - 1
            }))
                                     .Select(x => x.Key);

            foreach (var key in overwrittenPackets)
            {
                packets = packets.Remove(key);
            }

            packets = packets.Add(range.Minimum, range.Maximum - range.Minimum + 1);
        }
Exemple #14
0
        private IImmutableDictionary <int, IImmutableDictionary <int, int> > AddSleepyTime(
            IImmutableDictionary <int, IImmutableDictionary <int, int> > slots,
            int guardId,
            int startMinutes,
            int endMinutes)
        {
            IEnumerable <int> minutesInWhichAsleep = Enumerable.Range(startMinutes, endMinutes - startMinutes + 1);

            if (!slots.TryGetValue(guardId, out IImmutableDictionary <int, int> guardSleepCounts))
            {
                var b = ImmutableDictionary.CreateRange(
                    minutesInWhichAsleep
                    .Select(i => new KeyValuePair <int, int>(i, 1)));

                return(slots.Add(guardId, b.ToImmutableDictionary()));
            }

            guardSleepCounts = minutesInWhichAsleep
                               .Aggregate(
                guardSleepCounts,
                (s, i) => s.TryGetValue(i, out int currentSleepsThisSlot)
                        ? s.SetItem(i, currentSleepsThisSlot + 1)
                        : s.Add(i, 1));
            return(slots.SetItem(guardId, guardSleepCounts));
        }
Exemple #15
0
 /// <inheritdoc />
 public IImmutableDictionary <Address, object> Add(
     Address key,
     object value
     )
 {
     return(new AddressStateMap(_impl.Add(key, value)));
 }
Exemple #16
0
        public void TestRemove()
        {
            IImmutableDictionary <int, int> dictionary = CreateDictionary <int, int>();

            for (int i = 0; i < 4; i++)
            {
                dictionary = dictionary.Add(i, i);
            }

            Assert.Same(dictionary, dictionary.Remove(4));

            Assert.Equal(
                new[]
            {
                new KeyValuePair <int, int>(0, 0),
                new KeyValuePair <int, int>(1, 1),
                new KeyValuePair <int, int>(2, 2),
            },
                dictionary.Remove(3));

            Assert.Equal(
                new[]
            {
                new KeyValuePair <int, int>(0, 0),
                new KeyValuePair <int, int>(2, 2),
                new KeyValuePair <int, int>(3, 3),
            },
                dictionary.Remove(1));
        }
Exemple #17
0
        public static void CollectRoslynReferences(
            ref IImmutableDictionary <AssemblyShortName, AssemblyDetails> usedRoslynAssemblies,
            IImmutableDictionary <AssemblyShortName, string> roslynAssemblyPaths,
            ref IImmutableDictionary <AssemblyShortName, AssemblyDetails> mainAssemblies,
            IImmutableDictionary <AssemblyShortName, IImmutableSet <PackageInfo> > roslynPackageMap,
            out IImmutableDictionary <AssemblyShortName, AssemblyDetails> othersReferencedByRoslyn
            )
        {
            var othersReferencedByRoslynBuilder = ImmutableSortedDictionary.CreateBuilder <AssemblyShortName, AssemblyDetails>();

            FluentConsole.White.Line("Analyzing Roslyn references…");
            var seen  = new HashSet <AssemblyShortName>();
            var queue = new Queue <AssemblyDetails>(usedRoslynAssemblies.Values);

            while (queue.Count > 0)
            {
                var assembly = queue.Dequeue();
                FluentConsole.Gray.Line($"  {assembly.Definition.Name.Name}");
                seen.Add(assembly.Definition.Name.Name);
                foreach (var reference in assembly.Definition.MainModule.AssemblyReferences)
                {
                    if (!seen.Add(reference.Name))
                    {
                        continue;
                    }
                    FluentConsole.Gray.Line($"    {reference.FullName}");
                    mainAssemblies = mainAssemblies.Remove(reference.Name);
                    if (usedRoslynAssemblies.ContainsKey(reference.Name))
                    {
                        FluentConsole.Gray.Line("      [roslyn assembly, already used]");
                        continue;
                    }
                    var roslynAssemblyPath = roslynAssemblyPaths.GetValueOrDefault(reference.Name);
                    if (roslynAssemblyPath != null)
                    {
                        FluentConsole.Gray.Line("      [roslyn assembly, queued]");
                        var roslynAssembly = AssemblyDetails.ReadFrom(roslynAssemblyPath, readSymbols: true);
                        usedRoslynAssemblies = usedRoslynAssemblies.Add(roslynAssembly.Definition.Name.Name, roslynAssembly);
                        queue.Enqueue(roslynAssembly);
                        continue;
                    }
                    if (InGlobalAssemblyCache(reference))
                    {
                        FluentConsole.Gray.Line("      [gac]");
                        continue;
                    }

                    var referencedAssembly = GetAssemblyDetailsFromNuGetCache(reference.Name, roslynPackageMap);
                    if (referencedAssembly == null)
                    {
                        FluentConsole.Gray.Line("      [system?]");
                        continue;
                    }
                    othersReferencedByRoslynBuilder.Add(reference.Name, referencedAssembly);
                    queue.Enqueue(referencedAssembly);
                }
            }
            othersReferencedByRoslyn = othersReferencedByRoslynBuilder.ToImmutable();
        }
        public async Task AddWorkout(Workout workout)
        {
            CheckIsNotNull(nameof(workout), workout);

            _workouts = _workouts.Add(workout.WorkoutId, workout);

            await Task.CompletedTask;
        }
        public async Task AddExercise(Exercise exercise)
        {
            CheckIsNotNull(nameof(exercise), exercise);

            _exercises = _exercises.Add(exercise.ExerciseId, exercise);

            await Task.CompletedTask;
        }
        public async Task AddDeck(Deck deck)
        {
            CheckIsNotNull(nameof(deck), deck);

            _decks = _decks.Add(deck.DeckId, deck);

            await Task.CompletedTask;
        }
Exemple #21
0
 protected static void ContainsKeyTestHelper <TKey, TValue>(
     IImmutableDictionary <TKey, TValue> map,
     TKey key,
     TValue value
     )
 {
     Assert.False(map.ContainsKey(key));
     Assert.True(map.Add(key, value).ContainsKey(key));
 }
Exemple #22
0
        private IWriteHandler CheckBaseClasses(Type type)
        {
            Type baseType = type.GetTypeInfo().BaseType;

            while (baseType != null && baseType != typeof(object))
            {
                IWriteHandler handler;
                if (handlers.TryGetValue(baseType, out handler))
                {
                    handlers = handlers.Add(type, handler);
                    return(handler);
                }

                baseType = baseType.GetTypeInfo().BaseType;
            }

            return(null);
        }
        public static IImmutableDictionary <string, IProjectRuleSnapshot> Add(this IImmutableDictionary <string, IProjectRuleSnapshot> snapshots, string ruleName, string propertyName, string propertyValue)
        {
            if (!snapshots.TryGetValue(ruleName, out IProjectRuleSnapshot snapshot))
            {
                snapshot = IProjectRuleSnapshotFactory.Create(ruleName, propertyName, propertyValue);
                return(snapshots.Add(ruleName, snapshot));
            }

            return(snapshots.SetItem(ruleName, snapshot.Add(propertyName, propertyValue)));
        }
Exemple #24
0
        public void TestClear()
        {
            IImmutableDictionary <int, int> dictionary = CreateDictionary <int, int>();

            Assert.Empty(dictionary);
            Assert.Same(dictionary, dictionary.Clear());

            dictionary = dictionary.Add(1, 1);
            Assert.Empty(dictionary.Clear());
        }
        protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
        {
            Assert.Equal(0, map.Values.Count());
            Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count());

            var nonEmpty = map.Add(key, default(TValue));
            Assert.Equal(1, nonEmpty.Values.Count());
            Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count());
            KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue));
        }
        private bool IsNamespaceMatch(Type type)
        {
            if (!namespaceScratchPad.ContainsKey(type))
            {
                var ns    = type.Namespace ?? "";
                var match = config.ModelNamespaces.Any(ns.StartsWith);
                namespaceScratchPad = namespaceScratchPad.Add(type, match);
            }

            return(namespaceScratchPad[type]);
        }
Exemple #27
0
        /// <summary>
        /// Gets a new or existing section descriptor
        /// </summary>
        /// <typeparam name="T">The type of the configuration section</typeparam>
        /// <returns>The section descriptor for <see cref="T:self"/></returns>
        internal static IConfigurationSectionDescriptor GetSectionDescriptor <T>(string sectionKey)
            where T : class, IConfigurationSection <T>
        {
            if (sectionDescriptors.ContainsKey(typeof(T)))
            {
                return(sectionDescriptors[typeof(T)]);
            }

            sectionDescriptors = sectionDescriptors.Add(typeof(T), new ConfigurationSectionDescriptor <T>(sectionKey));
            return(sectionDescriptors[typeof(T)]);
        }
Exemple #28
0
        /// <summary>
        /// Gets a new or existing collection descriptor
        /// </summary>
        /// <typeparam name="T">The type of the configuration collection</typeparam>
        /// <returns>The collection descriptor for <see cref="T:self"/></returns>
        internal static IConfigurationCollectionDescriptor GetCollectionDescriptor <T>()
            where T : class, IConfigurationCollection <T>
        {
            if (collectionDescriptors.ContainsKey(typeof(T)))
            {
                return(collectionDescriptors[typeof(T)]);
            }

            collectionDescriptors = collectionDescriptors.Add(typeof(T), new ConfigurationCollectionDescriptor <T>());
            return(collectionDescriptors[typeof(T)]);
        }
Exemple #29
0
        /// <summary>
        /// Gets the set of global properties that should apply to the project(s) in this scope.
        /// </summary>
        /// <value>A map whose keys are case insensitive.  Never null, but may be empty.</value>
        public override Task <IImmutableDictionary <string, string> > GetGlobalPropertiesAsync(CancellationToken cancellationToken)
        {
            IImmutableDictionary <string, string> properties = Empty.PropertiesMap;

            if (_overrideGeneratePackageOnBuild.HasValue)
            {
                properties = properties.Add(ConfigurationGeneralBrowseObject.GeneratePackageOnBuildProperty, _overrideGeneratePackageOnBuild.Value ? "true" : "false");
            }

            return(Task.FromResult(properties));
        }
Exemple #30
0
        public override IImmutableDictionary <TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            // Validate parameters.
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // Is this null?  If so, return null.
            if (reader.TokenType == JsonTokenType.Null)
            {
                return(null !);
            }

            // If it is not an object, throw.
            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new JsonException($"Expected a token type of {nameof(JsonTokenType.StartObject)}, encountered {reader.TokenType}.");
            }

            // The return value.
            IImmutableDictionary <TKey, TValue> values = ImmutableDictionary <TKey, TValue> .Empty;

            // Cycle.
            while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
            {
                // We should be on the name now.  Get the string.
                string stringKey = reader.GetString();

                // Convert the key.
                TKey key = _keyDeserializer(stringKey, options);

                // Move the reader now.
                if (!reader.Read())
                {
                    throw new JsonException($"Expected call to {nameof(Utf8JsonReader.Read)} to return true, returned false.");
                }

                // Deserialize the value.
                TValue value = _valueDeserializer(ref reader, options);

                // Add.
                values = values.Add(key, value);
            }

            // If the token is not an end object, throw.
            if (reader.TokenType != JsonTokenType.EndObject)
            {
                throw new JsonException($"Expected a token of {JsonTokenType.EndObject}, actual {reader.TokenType}.");
            }

            // Return the values.
            return(values);
        }
Exemple #31
0
        /// <summary>
        /// Writes a <see cref="Packet"/> object to the currrent stream.
        /// </summary>
        /// <param name="packet">The <see cref="Packet"/> object.</param>
        public void Write(Packet packet)
        {
            var range = new Range<long>();
            range.Minimum = BaseStream.Position;
            
            packet.Header.CopyTo(BaseStream);
            packet.Body.CopyTo(BaseStream);

            range.Maximum = BaseStream.Position - 1;

            var overwrittenPackets = packets
                .Where(x => range.IsInsideRange(new Range<long>
                {
                    Minimum = x.Key,
                    Maximum = x.Key + x.Value - 1
                }))
                .Select(x => x.Key);

            foreach (var key in overwrittenPackets)
            {
                packets = packets.Remove(key);
            }

            packets = packets.Add(range.Minimum, range.Maximum - range.Minimum + 1);
        }