private StringComparisonExpression(ExpressionType operation, Expression left, Expression right, StringComparison?comparison = null)
 {
     Operation  = operation;
     Left       = left;
     Right      = right;
     Comparison = comparison;
 }
 public static void IsEqualTo(this Param <string> param, string expected, StringComparison?comparison = null)
 {
     if (!StringEquals(param.Value, expected, comparison))
     {
         throw ExceptionFactory.CreateForParamValidation(param, ExceptionMessages.Strings_IsEqualTo_Failed.Inject(param.Value, expected));
     }
 }
示例#3
0
        public void TextGetEnumTest()
        {
            StringComparison?cmp = _tcfg.ReadEnumValue <StringComparison>("sect2", "k2");

            Assert.AreEqual(StringComparison.OrdinalIgnoreCase, cmp);
            Assert.AreEqual(355, _tcfg.ReadValue <int>("sect1", "k1"));
        }
示例#4
0
        public FsPath RelativeTo(FsPath other, StringComparison?comparison = null)
        {
            if (string.IsNullOrEmpty(other.Value))
            {
                return(this);
            }


            int len = Value.Length;

            if (len == other.Length)
            {
                return(Value.StartsWith(other.Value, comparison ?? Comparison)
                                        ? Empty
                                        : None);
            }

            int minLen = other.Value.Length + 1;

            if (len < minLen || Value[other.Value.Length] != Separator || !Value.StartsWith(other.Value, comparison ?? Comparison))
            {
                return(None);
            }

            if (len == minLen)
            {
                return(Empty);
            }

            return(new FsPath(Value.Substring(minLen)));
        }
示例#5
0
        public void UsageTest(StringComparison?comparison)
        {
            var dict = comparison == null ? new StringKeyedDictionary <int>() : new StringKeyedDictionary <int>(StringSegmentComparer.FromComparison(comparison.Value));

            dict.Add("alpha", 1);
            dict.Add("beta", 2);
            dict.Add("gamma", 3);
            Assert.AreEqual(3, dict.Count);
            Assert.AreEqual(1, dict["alpha"]);
            Assert.AreEqual(1, dict["alpha".AsSegment()]);
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
            Assert.AreEqual(1, dict["alpha".AsSpan()]);
#endif

            // remove and re-add by string
            Assert.IsTrue(dict.Remove("alpha"));
            Assert.AreEqual(2, dict.Count);
            Assert.IsFalse(dict.Remove("alpha"));
            Assert.IsTrue(dict.Remove("beta"));
            dict.Add("alpha", -1);
            Assert.AreEqual(2, dict.Count);
            Assert.AreEqual(-1, dict["alpha"]);
            Assert.AreEqual(-1, dict["alpha".AsSegment()]);
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
            Assert.AreEqual(-1, dict["alpha".AsSpan()]);
#endif

            // Clear
            dict.Clear();
            Assert.AreEqual(0, dict.Count);
            dict.Add("alpha", 42);
            Assert.AreEqual(42, dict["alpha"]);
        }
示例#6
0
 public record IndexOfTestCase(
     string Text,
     string Search,
     int Expected,
     int?StartIndex = null,
     int?Count      = null,
     StringComparison?StringComparison = null
     );
示例#7
0
 public static IValidationTarget <string> IsEqualTo(this IValidationTarget <string> target,
                                                    string expected,
                                                    StringComparison?comparison = null)
 {
     return(target.And(new DefaultValidationPredicate <string>(v => StringEquals(v, expected, comparison),
                                                               ExceptionMessages.StringsIsEqualToFailed
                                                               .Inject(target.Value, expected))));
 }
示例#8
0
 public static void ValidateSingleString(Comparison comparison, StringComparison? @case)
 {
     ValidateString(comparison, @case);
     if (comparison == Comparison.In)
     {
         throw new($"Cannot perform {comparison} on a single String.");
     }
 }
示例#9
0
        /// <summary>
        /// Saves all modified resource files.
        /// </summary>
        /// <exception cref="IOException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        public void Save(StringComparison?fileContentSorting)
        {
            var changedResourceLanguages = _resourceEntities
                                           .SelectMany(entity => entity.Languages)
                                           .Where(lang => lang.HasChanges)
                                           .ToArray();

            changedResourceLanguages.ForEach(resourceLanguage => resourceLanguage.Save(fileContentSorting));
        }
