private static void SetRowRefValue(this SectionData self, UserSession Session, string fieldValue,
                                           string value, CardData reference, Guid sectionId,
                                           string searchFieldName       = "Name", FieldType fieldType = FieldType.Unistring,
                                           ConditionOperation operation = ConditionOperation.Equals)
        {
            if (!String.IsNullOrEmpty(value) && !RegexEngine.IsMatch(value, @"^\s+$"))
            {
                RowData si = SearchItemInReference(Session, reference, sectionId,
                                                   searchFieldName, value, fieldType, operation);
                if (si != null)
                {
                    self.SetRowValue(fieldValue, "Value", si.Id, fieldType: FieldType.RefId);
                    self.SetRowValue(fieldValue, "DisplayValue", si.DisplayString);
                }
                else
                {
                    if (sectionId == DocsVision.Platform.Cards.Constants.RefStaff.Employees.ID)
                    {
                        RowData unit = SearchItemInReference(Session, reference, DocsVision.Platform.Cards.Constants.RefStaff.Units.ID, "Name", "Временные");
                        RowData ne   = unit.ChildSections[DocsVision.Platform.Cards.Constants.RefStaff.Employees.ID].Rows.AddNew();
                        ne.SetString("LastName", value);
                        ne.SetString("DisplayString", value);

                        self.SetRowValue(fieldValue, "Value", ne.Id, fieldType: FieldType.RefId);
                        self.SetRowValue(fieldValue, "DisplayValue", ne.DisplayString);
                    }
                    else
                    {
                        logger.Warn("cardId='{0}'; {2}='{1}' value not found", self.Card.Id, value, fieldValue);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public async Task UnicodeCategoryInclusionsExpected(RegexEngine engine, string set, UnicodeCategory[] categories)
        {
            HashSet <char> categoryInclusions = ComputeIncludedSet(c => Array.IndexOf(categories, char.GetUnicodeCategory(c)) >= 0);

            await ValidateSetAsync(engine, $"[{set}]", RegexOptions.None, categoryInclusions, null);
            await ValidateSetAsync(engine, $"[^{set}]", RegexOptions.None, null, categoryInclusions);
        }
Ejemplo n.º 3
0
 public static async Task <Regex> GetRegexAsync(RegexEngine engine, string pattern, RegexOptions options, Globalization.CultureInfo culture)
 {
     using (new System.Tests.ThreadCultureChange(culture))
     {
         return(await GetRegexAsync(engine, pattern, options));
     }
 }
Ejemplo n.º 4
0
        public async Task SingleExpected(RegexEngine engine, char c)
        {
            string s   = $@"\u{(int)c:X4}";
            var    set = new HashSet <char>()
            {
                c
            };

            // One
            await ValidateSetAsync(engine, $"{s}", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, $"[{s}]", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, $"[^{s}]", RegexOptions.None, null, set);

            if (!RegexHelpers.IsNonBacktracking(engine))
            {
                // Positive lookahead
                await ValidateSetAsync(engine, $"(?={s}){s}", RegexOptions.None, set, null);
                await ValidateSetAsync(engine, $"(?=[^{s}])[^{s}]", RegexOptions.None, null, set);

                // Negative lookahead
                await ValidateSetAsync(engine, $"(?![^{s}]){s}", RegexOptions.None, set, null);
                await ValidateSetAsync(engine, $"(?![{s}])[^{s}]", RegexOptions.None, null, set);
            }

            // Concatenation
            await ValidateSetAsync(engine, $"[{s}{s}]", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, $"[^{s}{s}{s}]", RegexOptions.None, null, set);

            // Alternation
            await ValidateSetAsync(engine, $"{s}|{s}", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, $"[^{s}]|[^{s}]|[^{s}]", RegexOptions.None, null, set);
            await ValidateSetAsync(engine, $"{s}|[^{s}]", RegexOptions.None, null, new HashSet <char>());
        }
Ejemplo n.º 5
0
        public async Task CharactersComparedOneByOne_Invariant(RegexEngine engine, RegexOptions options)
        {
            // Regex compares characters one by one.  If that changes, it could impact the behavior of
            // a case like this, where these characters are not the same, but the strings compare
            // as equal with the invariant culture (and some other cultures as well).
            const string S1 = "\u00D6\u200D";
            const string S2 = "\u004F\u0308";

            // Validate the chosen strings to make sure they compare the way we want to test via Regex
            Assert.False(S1[0] == S2[0]);
            Assert.False(S1[1] == S2[1]);
            Assert.StartsWith(S1, S2, StringComparison.InvariantCulture);
            Assert.True(S1.Equals(S2, StringComparison.InvariantCulture));

            // Test varying lengths of strings to validate codegen changes that kick in at longer lengths
            foreach (int multiple in new[] { 1, 10, 100 })
            {
                string pattern = string.Concat(Enumerable.Repeat(S1, multiple));
                string input   = string.Concat(Enumerable.Repeat(S2, multiple));
                Regex  r;

                // Validate when the string is at the beginning of the pattern, as it impacts prefix matching.
                r = await RegexHelpers.GetRegexAsync(engine, pattern, options);

                Assert.False(r.IsMatch(input));
                Assert.True(r.IsMatch(pattern));

                // Validate when it's not at the beginning of the pattern, as it impacts "multi" matching.
                r = await RegexHelpers.GetRegexAsync(engine, "[abc]" + pattern, options);

                Assert.False(r.IsMatch("a" + input));
                Assert.True(r.IsMatch("a" + pattern));
            }
        }
Ejemplo n.º 6
0
        public async Task Count_ReturnsExpectedCount(RegexEngine engine, string pattern, string input, RegexOptions options, int expectedCount)
        {
            Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options);

            Assert.Equal(expectedCount, r.Count(input));
            Assert.Equal(expectedCount, r.Count(input.AsSpan()));
            Assert.Equal(r.Count(input), r.Matches(input).Count);
            Assert.Equal(r.Count(input.AsSpan()), r.Matches(input).Count);

            if (options == RegexOptions.None && engine == RegexEngine.Interpreter)
            {
                Assert.Equal(expectedCount, Regex.Count(input, pattern));
                Assert.Equal(expectedCount, Regex.Count(input.AsSpan(), pattern));
            }

            switch (engine)
            {
            case RegexEngine.Interpreter:
            case RegexEngine.Compiled:
            case RegexEngine.NonBacktracking:
                RegexOptions engineOptions = RegexHelpers.OptionsFromEngine(engine);
                Assert.Equal(expectedCount, Regex.Count(input, pattern, options | engineOptions));
                Assert.Equal(expectedCount, Regex.Count(input.AsSpan(), pattern, options | engineOptions));
                Assert.Equal(expectedCount, Regex.Count(input, pattern, options | engineOptions, Regex.InfiniteMatchTimeout));
                Assert.Equal(expectedCount, Regex.Count(input.AsSpan(), pattern, options | engineOptions, Regex.InfiniteMatchTimeout));
                break;
            }
        }
Ejemplo n.º 7
0
        public async Task Count_Timeout_ThrowsAfterTooLongExecution(RegexEngine engine)
        {
            if (RegexHelpers.IsNonBacktracking(engine))
            {
                // Test relies on backtracking taking a long time
                return;
            }

            const string Pattern = @"^(\w+\s?)*$";
            const string Input   = "An input string that takes a very very very very very very very very very very very long time!";

            Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.None, TimeSpan.FromMilliseconds(1));

            Stopwatch sw = Stopwatch.StartNew();

            Assert.Throws <RegexMatchTimeoutException>(() => r.Count(Input));
            Assert.Throws <RegexMatchTimeoutException>(() => r.Count(Input.AsSpan()));
            Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout

            switch (engine)
            {
            case RegexEngine.Interpreter:
            case RegexEngine.Compiled:
                sw = Stopwatch.StartNew();
                Assert.Throws <RegexMatchTimeoutException>(() => Regex.Count(Input, Pattern, RegexHelpers.OptionsFromEngine(engine), TimeSpan.FromMilliseconds(1)));
                Assert.Throws <RegexMatchTimeoutException>(() => Regex.Count(Input.AsSpan(), Pattern, RegexHelpers.OptionsFromEngine(engine), TimeSpan.FromMilliseconds(1)));
                Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10);     // arbitrary upper bound that should be well above what's needed with a 1ms timeout
                break;
            }
        }
Ejemplo n.º 8
0
        public async Task Replace(RegexEngine engine, string pattern, string input, string replacement, RegexOptions options, int count, int start, string expected)
        {
            // A few tests exceed the 1000 limit, they reach 6003
            RegexHelpers.SetSafeSizeThreshold(6005);
            Regex r;

            try
            {
                r = await RegexHelpers.GetRegexAsync(engine, pattern, options);
            }
            finally
            {
                RegexHelpers.RestoreSafeSizeThresholdToDefault();
            }

            bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
            bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, count);

            if (isDefaultStart)
            {
                if (isDefaultCount)
                {
                    Assert.Equal(expected, r.Replace(input, replacement));
                    Assert.Equal(expected, Regex.Replace(input, pattern, replacement, options));
                }

                Assert.Equal(expected, r.Replace(input, replacement, count));
            }

            Assert.Equal(expected, r.Replace(input, replacement, count, start));
        }
