コード例 #1
0
        private static T GetOrAdd <T>(ref ImmutableHashSet <T> location, T value)
        {
            ImmutableHashSet <T> prior = Volatile.Read(ref location);

            while (true)
            {
                if (prior.TryGetValue(value, out T existingValue))
                {
                    // The value already exists in the set. Return it.
                    return(existingValue);
                }

                // Add a value to the set. This will succeed as we've just seen that value is not in prior.
                ImmutableHashSet <T> updated = prior.Add(value);

                // Attempt to update the field optimistically.
                ImmutableHashSet <T> original = Interlocked.CompareExchange(ref location, updated, prior);

                if (ReferenceEquals(original, prior))
                {
                    // The update was successful; return the added icon set.
                    return(value);
                }

                // Optimistic update failed, so loop around and try again.
            }
        }
コード例 #2
0
        public T Intern(T value)
        {
            // Would be nice if this was on ImmutableInterlocked as
            // requested in https://github.com/dotnet/corefx/issues/33653

            ImmutableHashSet <T> priorCollection = Volatile.Read(ref _set);

            bool successful;

            do
            {
                if (priorCollection.TryGetValue(value, out T existingValue))
                {
                    // The value already exists in the set. Return it.
                    return(existingValue);
                }

                ImmutableHashSet <T> updatedCollection = priorCollection.Add(value);
                ImmutableHashSet <T> interlockedResult = Interlocked.CompareExchange(ref _set, updatedCollection, priorCollection);
                successful      = ReferenceEquals(priorCollection, interlockedResult);
                priorCollection = interlockedResult; // We already have a volatile read that we can reuse for the next loop
            }while (!successful);

            // We won the race-condition and have updated the collection.
            // Return the value that is in the collection (as of the Interlocked operation).
            return(value);
        }
コード例 #3
0
ファイル: Wallet.cs プロジェクト: DrunkyBard/VendingMachine
        public Wallet Put(Coin coin)
        {
            if (coin.Total == decimal.Zero)
            {
                return(this);
            }

            Coin oldValue;
            var  newCoinValue = _coins.TryGetValue(coin, out oldValue)
                ? oldValue.Add(coin.Count)
                : coin;
            var updatedWallet = _coins
                                .Remove(oldValue)
                                .Add(newCoinValue);

            return(new Wallet(updatedWallet));
        }
コード例 #4
0
 public DependencyIconSet GetOrAddIconSet(DependencyIconSet iconSet)
 {
     if (ThreadingTools.ApplyChangeOptimistically(ref _iconSets, iconSets => iconSets.Add(iconSet)))
     {
         // The cache did not already contain an equivalent icon set; use the one passed in.
         return(iconSet);
     }
     else
     {
         // The cache already has an equivalent icon set; retrieve and return that one.
         _iconSets.TryGetValue(iconSet, out DependencyIconSet existingIconSet);
         return(existingIconSet);
     }
 }
コード例 #5
0
 public bool TryGetValue(string equalValue, out string actualValue)
 {
     return(_set.TryGetValue(equalValue, out actualValue));
 }