示例#10
0
        private void Initialize(string osName,
                                StringComparison?textComparison = null,
                                params ICleanupTokens[] cleanupTokens)
        {
            _parser = osName.Equals("windows", StringComparison.OrdinalIgnoreCase)
                          ? Parser.GetWindowsDefault(logger: Logger, cleanupProcessors: cleanupTokens)
                          : Parser.GetLinuxDefault(logger: Logger, cleanupProcessors: cleanupTokens);

            _parser !.Collection.Should().NotBeNull();
        }
        /// <summary>
        /// Nots the equals.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="comparison">The comparison.</param>
        /// <exception cref="UnexpectedElementStateException"></exception>
        public void NotEquals(string value, StringComparison?comparison = null)
        {
            if (!string.Equals(CompareValue, value, comparison ?? DefaultStringComparison))
            {
                return;
            }

            var failureMessage = FailureMessage ?? $"Element compared values do not differ. Provided value: '{CompareValue}' \r\n";

            throw new UnexpectedElementStateException(failureMessage);
        }
        /// <summary>
        /// Determines whether [contains] [the specified value].
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="comparison">The comparison.</param>
        /// <exception cref="UnexpectedElementStateException"></exception>
        public void Contains(string value, StringComparison?comparison = null)
        {
            if (CompareValue == value || CompareValue != null && CompareValue.IndexOf(value, comparison ?? DefaultStringComparison) > -1)
            {
                return;
            }

            var failureMessage = FailureMessage ?? $"Element value does not contain expected substring. Expected value to contain: '{value}', Provided value: '{CompareValue}' \r\n";

            throw new UnexpectedElementStateException(failureMessage);
        }
 public ClassData(
     ClassDeclarationSyntax syntax,
     string? @namespace,
     string?dataType,
     StringComparison?stringComparison,
     long?minValue)
 {
     Syntax           = syntax;
     Namespace        = @namespace;
     DataType         = dataType;
     StringComparison = stringComparison;
     MinValue         = minValue;
 }
        /// <summary>
        /// Returns the <see cref="Enumeration"/> <typeparamref name="T"/> Value by its
        /// <paramref name="displayName"/>. <paramref name="_"/> is provided to connect the
        /// caller with the <see cref="Enumeration"/> <typeparamref name="T"/>. Nothing more,
        /// nothing less.
        /// </summary>
        /// <param name="_"></param>
        /// <param name="displayName"></param>
        /// <param name="comparisonType"></param>
        /// <param name="verify"></param>
        /// <returns></returns>
        /// <see cref="Enumeration.FromDisplayName{T}(string)"/>
        /// <see cref="Enumeration.FromDisplayName{T}(string,StringComparison)"/>
        public static T GetValueByDisplayName <T>(this T _, string displayName
                                                  , StringComparison?comparisonType = null, Action <T> verify = null)
            where T : Enumeration
        {
            var result = comparisonType == null
                ? Enumeration.FromDisplayName <T>(displayName).AssertNotNull()
                : Enumeration.FromDisplayName <T>(displayName, comparisonType.Value);

            var value = result.AssertNotNull().AssertEqual(displayName, x => x.DisplayName);

            verify?.Invoke(value);
            return(value);
        }
示例#15
0
        /// <summary>
        /// Modify the constraint to the specified comparison.
        /// </summary>
        /// <exception cref="InvalidOperationException">Thrown when a comparison type different
        /// than <paramref name="comparisonType"/> was already set.</exception>
        public SubstringConstraint Using(StringComparison comparisonType)
        {
            if (this.comparisonType == null)
            {
                this.comparisonType = comparisonType;
            }
            else if (this.comparisonType != comparisonType)
            {
                throw new InvalidOperationException("A different comparison type was already set.");
            }

            return(this);
        }
示例#16
0
        public static bool PathEquals(this string firstPath, string secondPath, StringComparison?comparison = null)
        {
            if (!comparison.HasValue)
            {
                comparison = DiskProviderBase.PathStringComparison;
            }

            if (firstPath.Equals(secondPath, comparison.Value))
            {
                return(true);
            }
            return(string.Equals(firstPath.CleanFilePath(), secondPath.CleanFilePath(), comparison.Value));
        }
示例#17
0
        /// <summary>
        /// Determines the common length of two strings from start to end until the first difference.
        /// </summary>
        /// <param name="value1">First string</param>
        /// <param name="value2">Second string</param>
        /// <param name="stringComparison">determines the string comparision options</param>
        /// <returns>The number of characters common from the start</returns>
        public static int CountStartToDifference(this string value1, string value2, StringComparison?stringComparison = null)
        {
            // Performance analysis: https://neil.fraser.name/news/2007/10/09/
            var n = Math.Min(value1.Length, value2.Length);

            for (var i = 0; i < n; i++)
            {
                if ((stringComparison == null ? (value1[i] != value2[i]) : (!string.Equals(value1[i].ToString(), value2[i].ToString(), (StringComparison)stringComparison))))
                {
                    return(i);
                }
            }
            return(n);
        }