Ejemplo n.º 9
0
        public static async Task <Regex> GetRegexAsync(RegexEngine engine, string pattern, RegexOptions?options = null, TimeSpan?matchTimeout = null)
        {
            if (options is null)
            {
                Assert.Null(matchTimeout);
            }

            switch (engine)
            {
            case RegexEngine.Interpreter:
                return
                    (options is null ? new Regex(pattern) :
                     matchTimeout is null ? new Regex(pattern, options.Value) :
                     new Regex(pattern, options.Value, matchTimeout.Value));

            case RegexEngine.Compiled:
                return
                    (options is null ? new Regex(pattern, RegexOptions.Compiled) :
                     matchTimeout is null ? new Regex(pattern, options.Value | RegexOptions.Compiled) :
                     new Regex(pattern, options.Value | RegexOptions.Compiled, matchTimeout.Value));

            case RegexEngine.SourceGenerated:
                return(await RegexGeneratorHelper.SourceGenRegexAsync(pattern, options, matchTimeout));
            }

            throw new ArgumentException($"Unknown engine: {engine}");
        }
Ejemplo n.º 10
0
        public async Task Matches(RegexEngine engine, string pattern, string input, RegexOptions options, CaptureData[] expected)
        {
            Regex regexAdvanced = await RegexHelpers.GetRegexAsync(engine, pattern, options);

            VerifyMatches(regexAdvanced.Matches(input), expected);
            VerifyMatches(regexAdvanced.Match(input), expected);
        }