コード例 #6
0
        /// <summary>
        /// Install a NuGet package. Returns all newly installed packages.
        /// </summary>
        public async Task <IReadOnlyCollection <InteractivePackage> > InstallPackageAsync(
            InteractivePackage package,
            SourceRepository sourceRepository,
            CancellationToken cancellationToken)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (!package.Identity.HasVersion)
            {
                throw new ArgumentException("PackageIdentity.Version must be set");
            }

            // TODO: File upstream issue about exception if primary source repo is offline.
            //       Shouldn't secondary source repos kick in? Our current work around is to
            //       pass the source repo from search to install, but that's not perfect.
            sourceRepository = sourceRepository ?? SourceRepositories [0];

            project.ResetInstallationContext();

            // Just need to apply one fixup here
            if (PackageIdComparer.Equals(package.Identity.Id, FixedXamarinFormsPackageIdentity.Id) &&
                package.Identity.Version != FixedXamarinFormsPackageIdentity.Version)
            {
                Log.Warning(
                    TAG,
                    $"Replacing requested Xamarin.Forms version {package.Identity.Version} with " +
                    $"required version {FixedXamarinFormsPackageIdentity.Version}.");
                package = package.WithVersion(
                    FixedXamarinFormsPackageIdentity.Version,
                    overwriteRange: true);
            }

            if (PackageIdComparer.Equals(package.Identity.Id, IntegrationPackageId))
            {
                Log.Warning(TAG, $"Refusing to add integration NuGet package {IntegrationPackageId}.");
                return(Array.Empty <InteractivePackage> ());
            }

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest, // IDEs only use Highest if upgrading
                includePrelease: true,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            // Although there is a single repo associated with the package being installed,
            // dependency resolution will also look into the secondary sources. In some cases,
            // this can greatly slow down installation. For the primary case of searching for
            // packages in nuget.org, prevent the package manager from using secondary sources
            // for resolution.
            //
            // It is important to pass an empty enumerable, because if we pass null, the package
            // manager will determine secondary sources based on the NuGet configuration.
            var secondarySources =
                sourceRepository == SourceRepositories [0]
                ? Enumerable.Empty <SourceRepository> ()
                : SourceRepositories.Where(r => r != sourceRepository).ToArray();

            // There does not appear to be a way to hook into or override functionality of the
            // NuGetPackageManager or PackageResolver classes. In order to mess with package
            // resolution, we need to either write a lot of code, proxy the sources, or intercede
            // via preview installation actions.
            //
            // Here we do the latter, though it is not the best general-purpose approach. It works
            // fine for replacing one single package that we know a LOT about. If that package's
            // dependencies continually changed, we'd be better off with another approach.
            var previewInstallActions = await packageManager.PreviewInstallPackageAsync(
                project,
                package.Identity,
                resolutionContext,
                projectContext,
                sourceRepository,
                secondarySources,
                cancellationToken);

            var installActions = new List <NuGetProjectAction> ();

            foreach (var action in previewInstallActions)
            {
                // If the installed package has a dependency on Xamarin.Forms, make sure the version
                // that gets installed is our preferred version. Force it to install from the primary
                // source repository, because we can't assume that version is available everywhere.
                //
                // TODO: Consider adding a search or something to see if we can use the specified source
                //       instead. Could be handy if nuget.org is down or the user is offline and using
                //       a local repo.
                if (action.PackageIdentity.Id == FixedXamarinFormsPackageIdentity.Id)
                {
                    installActions.Add(NuGetProjectAction.CreateInstallProjectAction(
                                           FixedXamarinFormsPackageIdentity,
                                           SourceRepositories [0],
                                           action.Project));
                }
                else
                {
                    installActions.Add(action);
                }
            }

            // We follow the modern behavior of .NET Core and do not actually install packages anywhere.
            // Instead, we ultimately reference them out of the user's global package cache (by default,
            // ~/.nuget/packages). Our NuGetProject implementation simply collects package assembly
            // references (and potentially other necessary files) and populates them back into the
            // InteractiveInstallationContext.
            using (var sourceCacheContext = new SourceCacheContext())
                await packageManager.ExecuteNuGetProjectActionsAsync(
                    project,
                    installActions,
                    projectContext,
                    sourceCacheContext,
                    cancellationToken);

            // Identify which packages were not already noted as installed, or have been upgraded now
            var newlyInstalledPackages = new List <InteractivePackage> ();

            foreach (var newPackage in project.InstallationContext.InstalledPackages)
            {
                InteractivePackage finalNewPackage;
                var foundInstalledMatch = installedPackages.TryGetValue(
                    newPackage,
                    out finalNewPackage);

                if (!foundInstalledMatch ||
                    newPackage.Identity.Version > finalNewPackage.Identity.Version)
                {
                    // Make sure we have a reference to a matching explicit InteractivePackage if it
                    // exists, so that we can persist the original SupportedVersionRange
                    if (!foundInstalledMatch)
                    {
                        finalNewPackage = PackageIdComparer.Equals(package, newPackage)
                            ? package
                            : newPackage;
                    }

                    finalNewPackage = newPackage
                                      .WithIsExplicit(finalNewPackage.IsExplicit)
                                      .WithSupportedVersionRange(finalNewPackage.SupportedVersionRange);

                    newlyInstalledPackages.Add(finalNewPackage);
                    installedPackages = installedPackages
                                        .Remove(finalNewPackage)
                                        .Add(finalNewPackage);
                    UpdateInstalledPackages();
                }
            }

            return(newlyInstalledPackages);
        }