示例#18
0
    public static void ValidateObject(Type propertyType, Comparison comparison, StringComparison? @case)
    {
        if (comparison == Comparison.Contains ||
            comparison == Comparison.StartsWith ||
            comparison == Comparison.EndsWith ||
            comparison == Comparison.Like)
        {
            throw new($"Cannot perform {comparison} on {propertyType.FullName}.");
        }

        if (@case != null)
        {
            throw new($"Cannot use {nameof(StringComparison)} when comparing {propertyType.FullName}.");
        }
    }
示例#19
0
        public WordList(
            IEnumerable <string>?values,
            IEnumerable <WordSequence>?sequences,
            StringComparison?comparison = null)
        {
            Comparer   = StringComparer.FromComparison(comparison ?? DefaultComparison);
            Comparison = comparison ?? DefaultComparison;

            Values = values?.ToImmutableHashSet(Comparer) ?? ImmutableHashSet <string> .Empty;

            Sequences = sequences?
                        .GroupBy(f => f.First, Comparer)
                        .ToImmutableDictionary(f => f.Key, f => f.ToImmutableArray(), Comparer)
                        ?? ImmutableDictionary <string, ImmutableArray <WordSequence> > .Empty;
        }
示例#20
0
    public static void ValidateString(Comparison comparison, StringComparison? @case)
    {
        if (comparison == Comparison.GreaterThan ||
            comparison == Comparison.GreaterThanOrEqual ||
            comparison == Comparison.LessThanOrEqual ||
            comparison == Comparison.LessThan)
        {
            throw new($"Cannot perform {comparison} on a String.");
        }

        if (comparison == Comparison.Like && @case != null)
        {
            throw new($"{nameof(Comparison.Like)} is not compatible with {nameof(StringComparison)}.");
        }
    }
示例#21
0
        /// <summary>
        /// Saves this instance to the resource file.
        /// </summary>
        /// <param name="fileContentSorting">If a string comparison is specified, the file content will be sorted by the key.</param>
        /// <exception cref="IOException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        public void Save(StringComparison?fileContentSorting)
        {
            if (fileContentSorting.HasValue)
            {
                if (SortNodes(fileContentSorting.Value))
                {
                    _file.Changed();

                    UpdateNodes(_file, DuplicateKeyHandling.Rename);

                    Container.OnItemOrderChanged(this);
                }
            }

            _file.Save();
        }
示例#22
0
        public void TestNullConversionsEnum()
        {
            dynamic dynamicYaml = new DynamicYaml(NullTestYaml);

            StringComparison?object1 = dynamicYaml.field1;

            object1.Should().Be(null);

            StringComparison?object2 = dynamicYaml.field2;

            object2.Should().Be(null);

            StringComparison?object3 = dynamicYaml.field3;

            object3.Should().Be(null);
        }
示例#23
0
            internal StringSegmentCultureAwareComparer(CultureInfo culture, bool ignoreCase)
            {
                if (culture == null)
                {
                    Throw.ArgumentNullException(Argument.culture);
                }
                compareInfo = culture.CompareInfo;
                options     = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
#if NET35 || NET40 || NET45
                stringComparer = StringComparer.Create(culture, ignoreCase);
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_0
                // span comparison is not supported with a custom culture even in .NET Core 3 so using StringComparison when possible
                knownComparison = culture.Equals(CultureInfo.InvariantCulture)
                    ? ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture
                    : culture.Equals(CultureInfo.CurrentCulture)
                        ? ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture
                        : default(StringComparison?);
#endif
            }