Ejemplo n.º 11
0
        public async Task Match_In_Different_Cultures_CriticalCases(string pattern, RegexEngine engine, CultureInfo culture, string input, string match_expected)
        {
            Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, RegexOptions.None, culture);

            Match match = r.Match(input);

            Assert.Equal(match_expected, match.Value);
        }
Ejemplo n.º 12
0
        public async Task DigitInclusionsExpected(RegexEngine engine)
        {
            HashSet <char> digitInclusions = ComputeIncludedSet(char.IsDigit);

            await ValidateSetAsync(engine, @"[\d]", RegexOptions.None, digitInclusions, null);
            await ValidateSetAsync(engine, @"[^\d]", RegexOptions.None, null, digitInclusions);
            await ValidateSetAsync(engine, @"[\D]", RegexOptions.None, null, digitInclusions);
        }
Ejemplo n.º 13
0
        public async Task WhitespaceInclusionsExpected(RegexEngine engine)
        {
            HashSet <char> whitespaceInclusions = ComputeIncludedSet(char.IsWhiteSpace);

            await ValidateSetAsync(engine, @"[\s]", RegexOptions.None, whitespaceInclusions, null);
            await ValidateSetAsync(engine, @"[^\s]", RegexOptions.None, null, whitespaceInclusions);
            await ValidateSetAsync(engine, @"[\S]", RegexOptions.None, null, whitespaceInclusions);
        }