コード例 #7
0
 /// <inheritdoc />
 public bool TryGetValue(T equalValue, out T actualValue)
 {
     return(_set.TryGetValue(equalValue, out actualValue));
 }
コード例 #8
0
        private static void AnalyzeSymbols(SymbolAnalysisContext ctx)
        {
            PooledHashSet <ISymbol> instance1 = PooledHashSet <ISymbol> .GetInstance();

            PooledHashSet <ISymbol> instance2 = PooledHashSet <ISymbol> .GetInstance();

            PooledHashSet <ISymbol> instance3 = PooledHashSet <ISymbol> .GetInstance();

            PooledHashSet <ISymbol> instance4 = PooledHashSet <ISymbol> .GetInstance();

            PooledHashSet <ISymbol> instance5 = PooledHashSet <ISymbol> .GetInstance();

            PooledHashSet <ISymbol> instance6 = PooledHashSet <ISymbol> .GetInstance();

            ImmutableArray <ISymbol> members = ((IContainerSymbol)ctx.Symbol).GetMembers();

            try
            {
                ImmutableArray <ISymbol> .Enumerator enumerator1 = members.GetEnumerator();
                while (enumerator1.MoveNext())
                {
                    ISymbol current1 = enumerator1.Current;
                    switch (current1.Kind)
                    {
                    case SymbolKind.GlobalVariable:
                        instance1.ConcurrentAdd <ISymbol>(current1);
                        continue;

                    case SymbolKind.Method:
                        instance2.ConcurrentAdd <ISymbol>(current1);
                        foreach (IVariableSymbol localVariable in ((IMethodSymbol)current1).LocalVariables)
                        {
                            instance3.ConcurrentAdd <ISymbol>((ISymbol)localVariable);
                        }
                        continue;

                    case SymbolKind.Field:
                        instance4.ConcurrentAdd <ISymbol>(current1);
                        continue;

                    case SymbolKind.Control:
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.AnalyzeControls((IControlSymbol)current1, instance6);
                        continue;

                    case SymbolKind.Action:
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.AnalyzeActions((IActionSymbol)current1, instance5);
                        continue;

                    case SymbolKind.Change:
                        IEnumerable <IControlSymbol> flattenedSymbolsOfKind1 = Rule198GlobalLocalVariablesShouldNotHaveSameName.GetFlattenedSymbolsOfKind <IControlSymbol>((IContainerSymbol)current1, SymbolKind.Control);
                        IEnumerable <IActionSymbol>  flattenedSymbolsOfKind2 = Rule198GlobalLocalVariablesShouldNotHaveSameName.GetFlattenedSymbolsOfKind <IActionSymbol>((IContainerSymbol)current1, SymbolKind.Action);
                        foreach (IControlSymbol controlSymbol in flattenedSymbolsOfKind1)
                        {
                            instance6.ConcurrentAdd <ISymbol>((ISymbol)controlSymbol);
                        }
                        using (IEnumerator <IActionSymbol> enumerator2 = flattenedSymbolsOfKind2.GetEnumerator())
                        {
                            while (enumerator2.MoveNext())
                            {
                                IActionSymbol current2 = enumerator2.Current;
                                instance5.ConcurrentAdd <ISymbol>((ISymbol)current2);
                            }
                            continue;
                        }

                    case SymbolKind.QueryDataItem:
                        foreach (IQueryColumnSymbol flattenedQueryColumn in ((IQueryDataItemSymbol)current1).FlattenedQueryColumns)
                        {
                            if (flattenedQueryColumn.Kind == SymbolKind.QueryColumn)
                            {
                                instance4.ConcurrentAdd <ISymbol>((ISymbol)flattenedQueryColumn);
                            }
                        }
                        continue;

                    case SymbolKind.RequestPage:
                        foreach (IControlSymbol flattenedControl in ((IPageBaseTypeSymbol)current1).FlattenedControls)
                        {
                            Rule198GlobalLocalVariablesShouldNotHaveSameName.AnalyzeControls(flattenedControl, instance4);
                        }
                        foreach (IActionSymbol flattenedAction in ((IPageBaseTypeSymbol)current1).FlattenedActions)
                        {
                            instance5.ConcurrentAdd <ISymbol>((ISymbol)flattenedAction);
                        }
                        continue;

                    case SymbolKind.XmlPortNode:
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.AnalyzeXmlNode((IXmlPortNodeSymbol)current1, instance4);
                        continue;

                    default:
                        continue;
                    }
                }
                ImmutableHashSet <ISymbol> immutableHashSet1 = instance1.ToImmutableHashSet <ISymbol>((IEqualityComparer <ISymbol>)SemanticFacts.SymbolNameEqualityComparer);
                ImmutableHashSet <ISymbol> immutableHashSet2 = instance2.ToImmutableHashSet <ISymbol>((IEqualityComparer <ISymbol>)SemanticFacts.SymbolNameEqualityComparer);
                ImmutableHashSet <ISymbol> immutableHashSet3 = instance3.ToImmutableHashSet <ISymbol>();
                ImmutableHashSet <ISymbol> immutableHashSet4 = instance4.ToImmutableHashSet <ISymbol>((IEqualityComparer <ISymbol>)SemanticFacts.SymbolNameEqualityComparer);
                ImmutableHashSet <ISymbol> immutableHashSet5 = instance5.ToImmutableHashSet <ISymbol>((IEqualityComparer <ISymbol>)SemanticFacts.SymbolNameEqualityComparer);
                ImmutableHashSet <ISymbol> immutableHashSet6 = instance6.ToImmutableHashSet <ISymbol>((IEqualityComparer <ISymbol>)SemanticFacts.SymbolNameEqualityComparer);
                foreach (ISymbol symbol in immutableHashSet3)
                {
                    if (immutableHashSet1.Contains(symbol))
                    {
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.ReportDiagnostic(ctx, DiagnosticDescriptors.Rule022GlobalLocalVariablesShouldNotHaveSameName, symbol);
                    }
                    if (immutableHashSet2.Contains(symbol) || immutableHashSet4.Contains(symbol) || (immutableHashSet5.Contains(symbol) || immutableHashSet6.Contains(symbol)))
                    {
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.ReportDiagnostic(ctx, DiagnosticDescriptors.Rule023DoNotNameLocalVarAsFieldOrMethod, symbol);
                    }
                }
                foreach (ISymbol symbol in immutableHashSet2)
                {
                    if (immutableHashSet4.Contains(symbol) || immutableHashSet5.Contains(symbol) || immutableHashSet6.Contains(symbol))
                    {
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.ReportDiagnostic(ctx, DiagnosticDescriptors.Rule024DoNotNameMethodAsField, symbol);
                    }
                }
                foreach (ISymbol symbol in immutableHashSet1)
                {
                    if (immutableHashSet4.Contains(symbol) || immutableHashSet2.Contains(symbol) || immutableHashSet5.Contains(symbol))
                    {
                        Rule198GlobalLocalVariablesShouldNotHaveSameName.ReportDiagnostic(ctx, DiagnosticDescriptors.Rule025DoNotNameGlobalVarAsFieldOrMethod, symbol);
                    }
                    else
                    {
                        ISymbol actualValue;
                        if (immutableHashSet6.Contains(symbol) && immutableHashSet6.TryGetValue(symbol, out actualValue) && actualValue.Kind != SymbolKind.Control)
                        {
                            Rule198GlobalLocalVariablesShouldNotHaveSameName.ReportDiagnostic(ctx, DiagnosticDescriptors.Rule025DoNotNameGlobalVarAsFieldOrMethod, symbol);
                        }
                    }
                }
            }
            finally
            {
                instance1.Free();
                instance2.Free();
                instance3.Free();
                instance4.Free();
                instance5.Free();
                instance6.Free();
            }
        }
