Пример #1
0
        /// <summary>
        /// Tries to get the configuration for the specified key.
        /// </summary>
        /// <param name="key">The key to retrieve the configuration for.</param>
        /// <param name="configuration">The retrieved configuration instance.</param>
        /// <returns><c>true</c> if found; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">The key is null.</exception>
        /// <exception cref="ObjectDisposedException">The configuration manager has been disposed of.</exception>
        public bool TryGet(TKey key, out TConfiguration configuration)
        {
            ThrowExceptionWhenDisposed();

            if (Equals(key, null))
            {
                throw new ArgumentNullException(nameof(key), "The key cannot be null.");
            }

            bool isFound = false;

            lock (_syncRoot)
            {
                if (_configurations.TryGetValue(key, out configuration))
                {
                    configuration = (TConfiguration)configuration.Clone();
                    isFound       = true;
                }
                else
                {
                    bool isDefault = _keyComparer?.Equals(key, DefaultConfigurationKey) ?? Equals(key, DefaultConfigurationKey);

                    if (isDefault)
                    {
                        configuration = (TConfiguration)AddDefaultConfiguration().Clone();
                        isFound       = true;
                    }
                }
            }

            return(isFound);
        }
Пример #2
0
 static void AssertCompareEqual(IEqualityComparer<NameAndNumber> comparer, NameAndNumber x, NameAndNumber y)
 {
     Assert.IsTrue(comparer.Equals(x, y));
     Assert.IsTrue(comparer.Equals(y, x));
     if (x != null && y != null)
     {
         Assert.AreEqual(comparer.GetHashCode(x), comparer.GetHashCode(y));
     }
 }
Пример #3
0
        private static void Equal(JTokenAndSource expected, JTokenAndSource actual, IEqualityComparer <JValue> comparer, JsonAssertOptions options)
        {
            var expectedToken = expected?.JToken;
            var actualToken   = actual?.JToken;

            if (expectedToken?.Type != actualToken?.Type)
            {
                var message = CreateMessage(expected, actual);
                throw new AssertException(message);
            }

            CheckElementOrder(expected, actual, options);
            if (expected?.JProperty?.Name != actual?.JProperty?.Name)
            {
                var message = CreateMessage(expected, actual);
                throw new AssertException(message);
            }

            var expectedValue = expectedToken as JValue;
            var actualValue   = actualToken as JValue;

            if (expectedValue != null || actualValue != null)
            {
                if (expectedValue == null || actualValue == null)
                {
                    var message = CreateMessage(expected, actual);
                    throw new AssertException(message);
                }

                if (actualValue.HasValues)
                {
                    var message = CreateMessage(expected, actual);
                    throw new AssertException(message);
                }

                var valueComparer = JValueComparer.GetFor(options);
                if (valueComparer.Equals(expectedValue, actualValue))
                {
                    return;
                }

                if (comparer?.Equals(expectedValue, actualValue) == true)
                {
                    return;
                }
                else
                {
                    var message = CreateMessage(expected, actual);
                    throw new AssertException(message);
                }
            }

            for (int i = 0; i < Math.Max(expected?.Children.Count ?? 0, actual?.Children.Count ?? 0); i++)
            {
                var expectedChild = expected?.Children.ElementAtOrDefault(i);
                var actualChild   = actual?.Children.ElementAtOrDefault(i);
                Equal(expectedChild, actualChild, comparer, options);
            }
        }
        public static AndConstraint<ObjectAssertions> NotBeUsing(this ObjectAssertions assertions, object unexpected, IEqualityComparer comparer, string because = "", params object[] reasonArgs)
        {
            Execute.Assertion
                .BecauseOf(because, reasonArgs)
                .ForCondition(!comparer.Equals(assertions.Subject, unexpected))
                .FailWith("Did not expect {context:object} to be equal to {0}{reason}.", unexpected);

            return new AndConstraint<ObjectAssertions>(assertions);
        }
        // static methods
        public static AndConstraint<ObjectAssertions> BeUsing(this ObjectAssertions assertions, object expected, IEqualityComparer comparer, string because = "", params object[] reasonArgs)
        {
            Execute.Assertion
                .BecauseOf(because, reasonArgs)
                .ForCondition(comparer.Equals(assertions.Subject, expected))
                .FailWith("Expected {context:object} to be {0}{reason}, but found {1}.", expected,
                    assertions.Subject);

            return new AndConstraint<ObjectAssertions>(assertions);
        }