Ejemplo n.º 14
0
 private void HandleProgressResult(DataReceivedEventArgs received, TimeSpan totalMediaDuration)
 {
     if (RegexEngine.IsProgressData(received.Data, out ConvertProgressEventArgs progressEvent))
     {
         progressEvent.TotalDuration = totalMediaDuration;
         this.OnProgressChanged(progressEvent);
     }
 }
Ejemplo n.º 15
0
        public async Task Test(RegexEngine engine, RegexOptions options, string pattern, string input, string captures, string nonBacktrackingCaptures = null)
        {
            if (input == "NULL")
            {
                input = "";
            }

            bool   nonBacktracking = engine == RegexEngine.NonBacktracking;
            string expected        = nonBacktracking && nonBacktrackingCaptures != null ?
                                     nonBacktrackingCaptures : // nonBacktrackingCaptures value overrides the expected result in NonBacktracking mode
                                     captures;

            if (expected == "BADBR")
            {
                await Assert.ThrowsAnyAsync <ArgumentException>(async() => await RegexHelpers.GetRegexAsync(engine, pattern, options));

                return;
            }

            if (nonBacktracking && nonBacktrackingCaptures == "NONBACKTRACKINGINCOMPATIBLE")
            {
                // In particular: backreferences are not supported in NonBacktracking mode
                await Assert.ThrowsAnyAsync <NotSupportedException>(() => RegexHelpers.GetRegexAsync(engine, pattern, options));

                return;
            }

            Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options);

            if (expected == "NOMATCH")
            {
                Assert.False(r.IsMatch(input));
                return;
            }

            Match match = r.Match(input);

            Assert.True(match.Success);

            var expectedSet = new HashSet <(int start, int end)>(
                expected
                .Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Split(','))
                .Select(s => (start: int.Parse(s[0]), end: int.Parse(s[1]))));

            var actualSet = new HashSet <(int start, int end)>(
                match.Groups
                .Cast <Group>()
                .Select(g => (start: g.Index, end: g.Index + g.Length)));

            // NonBacktracking mode only provides the top-level match.
            // The .NET implementation sometimes has extra captures beyond what the original data specifies, so we assert a subset.
            if (nonBacktracking ? !actualSet.IsSubsetOf(expectedSet) : !expectedSet.IsSubsetOf(actualSet))
            {
                throw new Xunit.Sdk.XunitException($"Actual: {string.Join(", ", actualSet)}{Environment.NewLine}Expected: {string.Join(", ", expected)}");
            }
        }
Ejemplo n.º 16
0
        public async Task TurkishCulture_MatchesWordChar(RegexEngine engine, string input, RegexOptions options, string expectedResult)
        {
            using (new ThreadCultureChange(new CultureInfo("tr-TR")))
            {
                Regex regex = await RegexHelpers.GetRegexAsync(engine, @"\w*", options);

                Assert.Equal(expectedResult, regex.Match(input).Value);
            }
        }
Ejemplo n.º 17
0
 public async Task CharactersLowercasedOneByOne(RegexEngine engine)
 {
     using (new ThreadCultureChange("en-US"))
     {
         Assert.True((await RegexHelpers.GetRegexAsync(engine, "\uD801\uDC00", RegexOptions.IgnoreCase)).IsMatch("\uD801\uDC00"));
         Assert.True((await RegexHelpers.GetRegexAsync(engine, "\uD801\uDC00", RegexOptions.IgnoreCase)).IsMatch("abcdefg\uD801\uDC00"));
         Assert.True((await RegexHelpers.GetRegexAsync(engine, "\uD801", RegexOptions.IgnoreCase)).IsMatch("\uD801\uDC00"));
         Assert.True((await RegexHelpers.GetRegexAsync(engine, "\uDC00", RegexOptions.IgnoreCase)).IsMatch("\uD801\uDC00"));
     }
 }