示例#24
0
 public DeepEqualityComparer(TextWriter loggingTextWriter,
                             ReadOnlyCollection <string> propertiesToIgnore,
                             ReadOnlyCollection <Type> typesToIgnore,
                             StringComparison?stringComparison,
                             bool treatNullAsEmptyString,
                             bool ignoreIndexer,
                             bool logOnlyNotEqualItems,
                             IEnumerable <KeyValuePair <Type, IEqualityComparer> >
                             comparerForSpecificType,
                             IEnumerable <Tuple <Type, object> > nullReplacements)
     : base(loggingTextWriter,
            propertiesToIgnore,
            typesToIgnore,
            stringComparison,
            treatNullAsEmptyString,
            ignoreIndexer,
            logOnlyNotEqualItems,
            comparerForSpecificType,
            nullReplacements)
 {
 }
        public void AccessTest(StringComparison?comparison)
        {
            const int             count = 100_000;
            StringComparer        sc    = null;
            StringSegmentComparer ssc   = null;

            if (comparison != null)
            {
#if NETFRAMEWORK || NETSTANDARD2_0
                sc = comparison.Value switch
                {
                    StringComparison.Ordinal => StringComparer.Ordinal,
                    StringComparison.OrdinalIgnoreCase => StringComparer.OrdinalIgnoreCase,
                    StringComparison.InvariantCulture => StringComparer.InvariantCulture,
                    StringComparison.InvariantCultureIgnoreCase => StringComparer.InvariantCultureIgnoreCase,
                    _ => throw new ArgumentOutOfRangeException(nameof(comparison))
                };
#else
                sc = StringComparer.FromComparison(comparison.Value);
#endif
                ssc = StringSegmentComparer.FromComparison(comparison.Value);
            }

            Dictionary <string, int> dictionary = Enumerable.Range(0, count).ToDictionary(i => i.ToString(CultureInfo.InvariantCulture), sc);
            var strDict = new StringKeyedDictionary <int>(dictionary, ssc);

            new IteratorPerformanceTest <int> {
                TestName = "Indexer access test", Iterations = count
            }
            .AddCase(i => dictionary[i.ToString(CultureInfo.InvariantCulture)], "Dictionary read")
            .AddCase(i => strDict[i.ToString(CultureInfo.InvariantCulture)], "StringKeyedDictionary read (string)")
            .AddCase(i => strDict[i.ToString(CultureInfo.InvariantCulture).AsSegment()], "StringKeyedDictionary read (StringSegment)")
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
            .AddCase(i => strDict[i.ToString(CultureInfo.InvariantCulture).AsSpan()], "StringKeyedDictionary read (ReadOnlySpan<char>)")
#endif
            .DoTest()
            .DumpResults(Console.Out);
        }
    public void SingleCombos(string name, Comparison expression, string value, string expectedName, StringComparison?stringComparison)
    {
        var people = new List <Person>
        {
            new Person
            {
                Name        = "Person 1",
                Age         = 12,
                DateOfBirth = new DateTime(2001, 10, 10, 10, 10, 10, DateTimeKind.Utc)
            },
            new Person
            {
                Name        = "Person 2",
                Age         = 13,
                DateOfBirth = new DateTime(2000, 10, 11, 10, 10, 10, DateTimeKind.Utc)
            },
        };

        var result = people.AsQueryable()
                     .Where(ExpressionBuilder <Person> .BuildSinglePredicate(name, expression, value, stringComparison))
                     .Single();

        Assert.Equal(expectedName, result.Name);
    }
示例#27
0
 public ChoCSVLiteWriter(StringComparison stringComparision = StringComparison.Ordinal)
 {
     _stringComparision = stringComparision;
 }
示例#28
0
 public static bool PathNotEquals(this string firstPath, string secondPath, StringComparison?comparison = null)
 {
     return(!PathEquals(firstPath, secondPath, comparison));
 }
        static Expression <Func <T, bool> > BuildStringIn(string[] array, Property <T> property, StringComparison?comparison, bool not = false)
        {
            MethodCallExpression equalsBody;

            if (comparison == null)
            {
                equalsBody = Expression.Call(null, ReflectionCache.StringEqual, ExpressionCache.StringParam, property.Left);
            }
            else
            {
                equalsBody = Expression.Call(null, ReflectionCache.StringEqualComparison, ExpressionCache.StringParam, property.Left, Expression.Constant(comparison));
            }

            var itemEvaluate = Expression.Lambda <Func <string, bool> >(equalsBody, ExpressionCache.StringParam);
            var anyBody      = Expression.Call(null, ReflectionCache.StringAny, Expression.Constant(array), itemEvaluate);

            return(Expression.Lambda <Func <T, bool> >(not ? Expression.Not(anyBody) : (Expression)anyBody, property.SourceParameter));
        }
        static Expression <Func <T, bool> > BuildStringCompare(Comparison comparison, string value, Property <T> property, StringComparison?stringComparison)
        {
            var body = MakeStringComparison(property.Left, comparison, value, stringComparison);

            return(Expression.Lambda <Func <T, bool> >(body, property.SourceParameter));
        }