Пример #6
0
        private static void Equal(
            XElementAndSource expected,
            XElementAndSource actual,
            IEqualityComparer <XElement> customElementComparer,
            IEqualityComparer <XAttribute> customAttributeComparer,
            XmlAssertOptions options)
        {
            CheckAttributes(expected, actual, customAttributeComparer, options);

            if ((expected?.AllElements.Count ?? 0) == 0 && (actual?.AllElements.Count ?? 0) == 0)
            {
                if (XElementComparer.GetFor(options).Equals(expected?.Element, actual?.Element))
                {
                    return;
                }

                if (customElementComparer?.Equals(expected?.Element, actual?.Element) == true)
                {
                    return;
                }

                var message = CreateMessage(expected, actual);
                throw new AssertException(message);
            }

            var nameComparer = XNameComparer.GetFor(options);

            if (!nameComparer.Equals(expected?.Element.Name, actual?.Element.Name))
            {
                var message = CreateMessage(expected, actual);
                throw new AssertException(message);
            }

            if (!options.IsSet(XmlAssertOptions.IgnoreElementOrder))
            {
                var expectedElements = expected?.AllElements;
                var actualElements   = actual?.AllElements;
                CheckOrder(expectedElements,
                           actualElements,
                           x => x.Element.Name,
                           "  The order of elements is incorrect.",
                           options);
            }

            var expectedElementsToCheck = expected?.ElementsToCheck;
            var actualElementsToCheck   = actual?.ElementsToCheck;

            for (int i = 0; i < Math.Max(expectedElementsToCheck?.Count ?? 0, actualElementsToCheck?.Count ?? 0); i++)
            {
                var expectedChild = expectedElementsToCheck.ElementAtOrDefault(i);
                var actualChild   = actualElementsToCheck.ElementAtOrDefault(i);
                Equal(expectedChild, actualChild, customElementComparer, customAttributeComparer, options);
            }
        }
Пример #7
0
 public bool Equals(Result <TValue, TError> other)
 {
     if (IsOk && other.IsOk)
     {
         return(_valueComparer.Equals(_value, other._value));
     }
     if (IsError && other.IsError)
     {
         return(_errorComparer?.Equals(_error, other._error) ?? false);
     }
     return(false);
 }
Пример #8
0
 internal bool Equals(ScopeValue scopeValue, IEqualityComparer <object> comparer)
 {
     if ((object)scopeValue == null)
     {
         return(false);
     }
     if (ScopeType != scopeValue.ScopeType)
     {
         return(false);
     }
     return(comparer?.Equals(base.Value, scopeValue.Value) ?? ObjectSerializer.Equals(base.Value, scopeValue.Value, base.TypeCode, scopeValue.TypeCode));
 }
Пример #9
0
        protected override bool IsValid(ValidationContext <TObject, TProp> context)
        {
            var paramValue = context.GetParamValue(_valueToCompare);

            var isEquals = _comparer?.Equals(context.PropertyValue, paramValue) ?? Equals(context.PropertyValue, paramValue);

            if (isEquals == true)
            {
                context.RegisterMessageArgument("ValueToCompare", _valueToCompare, paramValue);
            }

            return(isEquals == false);
        }
Пример #10
0
 public static void AddOrReplaceListener(ILoggerListener listener, IEqualityComparer<ILoggerListener> equalityComparer)
 {
     if (listener == null) throw new ArgumentNullException(nameof(listener));
     if (equalityComparer == null) throw new ArgumentNullException(nameof(equalityComparer));
     var currentListeners = _listeners;
     var old = currentListeners.Find(s => equalityComparer.Equals(s, listener));
     if (old == null)
     {
         _listeners = currentListeners.Add(listener);
     }
     else
     {
         _listeners = currentListeners.Replace(old, listener);
     }
 }
Пример #11
0
        private static bool Equals(IEnumerable<KeyValuePair<string, string>> leftKeyValuePairs,
      IEnumerable<KeyValuePair<string, string>> rightKeyValuePairs,
      IEqualityComparer<string> equalityComparer,
      params string[] keysToExclude)
        {
            Dictionary<string, string> leftDictionary = leftKeyValuePairs.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
              Dictionary<string, string> rightDictionary = rightKeyValuePairs.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
              if (leftDictionary.Count != rightDictionary.Count) return false;

              keysToExclude = keysToExclude ?? new string[0];
              foreach (var keyValuePair in leftDictionary.Where(kvp => !keysToExclude.Contains(kvp.Key))) {
            string value;
            if (!rightDictionary.TryGetValue(keyValuePair.Key, out value)) return false;
            if (!equalityComparer.Equals(keyValuePair.Value, value)) return false;
              }
              return true;
        }