Ejemplo n.º 18
0
        public async Task DotInclusionsExpected(RegexEngine engine)
        {
            await ValidateSetAsync(engine, ".", RegexOptions.None, null, new HashSet <char>() { '\n' });
            await ValidateSetAsync(engine, ".", RegexOptions.IgnoreCase, null, new HashSet <char>() { '\n' });
            await ValidateSetAsync(engine, ".", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, null, new HashSet <char>() { '\n' }, validateEveryChar : true);

            await ValidateSetAsync(engine, ".", RegexOptions.Singleline, null, new HashSet <char>());
            await ValidateSetAsync(engine, ".", RegexOptions.Singleline | RegexOptions.IgnoreCase, null, new HashSet <char>());
            await ValidateSetAsync(engine, ".", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, null, new HashSet <char>(), validateEveryChar : true);
        }
Ejemplo n.º 19
0
        public void EnumerateMatches_Count(RegexEngine engine, string pattern, string input, int expectedCount)
        {
            Regex r     = RegexHelpers.GetRegexAsync(engine, pattern).GetAwaiter().GetResult();
            int   count = 0;

            foreach (ValueMatch _ in r.EnumerateMatches(input))
            {
                count++;
            }
            Assert.Equal(expectedCount, count);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Loads lexis from stream and builds recognizing automaton
        /// </summary>
        /// <param name="stream">
        ///     <para>Lexis specification stream</para>
        ///     <remarks>See schema at Schemas\LexisSchema.xsd</remarks>
        /// </param>
        /// <param name="deterministic">
        ///     <para>Flag, which specifies automaton type:
        ///     deterministic or non-deterministic.</para>
        ///     <remarks>DFA's building is significantly slower (creates up to 2^n of NFA states),
        ///     but recognizes much faster (O(n) instead of O(n*m), where n - token's length)</remarks>
        /// </param>
        public void LoadLexis(Stream stream, bool deterministic = false)
        {
            var    schemas = new XmlSchemaSet();
            string pwd     = AppDomain.CurrentDomain.BaseDirectory;

            schemas.Add("http://savva.moe/compiler/lexis.xsd", Path.Combine(pwd, "Schemas", "LexisSchema.xsd"));
            var lexis = XmlReader.Create(stream, new XmlReaderSettings
            {
                ValidationType = ValidationType.Schema,
                Schemas        = schemas
            });
            var builder = new RegexEngine();

            while (lexis.Read())
            {
                if (!lexis.IsStartElement())
                {
                    continue;
                }

                string name, regex, precedence, canBeOmitted;
                switch (lexis.Name)
                {
                case "lexis":
                    continue;

                case "token":
                    name         = lexis.GetAttribute("name");
                    regex        = lexis.GetAttribute("expression");
                    precedence   = lexis.GetAttribute("precedence");
                    canBeOmitted = lexis.GetAttribute("omit");
                    break;

                default:
                    throw new XmlException($"Lexis definition cannot contain '{lexis.Name}' element");
                }

                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(regex))
                {
                    throw new XmlException("Token attributes cannot be empty");
                }
                builder.AddExpression(name, regex);

                int prec;
                int.TryParse(precedence, out prec);
                _prec[name] = prec;

                bool omit;
                bool.TryParse(canBeOmitted, out omit);
                _required[name] = !omit;
            }
            _machine = deterministic ? (Automaton <char>)builder.Build().ToDFA() : builder.Build();
            _machine.Initial();
        }
Ejemplo n.º 21
0
        public async Task CharactersComparedOneByOne_AnchoredPattern(RegexEngine engine, string pattern, string input, string culture, RegexOptions options, bool expected)
        {
            // Regex compares characters one by one.  If that changes, it could impact the behavior of
            // a case like this, where these characters are not the same, but the strings compare
            // as equal with the invariant culture (and some other cultures as well).
            using (new ThreadCultureChange(culture))
            {
                Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options);

                Assert.Equal(expected, r.IsMatch(input));
            }
        }