コード例 #9
0
        public void ImmutableSetAdapter_Ctor_Succeeds()
        {
            const int NumberOfMethods = 17;

            int[] methodsCalled            = new int[NumberOfMethods];
            ImmutableHashSet <int> realSet = ImmutableHashSet <int> .Empty;

            System.Collections.Immutable.IImmutableSet <int> backingSet =
                new MockSystemImmutableSet <int>(
                    addDelegate: x => { methodsCalled[0]++; return(realSet.Add(x)); },
                    clearDelegate: () => { methodsCalled[1]++; return(realSet.Clear()); },
                    containsDelegate: x => { methodsCalled[2]++; return(realSet.Contains(x)); },
                    countDelegate: () => { methodsCalled[3]++; return(realSet.Count); },
                    equalsDelegate: null,
                    exceptDelegate: x => { methodsCalled[4]++; return(realSet.Except(x)); },
                    getEnumeratorDelegate: () => { methodsCalled[5]++; return(realSet.GetEnumerator()); },
                    getHashCodeDelegate: null,
                    intersectDelegate: x => { methodsCalled[6]++; return(realSet.Intersect(x)); },
                    isProperSubsetOfDelegate: x => { methodsCalled[7]++; return(realSet.IsProperSubsetOf(x)); },
                    isProperSupersetOfDelegate: x => { methodsCalled[8]++; return(realSet.IsProperSupersetOf(x)); },
                    isSubsetOfDelegate: x => { methodsCalled[9]++; return(realSet.IsSubsetOf(x)); },
                    isSupersetOfDelegate: x => { methodsCalled[10]++; return(realSet.IsSupersetOf(x)); },
                    overlapsDelegate: x => { methodsCalled[11]++; return(realSet.Overlaps(x)); },
                    removeDelegate: x => { methodsCalled[12]++; return(realSet.Remove(x)); },
                    setEqualsDelegate: x => { methodsCalled[13]++; return(realSet.SetEquals(x)); },
                    symmetricExceptDelegate: x => { methodsCalled[14]++; return(realSet.SymmetricExcept(x)); },
                    toStringDelegate: null,
                    tryGetValueDelegate: (int x, out int y) => { methodsCalled[15]++; return(realSet.TryGetValue(x, out y)); },
                    unionDelegate: x => { methodsCalled[16]++; return(realSet.Union(x)); });

#pragma warning disable IDE0028 // Simplify collection initialization. Intentionally calling .Add separately for clarity
            ImmutableSetAdapter <int> set = new ImmutableSetAdapter <int>(backingSet);
#pragma warning restore IDE0028 // Simplify collection initialization.

            set.Add(12);
            set.Clear();
            set.Contains(12);
            _ = set.Count;
            set.Except(Array.Empty <int>());
            set.GetEnumerator();
            set.Intersect(Array.Empty <int>());
            set.IsProperSubsetOf(Array.Empty <int>());
            set.IsProperSupersetOf(Array.Empty <int>());
            set.IsSubsetOf(Array.Empty <int>());
            set.IsSupersetOf(Array.Empty <int>());
            set.Overlaps(Array.Empty <int>());
            set.Remove(12);
            set.SetEquals(Array.Empty <int>());
            set.SymmetricExcept(Array.Empty <int>());
            set.TryGetValue(12, out _);
            set.Union(Array.Empty <int>());

            for (int counter = 0; counter < NumberOfMethods; counter++)
            {
                Assert.AreEqual(1, methodsCalled[counter]);
            }
        }