Пример #12
0
        /// <summary>
        ///		Checks if the elements are equal to the elements at the end of the array
        /// </summary>
        /// <param name="elements"></param>
        /// <returns></returns>
        public virtual bool EndsWith(T[] elements, IEqualityComparer <T> comparer = null)
        {
            if (elements.Length > Buffer.Length)
            {
                throw new IndexOutOfRangeException("The number of elements exceeds the size of the array");
            }
            for (int i = 0; i < elements.Length; i++)
            {
                var objA = elements[elements.Length - (i + 1)];
                var objB = this[Buffer.Length - (i + 1)];
                if (!comparer?.Equals(objA, objB) ?? !Equals(objA, objB))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #13
0
        private static void CheckAttributes(
            XElementAndSource expectedElement,
            XElementAndSource actualElement,
            IEqualityComparer <XAttribute> customAttributeComparer,
            XmlAssertOptions options)
        {
            if (!options.IsSet(XmlAssertOptions.IgnoreAttributeOrder))
            {
                var expectedAttributes = expectedElement?.AllAttributes;
                var actualAttributes   = actualElement?.AllAttributes;
                CheckOrder(expectedAttributes,
                           actualAttributes,
                           x => x.Attribute.Name,
                           "  The order of attributes is incorrect.",
                           options);
            }

            var expectedAttributesToCheck = expectedElement?.AttributesToCheck;
            var actualAttributesToCheck   = actualElement?.AttributesToCheck;

            var defaultAttributeComparer = XAttributeComparer.GetFor(options);

            for (int i = 0; i < Math.Max(expectedAttributesToCheck?.Count ?? 0, actualAttributesToCheck?.Count ?? 0); i++)
            {
                var expectedAttribute = expectedAttributesToCheck.ElementAtOrDefault(i);
                var actualAttribute   = actualAttributesToCheck.ElementAtOrDefault(i);

                if (defaultAttributeComparer.Equals(expectedAttribute?.Attribute, actualAttribute?.Attribute))
                {
                    continue;
                }

                if (customAttributeComparer?.Equals(expectedAttribute?.Attribute, actualAttribute?.Attribute) == true)
                {
                    continue;
                }

                var message = expectedAttribute == null || actualAttribute == null
                    ? CreateMessage(expectedElement, actualElement)
                    : CreateMessage(expectedAttribute, actualAttribute);

                throw new AssertException(message);
            }
        }
Пример #14
0
        public static bool ParseText(this IParsingContextStream source, IEnumerable <char> text, IEqualityComparer <char> charComparer = null, bool accept = false)
        {
            foreach (var ch in text)
            {
                if (!source.MoveNext())
                {
                    return(false);
                }

                var cur = source.Current;

                if (!(charComparer?.Equals(ch, cur) ?? ch == cur))
                {
                    return(false);
                }
            }

            if (accept)
            {
                source.Accept();
            }

            return(true);
        }
Пример #15
0
            bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
                object obj;
                if (!TryGetObject(out obj)) {
                    obj = null;
                }

                weakcallableproxy wrp = other as weakcallableproxy;
                if (wrp != null) {
                    object otherObj;
                    if (!TryGetObject(out otherObj)) {
                        otherObj = null;
                    }

                    return comparer.Equals(obj, otherObj);
                }

                return comparer.Equals(obj, other);
            }
Пример #16
0
        public static int IndexOf( this IEnumerable sequence, object item, IEqualityComparer comparer )
        {
            Arg.NotNull( sequence, nameof( sequence ) );
            Arg.NotNull( comparer, nameof( comparer ) );
            Contract.Ensures( Contract.Result<int>() >= -1 );

            var enumerator = sequence.GetEnumerator();
            var index = 0;

            try
            {
                while ( enumerator.MoveNext() )
                {
                    var current = enumerator.Current;

                    if ( comparer.Equals( current, item ) )
                        return index;

                    index++;
                }
            }
            finally
            {
                var disposable = enumerator as IDisposable;

                if ( disposable != null )
                    disposable.Dispose();
            }

            return -1;
        }
 /// <summary>
 /// Returns the <see cref="NodeDifference"/> between the original node and
 /// the new node.
 /// </summary>
 /// <param name="originalNode">The original node.</param>
 /// <param name="newNode">The new node.</param>
 /// <param name="dimensionComparator">The dimension comparator.</param>
 private static NodeDifference Diff(ProductPartitionNode originalNode,
 ProductPartitionNode newNode, IEqualityComparer<ProductDimension> dimensionComparator)
 {
     NodeDifference nodeDifference;
       if (originalNode == null && newNode == null) {
     nodeDifference = NodeDifference.NONE;
       } else if (originalNode == null) {
     nodeDifference = NodeDifference.NEW_NODE;
       } else if (newNode == null) {
     nodeDifference = NodeDifference.REMOVED_NODE;
       } else if (!dimensionComparator.Equals(originalNode.Dimension, newNode.Dimension)) {
     throw new InvalidOperationException(string.Format(
     ShoppingMessages.ProductDimensionMismatch, originalNode.Dimension, newNode.Dimension));
       } else if (originalNode.IsUnit != newNode.IsUnit) {
     nodeDifference = NodeDifference.PARTITION_TYPE_CHANGE;
       } else if (originalNode.IsExcludedUnit != newNode.IsExcludedUnit) {
     nodeDifference = NodeDifference.EXCLUDED_UNIT_CHANGE;
       } else if (!originalNode.IsExcludedUnit && originalNode.IsUnit && newNode.IsUnit) {
     // Both nodes are non-excluded units - the only possible difference
     // left is the bid.
     nodeDifference = (originalNode.CpcBid != newNode.CpcBid) ? NodeDifference.BID_CHANGE :
     NodeDifference.NONE;
       } else {
     nodeDifference = NodeDifference.NONE;
       }
       return nodeDifference;
 }
Пример #18
0
 private static bool MatchesName(INamespaceOrTypeSymbol typeOrNamespace, NameAndArity nameAndArity, IEqualityComparer<string> comparer)
 {
     return typeOrNamespace.TypeSwitch(
         (INamespaceSymbol namespaceSymbol) =>
             comparer.Equals(namespaceSymbol.Name, nameAndArity.Name) && nameAndArity.Arity == 0,
         (INamedTypeSymbol typeSymbol) =>
             comparer.Equals(typeSymbol.Name, nameAndArity.Name) &&
             (nameAndArity.Arity == 0 || nameAndArity.Arity == typeSymbol.TypeArguments.Length));
 }
        public bool Equals(object obj, IEqualityComparer equalityComparer)
        {
            if (!(obj is Customer)) return false;

            return equalityComparer.Equals(this, obj);
        }
Пример #20
0
 protected bool Compare(T comparisonValue, T propertyValue) =>
 _comparer?.Equals(comparisonValue, propertyValue) ?? Equals(comparisonValue, propertyValue);
Пример #21
0
 public override bool Equals(object obj)
 {
     return(_comparer.Equals(_key, ((ComparableKey)obj)._key));
 }
 public bool AppliesTo(EquatableExpression expression)
 {
     return(AppliesToComparer.Equals(this, expression));
 }
Пример #23
0
 /// <inheritdoc/>
 public new bool Equals(object x, object y)
 {
     return(innerComparer.Equals((T)x, (T)y));
 }
Пример #24
0
            /// <summary>
            /// Return all the spans that appear in only one of "latestSpans" or "previousSpans".
            /// </summary>
            private static DiffResult Difference <T>(IEnumerable <ITagSpan <T> > latestSpans, IEnumerable <ITagSpan <T> > previousSpans, IEqualityComparer <T> comparer)
                where T : ITag
            {
                using (var addedPool = SharedPools.Default <List <SnapshotSpan> >().GetPooledObject())
                    using (var removedPool = SharedPools.Default <List <SnapshotSpan> >().GetPooledObject())
                        using (var latestEnumerator = latestSpans.GetEnumerator())
                            using (var previousEnumerator = previousSpans.GetEnumerator())
                            {
                                var added   = addedPool.Object;
                                var removed = removedPool.Object;

                                var latest   = NextOrDefault(latestEnumerator);
                                var previous = NextOrDefault(previousEnumerator);

                                while (latest != null && previous != null)
                                {
                                    var latestSpan   = latest.Span;
                                    var previousSpan = previous.Span;

                                    if (latestSpan.Start < previousSpan.Start)
                                    {
                                        added.Add(latestSpan);
                                        latest = NextOrDefault(latestEnumerator);
                                    }
                                    else if (previousSpan.Start < latestSpan.Start)
                                    {
                                        removed.Add(previousSpan);
                                        previous = NextOrDefault(previousEnumerator);
                                    }
                                    else
                                    {
                                        // If the starts are the same, but the ends are different, report the larger
                                        // region to be conservative.
                                        if (previousSpan.End > latestSpan.End)
                                        {
                                            removed.Add(previousSpan);
                                            latest = NextOrDefault(latestEnumerator);
                                        }
                                        else if (latestSpan.End > previousSpan.End)
                                        {
                                            added.Add(latestSpan);
                                            previous = NextOrDefault(previousEnumerator);
                                        }
                                        else
                                        {
                                            if (!comparer.Equals(latest.Tag, previous.Tag))
                                            {
                                                added.Add(latestSpan);
                                            }

                                            latest   = NextOrDefault(latestEnumerator);
                                            previous = NextOrDefault(previousEnumerator);
                                        }
                                    }
                                }

                                while (latest != null)
                                {
                                    added.Add(latest.Span);
                                    latest = NextOrDefault(latestEnumerator);
                                }

                                while (previous != null)
                                {
                                    removed.Add(previous.Span);
                                    previous = NextOrDefault(previousEnumerator);
                                }

                                return(new DiffResult(added, removed));
                            }
            }
Пример #25
0
//#if NET40
            //[SuppressMessage("Usage", "CA1801:Nicht verwendete Parameter überprüfen", Justification = "<Ausstehend>")]
//#endif
            public ColumnAliasesLookup(CsvRecord record, ReadOnlyCollection <string> aliases, int wildcardTimeout)
            {
                this.CsvRecordIdentifier = record.Identifier;

                IEqualityComparer <string>? comparer    = record.Comparer;
                ReadOnlyCollection <string>?columnNames = record.ColumnNames;

                //this.Aliases = aliases.Intersect(record.Keys, comparer).Distinct(comparer).ToList();


                for (int i = 0; i < aliases.Count; i++)
                {
                    string alias = aliases[i];

                    if (alias is null)
                    {
                        continue;
                    }

                    if (HasWildcard(alias))
                    {
#if NET40
                        Regex regex = InitRegex(comparer, alias);
#else
                        Regex regex = InitRegex(comparer, alias, wildcardTimeout);
#endif

                        for (int k = 0; k < columnNames.Count; k++) // Die Wildcard könnte auf alle keys passen.
                        {
                            string columnName = columnNames[k];

                            try
                            {
                                if (regex.IsMatch(columnName))
                                {
                                    this.ColumnName = columnName;
                                    return;
                                }
                            }
                            catch (TimeoutException)
                            {
#if !NET40
                                Debug.WriteLine(nameof(RegexMatchTimeoutException));
#endif
                            }
                        }
                    }
                    else
                    {
                        for (int j = 0; j < columnNames.Count; j++)
                        {
                            string columnName = columnNames[j];

                            if (comparer.Equals(columnName, alias)) // Es kann in columnNames keine 2 Strings geben, auf die das zutrifft.
                            {
                                this.ColumnName = columnName;
                                return;
                            }
                        }
                    }
                }
Пример #26
0
 public bool Equals(TKey x, TKey y) => _comparer.Equals(x, y);
    private static OperationalEnumerable<bool> AsOperationalInternal(
      IEnumerable<bool> source,
      Func<IEnumerable<bool>, IEnumerable<bool>, Func<bool, bool, bool>, IEnumerable<bool>> binaryOperation = null,
      Func<IEnumerable<bool>, IEnumerable<bool>, Func<bool, bool, bool>, IEnumerable<bool>> comparisonOperation = null,
      IComparer<bool> comparer = null,
      IEqualityComparer<bool> equalityComparer = null)
    {
      Contract.Requires(source != null);
      Contract.Ensures(!object.Equals(Contract.Result<OperationalEnumerable<bool>>(), null));

      return source.AsOperational(
        binaryOperation: binaryOperation,
        comparisonOperation: comparisonOperation,
        add: null,
        subtract: null,
        multiply: null,
        divide: null,
        remainder: null,
        leftShift: null,
        rightShift: null,
        positive: null,
        negative: null,
        complement: null,
        not: value => !value,
        equals: (first, second) => equalityComparer == null ? first == second : equalityComparer.Equals(first, second),
        notEquals: (first, second) => equalityComparer == null ? first != second : !equalityComparer.Equals(first, second),
        lessThan: (first, second) => (comparer ?? Comparer<bool>.Default).Compare(first, second) < 0,
        lessThanOrEqual: (first, second) => (comparer ?? Comparer<bool>.Default).Compare(first, second) <= 0,
        greaterThan: (first, second) => (comparer ?? Comparer<bool>.Default).Compare(first, second) > 0,
        greaterThanOrEqual: (first, second) => (comparer ?? Comparer<bool>.Default).Compare(first, second) >= 0,
        and: (first, second) => first & second,
        or: (first, second) => first | second,
        xor: (first, second) => first ^ second);
    }
Пример #28
0
 private static bool Contains(QueryToken token, ArrayList<string> text, IEqualityComparer<string> tokenComparer)
 {
     for (int i = 0; i < text.Count - (token.Parts.Length - 1); i++)
     {
         bool success = true;
         for (int j = 0; j < token.Parts.Length; j++)
         {
             string textWord = text[i + j];
             string queryWord = token.Parts[j];
             if (!tokenComparer.Equals(queryWord, textWord)) { success = false; break; }
         }
         if (success) { return true; }
     }
     return false;
 }
Пример #29
0
 public static bool Equals(T left, T right)
 {
     return(s_instance.Equals(left, right));
 }
Пример #30
0
 public bool Equals(ParseResult <T> x, ParseResult <T> y)
 {
     if (x is ParseSuccess <T> )
     {
         ParseSuccess <T> xs = (ParseSuccess <T>)x;
         if (y is ParseSuccess <T> )
         {
             ParseSuccess <T> ys = (ParseSuccess <T>)y;
             return(xs.Position == ys.Position && xs.Length == ys.Length && resultComparer.Equals(xs.Value, ys.Value));
         }
         else
         {
             return(false);
         }
     }
     else
     {
         ParseFailure <T> xf = (ParseFailure <T>)x;
         if (y is ParseSuccess <T> )
         {
             return(false);
         }
         else
         {
             ParseFailure <T> yf = (ParseFailure <T>)y;
             return(xf.Errors.Count == yf.Errors.Count && Enumerable.Range(0, xf.Errors.Count).All(i => xf.Errors[i] == yf.Errors[i]));
         }
     }
 }
Пример #31
0
 private static bool KeyValueExists <TKey, TValue>(
     TKey key, TValue value, IReadOnlyDictionary <TKey, TValue> dictionary, IEqualityComparer <TValue> comparer)
 => dictionary.TryGetValue(key, out var rightVal) && comparer.Equals(value, rightVal);
Пример #32
0
 private bool KeysEqual(TKey value1, TKey value2) => comparer?.Equals(value1, value2) ?? value1.Equals(value2);
Пример #33
0
 public bool Equals(NuGetFramework other)
 {
     return(Comparer.Equals(this, other));
 }
Пример #34
0
        public static bool ContainsKeyWithValue <TKey, TValue>(this Dictionary <TKey, TValue> dictionary, TKey key, TValue requestedValue, IEqualityComparer <TValue> equalityComparer = null)
        {
            var keyValue = default(TValue);

            return(dictionary.TryGetValue(key, out keyValue) && (equalityComparer?.Equals(requestedValue, keyValue) ?? Equals(requestedValue, keyValue)));
        }
Пример #35
0
 public MatchResult TryMatch(string s, IEqualityComparer<string> comparer)
 {
     if (s == null)
     {
         throw new ArgumentNullException(nameof(s));
     }
     if (disposed)
     {
         throw new ObjectDisposedException(GetType().FullName);
     }
     if (s.Length == 0)
     {
         return MatchResult.FromMatch(string.Empty, s);
     }
     var buffer = new char[s.Length];
     var len = textSource.ReadBlock(buffer, 0, buffer.Length);
     var next = new string(buffer, 0, len);
     if (len == 0)
     {
         endOfInput = true;
         return MatchResult.FromEndOfInput(s);
     }
     if (!comparer.Equals(s, next))
     {
         textSource.Unread(buffer, 0, len);
         return MatchResult.FromMismatch(next, s);
     }
     Interlocked.Add(ref offset, len);
     return MatchResult.FromMatch(next, s);
 }
 private static bool MatchesName(INamespaceOrTypeSymbol typeOrNamespace, NameAndArity nameAndArity, IEqualityComparer<string> comparer)
 {
     switch (typeOrNamespace)
     {
         case INamespaceSymbol namespaceSymbol:
             return comparer.Equals(namespaceSymbol.Name, nameAndArity.Name) && nameAndArity.Arity == 0;
         case INamedTypeSymbol typeSymbol:
             return comparer.Equals(typeSymbol.Name, nameAndArity.Name) &&
                 (nameAndArity.Arity == 0 || nameAndArity.Arity == typeSymbol.TypeArguments.Length);
         default:
             return false;
     }
 }
Пример #37
0
            private bool EqualsWorker(deque otherDeque, IEqualityComparer comparer) {
                Assert.NotNull(otherDeque);

                if (otherDeque._itemCnt != _itemCnt) {
                    // number of items is different, deques can't be equal
                    return false;
                } else if (otherDeque._itemCnt == 0) {
                    // two empty deques are equal
                    return true;
                }

                if (CompareUtil.Check(this)) return true;

                CompareUtil.Push(this);
                try {
                    for (int otherIndex = otherDeque._head, ourIndex = _head; ourIndex != _tail; ) {
                        bool result;
                        if (comparer == null) {
                            result = PythonOps.EqualRetBool(_data[ourIndex], otherDeque._data[otherIndex]);
                        } else {
                            result = comparer.Equals(_data[ourIndex], otherDeque._data[otherIndex]);
                        }
                        if (!result) {
                            return false;
                        }

                        // advance both indices
                        otherIndex++;
                        if (otherIndex == otherDeque._data.Length) {
                            otherIndex = 0;
                        }

                        ourIndex++;
                        if (ourIndex == _data.Length) {
                            ourIndex = 0;
                        }
                    }

                    // same # of items, all items are equal
                    return true;
                } finally {
                    CompareUtil.Pop(this);
                }
            }
Пример #38
0
            /// <summary>
            /// Special equals because none of the special cases in Ops.Equals
            /// are applicable here, and the reference equality check breaks some tests.
            /// </summary>
            private static bool RefEquals(object x, object y, IEqualityComparer comparer) {
                CodeContext context;
                if (comparer != null && comparer is PythonContext.PythonEqualityComparer) {
                    context = ((PythonContext.PythonEqualityComparer)comparer).Context.SharedContext;
                } else {
                    context = DefaultContext.Default;
                }

                object ret;
                if (PythonTypeOps.TryInvokeBinaryOperator(context, x, y, "__eq__", out ret) &&
                    ret != NotImplementedType.Value) {
                    return (bool)ret;
                }

                if (PythonTypeOps.TryInvokeBinaryOperator(context, y, x, "__eq__", out ret) &&
                    ret != NotImplementedType.Value) {
                    return (bool)ret;
                }

                if (comparer != null) {
                    return comparer.Equals(x, y);
                }

                return x.Equals(y);
            }
    private static OperationalObservable<short, int> AsOperationalInternal(
      IObservable<short> source,
      Func<IObservable<short>, IObservable<short>, Func<short, short, int>, IObservable<int>> binaryOperation = null,
      Func<IObservable<int>, IObservable<int>, Func<int, int, int>, IObservable<int>> resultBinaryOperation = null,
      Func<IObservable<short>, IObservable<int>, Func<short, int, int>, IObservable<int>> shiftOperation = null,
      Func<IObservable<short>, IObservable<short>, Func<short, short, bool>, IObservable<bool>> comparisonOperation = null,
      IComparer<short> comparer = null,
      IEqualityComparer<short> equalityComparer = null)
    {
      Contract.Requires(source != null);
      Contract.Ensures(!object.Equals(Contract.Result<OperationalObservable<short, int>>(), null));

      return source.AsOperational(
        result => AsOperationalInternal(result, resultBinaryOperation),
        binaryOperation: binaryOperation,
        comparisonOperation: comparisonOperation,
        shiftOperation: shiftOperation,
        add: (first, second) => first + second,
        subtract: (first, second) => first - second,
        multiply: (first, second) => first * second,
        divide: (first, second) => first / second,
        remainder: (first, second) => first % second,
        leftShift: (first, second) => first << second,
        rightShift: (first, second) => first >> second,
        positive: value => +value,
        negative: value => -value,
        complement: value => ~value,
        not: null,
        equals: (first, second) => equalityComparer == null ? first == second : equalityComparer.Equals(first, second),
        notEquals: (first, second) => equalityComparer == null ? first != second : !equalityComparer.Equals(first, second),
        lessThan: (first, second) => comparer == null ? first < second : comparer.Compare(first, second) < 0,
        lessThanOrEqual: (first, second) => comparer == null ? first <= second : comparer.Compare(first, second) <= 0,
        greaterThan: (first, second) => comparer == null ? first > second : comparer.Compare(first, second) > 0,
        greaterThanOrEqual: (first, second) => comparer == null ? first >= second : comparer.Compare(first, second) >= 0,
        and: (first, second) => first & second,
        or: (first, second) => first | second,
        xor: (first, second) => first ^ second);
    }
Пример #40
0
        public static int IndexOf(IEnumerable collection, object element, IEqualityComparer comparer = null)
        {
            int i = 0;
            comparer = comparer ?? EqualityComparer<object>.Default;
            foreach (var currentElement in collection) {
                if (comparer.Equals (currentElement, element)) {
                    return i;
                }

                i++;
            }

            return -1;
        }
    private static OperationalObservable<string> AsOperationalInternal(
      IObservable<string> source,
      Func<IObservable<string>, IObservable<string>, Func<string, string, string>, IObservable<string>> binaryOperation = null,
      Func<IObservable<string>, IObservable<string>, Func<string, string, bool>, IObservable<bool>> comparisonOperation = null,
      IComparer<string> comparer = null,
      IEqualityComparer<string> equalityComparer = null)
    {
      Contract.Requires(source != null);
      Contract.Ensures(!object.Equals(Contract.Result<OperationalObservable<string>>(), null));

      return source.AsOperational(
        binaryOperation: binaryOperation,
        comparisonOperation: comparisonOperation,
        add: (first, second) => first + second,
        subtract: null,
        multiply: null,
        divide: null,
        remainder: null,
        leftShift: null,
        rightShift: null,
        positive: null,
        negative: null,
        complement: null,
        not: null,
        equals: (first, second) => equalityComparer == null ? first == second : equalityComparer.Equals(first, second),
        notEquals: (first, second) => equalityComparer == null ? first != second : !equalityComparer.Equals(first, second),
        lessThan: (first, second) => (comparer ?? StringComparer.Ordinal).Compare(first, second) < 0,
        lessThanOrEqual: (first, second) => (comparer ?? StringComparer.Ordinal).Compare(first, second) <= 0,
        greaterThan: (first, second) => (comparer ?? StringComparer.Ordinal).Compare(first, second) > 0,
        greaterThanOrEqual: (first, second) => (comparer ?? StringComparer.Ordinal).Compare(first, second) >= 0,
        and: null,
        or: null,
        xor: null);
    }
Пример #42
0
            public override Delegate RemoveHandler(object callableObject, IEqualityComparer<object> comparer) {
                List<KeyValuePair<WeakReference, WeakReference>> copyOfHandlers = _handlers.GetCopyForRead();
                for (int i = copyOfHandlers.Count - 1; i >= 0; i--) {
                    object key = copyOfHandlers[i].Key.Target;
                    object value = copyOfHandlers[i].Value.Target;

                    if (key != null && value != null && comparer.Equals(key, callableObject)) {
                        Delegate handler = (Delegate)value;
                        _handlers.RemoveAt(i);
                        return handler;
                    }
                }

                return null;
            }
Пример #43
0
 /// <inheritdoc/>
 public new bool Equals(object x, object y) => _innerComparer.Equals((T)x, (T)y);
Пример #44
0
        /// <summary>
        /// Determines whether two <see cref="ISpecimenBuilderNode" />
        /// instances are define the same graph.
        /// </summary>
        /// <param name="first">
        /// An <see cref="ISpecimenBuilderNode" /> to compare against
        /// <paramref name="second" />.
        /// </param>
        /// <param name="second">
        /// An <see cref="ISpecimenBuilderNode" /> to compare against
        /// <paramref name="first" />.
        /// </param>
        /// <param name="comparer">
        /// The comparer used to compare each node to another node.
        /// </param>
        /// <returns>
        /// <see langword="true" /> if the two
        /// <see cref="ISpecimenBuilderNode" /> define the same graph;
        /// otherwise, <see langword="false" />.
        /// </returns>
        /// <remarks>
        /// <para>
        /// Two <see cref="ISpecimenBuilderNode" /> instances define the same
        /// graph if they themselves are equal to each other, and all their
        /// child nodes recursively are equal to each other. Equality is
        /// defined by <paramref name="comparer" />.
        /// </para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">first</exception>
        /// <exception cref="System.ArgumentNullException">second</exception>
        /// <exception cref="System.ArgumentNullException">comparer</exception>
        /// <seealso cref="GraphEquals(ISpecimenBuilderNode, ISpecimenBuilderNode)"/>
        public static bool GraphEquals(this ISpecimenBuilderNode first, ISpecimenBuilderNode second, IEqualityComparer<ISpecimenBuilder> comparer)
        {
            if (first == null)
                throw new ArgumentNullException(nameof(first));
            if (second == null)
                throw new ArgumentNullException(nameof(second));
            if (comparer == null)
                throw new ArgumentNullException(nameof(comparer));

            if (!comparer.Equals(first, second))
                return false;

            using (IEnumerator<ISpecimenBuilder> e1 = first.GetEnumerator(),
                e2 = second.GetEnumerator())
            {
                while (e1.MoveNext())
                {
                    if (!e2.MoveNext())
                        return false;

                    var n1 = e1.Current as ISpecimenBuilderNode;
                    var n2 = e2.Current as ISpecimenBuilderNode;
                    if (n1 != null && n2 != null)
                    {
                        if (!n1.GraphEquals(n2, comparer))
                            return false;
                    }
                    else
                    {
                        if (n2 != null && n2.Any())
                            return false;
                        if (!comparer.Equals(e1.Current, e2.Current))
                            return false;
                    }
                }
                if (e2.MoveNext())
                    return false;
            }

            return true;
        }
 private void CheckEquality(Expression a, Expression b)
 {
     Assert.AreEqual(equalityComparer.GetHashCode(a), equalityComparer.GetHashCode(b));
     Assert.IsTrue(equalityComparer.Equals(a, b));
 }
    private static OperationalEnumerable<decimal> AsOperationalInternal(
      IEnumerable<decimal> source,
      Func<IEnumerable<decimal>, IEnumerable<decimal>, Func<decimal, decimal, decimal>, IEnumerable<decimal>> binaryOperation = null,
      Func<IEnumerable<decimal>, IEnumerable<decimal>, Func<decimal, decimal, bool>, IEnumerable<bool>> comparisonOperation = null,
      IComparer<decimal> comparer = null,
      IEqualityComparer<decimal> equalityComparer = null)
    {
      Contract.Requires(source != null);
      Contract.Ensures(!object.Equals(Contract.Result<OperationalEnumerable<decimal>>(), null));

      return source.AsOperational(
        binaryOperation: binaryOperation,
        comparisonOperation: comparisonOperation,
        add: (first, second) => first + second,
        subtract: (first, second) => first - second,
        multiply: (first, second) => first * second,
        divide: (first, second) => first / second,
        remainder: (first, second) => first % second,
        leftShift: null,
        rightShift: null,
        positive: value => +value,
        negative: value => -value,
        complement: null,
        not: null,
        equals: (first, second) => equalityComparer == null ? first == second : equalityComparer.Equals(first, second),
        notEquals: (first, second) => equalityComparer == null ? first != second : !equalityComparer.Equals(first, second),
        lessThan: (first, second) => comparer == null ? first < second : comparer.Compare(first, second) < 0,
        lessThanOrEqual: (first, second) => comparer == null ? first <= second : comparer.Compare(first, second) <= 0,
        greaterThan: (first, second) => comparer == null ? first > second : comparer.Compare(first, second) > 0,
        greaterThanOrEqual: (first, second) => comparer == null ? first >= second : comparer.Compare(first, second) >= 0,
        and: null,
        or: null,
        xor: null);
    }
Пример #47
0
 public bool Equals(Pair <T1, T2> other)
 {
     return(other != null &&
            FirstComparer.Equals(this.First, other.First) &&
            SecondComparer.Equals(this.Second, other.Second));
 }
Пример #48
0
 /// <summary>
 ///     Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <returns>
 ///     true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
 /// </returns>
 /// <param name="other">An object to compare with this object.</param>
 public bool Equals(IVirtualRequest other)
 {
     return(StartIndexSizeComparerInstance.Equals(this, other));
 }
 protected bool Compare(T comparisonValue, T propertyValue)
 {
     return(_comparer?.Equals(comparisonValue, propertyValue) ?? Equals(comparisonValue, propertyValue));
 }
 public static IEnumerable <ValidationFailure> WithCustomState(this IEnumerable <ValidationFailure> failures, object expectedCustomState, IEqualityComparer comparer = null)
 {
     return(failures.When(failure => comparer?.Equals(failure.CustomState, expectedCustomState) ?? Equals(failure.CustomState, expectedCustomState), string.Format("Expected custom state of '{0}'. Actual state was '{{State}}'", expectedCustomState)));
 }
Пример #51
0
 /// <summary>
 /// Creates a new <see cref="FuncList{T}"/> with an initial capacity of <paramref name="capacity"/>, using <paramref name="comparer"/> for equality-comparisons among elements, or <see cref="object.Equals(object)"/> is <paramref name="comparer"/> is null.
 /// </summary>
 /// <param name="capacity">The initial capacity of the list.</param>
 /// <param name="comparer">The equality comparer for the list's elements.</param>
 public FuncList(int capacity, IEqualityComparer <T> comparer = null)
 {
     list          = new List <T>(capacity);
     this.comparer = comparer != null ? new ListEqualityComparer <T>((x, y) => comparer.Equals(x, y)) : new ListEqualityComparer <T>((x, y) => x.Equals(y));
 }
Пример #52
0
 /// <summary>
 /// Creates a new <see cref="FuncList{T}"/> from the elements of <paramref name="xs"/>, using <paramref name="comparer"/> for equality-comparisons among elements, or <see cref="object.Equals(object)"/> is <paramref name="comparer"/> is null.
 /// </summary>
 /// <param name="xs">The elements to store in the list.</param>
 /// <param name="comparer">The equality comparer for the list's elements.</param>
 public FuncList(IEqualityComparer <T> comparer, IEnumerable <T> xs = null)
 {
     list          = xs == null ? new List <T>() : new List <T>(xs);
     this.comparer = comparer != null ? new ListEqualityComparer <T>((x, y) => comparer.Equals(x, y)) : new ListEqualityComparer <T>((x, y) => x.Equals(y));
 }
Пример #53
0
        private static string AreEqual(IEqualityComparer iec1, IEqualityComparer iec2)
        {
            string operand;

            if (iec1.Equals(iec1, iec2))
            {
                operand = " == ";
            }
            else
            {
                operand = " != ";
            }

            return operand;
        }