Ejemplo n.º 22
0
        public async Task TurkishCulture_Handling_Of_IgnoreCase(RegexEngine engine)
        {
            var    turkish = new CultureInfo("tr-TR");
            string input   = "I\u0131\u0130i";
            string pattern = "[H-J][\u0131-\u0140][\u0120-\u0130][h-j]";

            Regex regex = await RegexHelpers.GetRegexAsync(engine, pattern, RegexOptions.IgnoreCase, turkish);

            // The pattern must trivially match the input because all of the letters fall in the given intervals
            // Ignoring case can only add more letters here -- not REMOVE letters
            Assert.True(regex.IsMatch(input));
        }
Ejemplo n.º 23
0
        private void assertPattern(string line, TokenizedLine tokens)
        {
            RegexEngine engine        = new RegexEngine();
            var         tokenizedLine = engine.ExtractTokens(line);

            Assert.AreEqual(tokenizedLine.Type, tokens.Type);
            Assert.AreEqual(tokenizedLine.Tokens.Count, tokens.Tokens.Count);
            for (int i = 0; i < tokenizedLine.Tokens.Count; i++)
            {
                Assert.AreEqual(tokens.Tokens[i], tokenizedLine.Tokens[i]);
            }
        }
Ejemplo n.º 24
0
        public async Task NamedBlocksInclusionsExpected(RegexEngine engine, string set, int[] ranges)
        {
            var included = new HashSet <char>();

            for (int i = 0; i < ranges.Length - 1; i += 2)
            {
                ComputeIncludedSet(c => c >= ranges[i] && c <= ranges[i + 1], included);
            }

            await ValidateSetAsync(engine, $"[{set}]", RegexOptions.None, included, null);
            await ValidateSetAsync(engine, $"[^{set}]", RegexOptions.None, null, included);
        }
Ejemplo n.º 25
0
        public static async Task <Regex> GetRegexAsync(RegexEngine engine, [StringSyntax(StringSyntaxAttribute.Regex)] string pattern, RegexOptions options, Globalization.CultureInfo culture)
        {
            if (engine == RegexEngine.SourceGenerated)
            {
                return(await RegexGeneratorHelper.SourceGenRegexAsync(pattern, culture, options));
            }

            using (new System.Tests.ThreadCultureChange(culture))
            {
                return(await GetRegexAsync(engine, pattern, options));
            }
        }
Ejemplo n.º 26
0
        public void EnumerateMatches_ReturnsExpectedCount(RegexEngine engine, string pattern, string input, int startat, RegexOptions options, int expectedCount)
        {
            Regex r = RegexHelpers.GetRegexAsync(engine, pattern, options).GetAwaiter().GetResult();

            int count;

            count = 0;
            foreach (ValueMatch _ in r.EnumerateMatches(input, startat))
            {
                count++;
            }
            Assert.Equal(expectedCount, count);

            bool isDefaultStartAt = startat == ((options & RegexOptions.RightToLeft) != 0 ? input.Length : 0);

            if (!isDefaultStartAt)
            {
                return;
            }

            if (options == RegexOptions.None && engine == RegexEngine.Interpreter)
            {
                count = 0;
                foreach (ValueMatch _ in Regex.EnumerateMatches(input, pattern))
                {
                    count++;
                }
                Assert.Equal(expectedCount, count);
            }

            switch (engine)
            {
            case RegexEngine.Interpreter:
            case RegexEngine.Compiled:
            case RegexEngine.NonBacktracking:
                RegexOptions engineOptions = RegexHelpers.OptionsFromEngine(engine);
                count = 0;
                foreach (ValueMatch _ in Regex.EnumerateMatches(input, pattern, options | engineOptions))
                {
                    count++;
                }
                Assert.Equal(expectedCount, count);

                count = 0;
                foreach (ValueMatch _ in Regex.EnumerateMatches(input, pattern, options | engineOptions, Regex.InfiniteMatchTimeout))
                {
                    count++;
                }
                Assert.Equal(expectedCount, count);
                break;
            }
        }
Ejemplo n.º 27
0
        private void HandleConversionResult(EngineParameters engineParameters, DataReceivedEventArgs received, TimeSpan totalMediaDuration)
        {
            if (engineParameters.Task != FFmpegTask.Convert)
            {
                return;
            }

            if (RegexEngine.IsConvertCompleteData(received.Data, out ConversionCompleteEventArgs convertCompleteEvent))
            {
                convertCompleteEvent.TotalDuration = totalMediaDuration;
                this.OnConversionComplete(convertCompleteEvent);
            }
        }
Ejemplo n.º 28
0
        public async Task AllEmptySets(RegexEngine engine)
        {
            var set = new HashSet <char>();

            await ValidateSetAsync(engine, @"[\u0000-\uFFFF]", RegexOptions.None, null, set);
            await ValidateSetAsync(engine, @"[\u0000-\uFFFFa-z]", RegexOptions.None, null, set);
            await ValidateSetAsync(engine, @"[\u0000-\u1000\u1001-\u2002\u2003-\uFFFF]", RegexOptions.None, null, set);
            await ValidateSetAsync(engine, @"[\u0000-\uFFFE\u0001-\uFFFF]", RegexOptions.None, null, set, validateEveryChar : true);

            await ValidateSetAsync(engine, @"[^\u0000-\uFFFF]", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, @"[^\u0000-\uFFFFa-z]", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, @"[^\u0000-\uFFFE\u0001-\uFFFF]", RegexOptions.None, set, null);
            await ValidateSetAsync(engine, @"[^\u0000-\u1000\u1001-\u2002\u2003-\uFFFF]", RegexOptions.None, set, null, validateEveryChar : true);
        }
Ejemplo n.º 29
0
        public async Task SetInclusionsExpected(RegexEngine engine, string set, RegexOptions options, char[] expectedIncluded)
        {
            bool hasBracket = set.Contains("[");

            if (hasBracket)
            {
                await ValidateSetAsync(engine, set, options, new HashSet <char>(expectedIncluded), null, validateEveryChar : true);
            }
            else
            {
                await ValidateSetAsync(engine, $"[{set}]", options, new HashSet <char>(expectedIncluded), null, validateEveryChar : true);
                await ValidateSetAsync(engine, $"[^{set}]", options, null, new HashSet <char>(expectedIncluded), validateEveryChar : true);
            }
        }
Ejemplo n.º 30
0
        public void EnumerateMatches(RegexEngine engine, string pattern, string input, RegexOptions options, CaptureData[] expected)
        {
            Regex regexAdvanced      = RegexHelpers.GetRegexAsync(engine, pattern, options).GetAwaiter().GetResult();
            int   count              = 0;
            ReadOnlySpan <char> span = input.AsSpan();

            foreach (ValueMatch match in regexAdvanced.EnumerateMatches(span))
            {
                Assert.Equal(expected[count].Index, match.Index);
                Assert.Equal(expected[count].Length, match.Length);
                Assert.Equal(expected[count].Value, span.Slice(match.Index, match.Length).ToString());
                count++;
            }
            Assert.Equal(expected.Length, count);
        }
Ejemplo n.º 31
0
 private static void DumpParseSteps(RegexEngine engine, string pattern)
 {
     Debug.WriteLine(
             "| Index | Step          | Node Type                | {0} | Message",
             "Pattern".PadRight(Math.Max(pattern.Length + 2, 7)));
     Debug.WriteLine(
             "|---------------+--------------------------+-{0}-+---------------------------------------------------",
             "".PadRight(Math.Max(pattern.Length + 2, 7), '-'));
     Debug.WriteLine(engine.GetParseSteps().Aggregate(
         new StringBuilder(),
         (sb, step) => sb.AppendFormat(
             "{0}{1}{2}{3}",
             "| " + step.Type.ToString().PadRight(14),
             "| " + step.NodeType.PadRight(25),
             "| " + step.Pattern.PadRight(Math.Max(pattern.Length + 3, 8)),
             "| " + step.Message).AppendLine()).ToString());
 }