示例#1
0
        static void Main(string[] args)
        {
            var cultureInfo = new CultureInfo("en-US");

            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;

            List <double> listDouble = new List <double>();
            string        str;

            // Input start
            IParsedFile file      = new ParsedFile("SimpleInput.txt");
            IParsedLine firstLine = file.NextLine();

            int _integer = firstLine.NextElement <int>();

            for (int i = 0; i < _integer; ++i)
            {
                listDouble.Add(firstLine.NextElement <double>());
            }

            str = firstLine.NextElement <string>();
            // Input end

            // Data Processing

            // Output start
            StreamWriter writer = new StreamWriter("..\\C#SimpleOutput.txt");

            using (writer)
            {
                writer.WriteLine(_integer + " " + string.Join(null, listDouble));
            }
            // Output end
        }
示例#2
0
        public void ParsingException()
        {
            IParsedFile file = new ParsedFile(_validPath + "Sample_file.txt");

            IParsedLine line = file.NextLine();

            while (!file.Empty)
            {
                line = file.NextLine();
            }

            Assert.Throws <ParsingException>(() => file.NextLine());

            while (!line.Empty)
            {
                line.NextElement <object>();
            }

            Assert.Throws <ParsingException>(() => line.NextElement <object>());

            Queue <string> testQueue = new(new string[] { string.Empty });
            ParsedLine     testLine  = new(testQueue);

            Assert.Throws <ParsingException>(() => testLine.NextElement <char>());
        }
示例#3
0
        public void WriteListString()
        {
            string path = "WriteListString.txt";

            Writer.Clear(path);

            ICollection <string> vectorToWrite = new List <string>()
            {
                "string1", "string2", "string3", "string4"
            };
            string textInFile = string.Empty;
            string separator  = "$";

            Writer.WriteLine <ICollection <string>, string>(path, vectorToWrite, separator);

            IParsedFile file = new ParsedFile(path, separator);

            while (!file.Empty)
            {
                IParsedLine line = file.NextLine();
                while (!line.Empty)
                {
                    textInFile += line.NextElement <string>();
                    if (!line.Empty)
                    {
                        textInFile += "@";
                    }
                }
            }

            List <string> vectorInFile = textInFile.Split('@').ToList();

            Assert.Equal(vectorToWrite, vectorInFile);
        }
示例#4
0
        public void ExtractChar()
        {
            const string fileName = "ExtractChar.txt";
            const string line1    = "+-*/!?#$%&";
            const string line2    = "@()[]{}\"";

            StringBuilder parsedFile = new(string.Empty);

            using (StreamWriter writer = new(fileName))
            {
                writer.WriteLine(Math.PI.ToString());
                writer.WriteLine(line1);
                writer.WriteLine(line2);
            }

            IParsedFile file            = new ParsedFile(fileName);
            IParsedLine firstParsedLine = file.NextLine();
            int         nLines          = Convert.ToInt32(Math.Floor(firstParsedLine.NextElement <double>())) - 1;

            for (int iLine = 0; iLine < nLines; ++iLine)
            {
                IParsedLine parsedLine = file.NextLine();
                while (!parsedLine.Empty)
                {
                    parsedFile.Append(parsedLine.NextElement <char>());
                }

                parsedFile.Append('\\');
                Assert.True(parsedLine.Empty);
            }
            Assert.True(file.Empty);

            Assert.Equal(line1 + '\\' + line2 + '\\', parsedFile.ToString());
        }
示例#5
0
        private ICollection <Event> ParseInput()
        {
            ICollection <Event> events = new List <Event>();

            IParsedFile parsedFile = new ParsedFile(FilePath);

            while (!parsedFile.Empty)
            {
                IParsedLine parsedLine = parsedFile.NextLine();

                string aux = string.Empty;
                while (!parsedLine.Empty)
                {
                    aux += $"{parsedLine.NextElement<string>()} ";
                }
                string line = aux
                              .Trim()
                              .Replace("  ", " ");

                Event evnt = ParseEvent(line);
                evnt.DateTime = ParseDateTime(line);

                events.Add(evnt);
            }

            return(events);
        }
示例#6
0
        public void ElementAt()
        {
            IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt");

            IParsedLine firstLine   = file.NextLine();
            string      lastElement = firstLine.ElementAt <string>(firstLine.Count - 1);

            Assert.Equal("food", lastElement);

            IParsedLine peekedSecondLine = file.PeekNextLine();
            int         number           = peekedSecondLine.ElementAt <int>(1);

            Assert.Equal(100, number);
            const double modifiedNumber = 100 + Math.PI;

            peekedSecondLine.Append($" {modifiedNumber}");

            IParsedLine secondLine  = file.NextLine();
            int         numberAgain = secondLine.ElementAt <int>(1);

            Assert.Equal(number, numberAgain);

            double addedNumber = secondLine.ElementAt <double>(secondLine.Count - 1);

            Assert.Equal(modifiedNumber, addedNumber, 10);
        }
示例#7
0
        private void LoadData()
        {
            ParsedFile _file = new ParsedFile(_inputPath);

            IParsedLine firstLine = _file.NextLine();

            /*long gridRow = */
            firstLine.NextElement <long>();
            /*long gridCol = */
            firstLine.NextElement <long>();

            //Grid = new Grid(gridRow, gridCol);

            long n_vehicles = firstLine.NextElement <long>();

            for (int i = 0; i < n_vehicles; ++i)
            {
                VehicleList.Add(new Vehicle(i));
            }

            long n_rides = firstLine.NextElement <long>();
            long bonus   = firstLine.NextElement <long>();

            TotalSimulationSteps = firstLine.NextElement <long>();

            long rideId = 0;

            while (!_file.Empty)
            {
                IParsedLine line = _file.NextLine();

                long row = line.NextElement <long>();
                long col = line.NextElement <long>();

                long endrow = line.NextElement <long>();
                long endcol = line.NextElement <long>();

                long start = line.NextElement <long>();
                long end   = line.NextElement <long>();

                RideList.Add(new Ride(
                                 rideId,
                                 bonus,
                                 new Position(row, col),
                                 new Position(endrow, endcol),
                                 start,
                                 end,
                                 TotalSimulationSteps));

                ++rideId;
            }

            if (n_rides != RideList.Count)
            {
                throw new ParsingException();
            }
        }
示例#8
0
        public void LineAt()
        {
            IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt");

            IParsedLine lineAt0 = file.LineAt(0);

            int n = lineAt0.PeekNextElement <int>();

            Assert.Equal(23, n);
            int nPlusOne = n + 1;

            lineAt0.Append($" {nPlusOne}");

            file.Append(new ParsedLine(new[] { nPlusOne.ToString() }));
            int totalNumberOfLines = file.Count;

            IParsedLine firstLine    = file.NextLine();
            int         nAgain       = firstLine.NextElement <int>();
            string      str          = firstLine.NextElement <string>();
            int         incrementedN = firstLine.NextElement <int>();

            Assert.Equal(n, nAgain);
            Assert.Equal(nPlusOne, incrementedN);
            Assert.Equal("food", str);

            IParsedLine lastLine = file.LastLine();

            Assert.Equal(incrementedN, lastLine.PeekNextElement <int>());

            for (int lineIndex = 1; lineIndex < totalNumberOfLines - 1; ++lineIndex)
            {
                IParsedLine line    = file.NextLine();
                int         counter = line.NextElement <int>();
                for (int j = 0; j < counter; ++j)
                {
                    line.NextElement <int>();
                }

                while (!line.Empty)
                {
                    line.NextElement <string>();
                }
            }

            IParsedLine extraLine = file.NextLine();

            Assert.Equal(incrementedN, extraLine.NextElement <int>());
            Assert.True(extraLine.Empty);
            Assert.Throws <ArgumentOutOfRangeException>(() => extraLine.ElementAt <string>(1));
            Assert.Throws <InvalidOperationException>(() => extraLine.LastElement <string>());
            Assert.True(file.Empty);
            Assert.Throws <ArgumentOutOfRangeException>(() => file.LineAt(1));
            Assert.Throws <InvalidOperationException>(() => file.LastLine());
        }
示例#9
0
        public void ToSingleStringWithEmptySeparator()
        {
            IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "ToSingleString.txt"));

            IParsedLine firstLine = parsedFile.NextLine();

            Assert.Equal(
                "0This1234isalinewithsomelinesoftext404",
                firstLine.ToSingleString(string.Empty));

            Assert.True(firstLine.Empty);
        }
示例#10
0
        private IEnumerable <Rectangle> ParseInput()
        {
            ICollection <Rectangle> rectangles = new List <Rectangle>();

            IParsedFile parsedFile = new ParsedFile(FilePath);

            while (!parsedFile.Empty)
            {
                IParsedLine parsedLine = parsedFile.NextLine();

                string idString = parsedLine.NextElement <string>();
                if (!idString.StartsWith("#"))
                {
                    throw new Exception($"{idString} is not #n");
                }
                int.TryParse(idString.Trim('#'), out int id);

                if (parsedLine.NextElement <string>() != "@")
                {
                    throw new Exception($"Exception parsing @");
                }

                string[] x0y0 = parsedLine.NextElement <string>()
                                .Trim(':')
                                .Split(',');
                if (x0y0.Length != 2)
                {
                    throw new Exception($"Length of {x0y0} isn't 2");
                }
                int.TryParse(x0y0.First(), out int x0);
                int.TryParse(x0y0.Last(), out int y0);

                string[] xy = parsedLine.NextElement <string>()
                              .Split('x');
                if (xy.Length != 2)
                {
                    throw new Exception($"Length of {xy} isn't 2");
                }
                int.TryParse(xy.First(), out int x);
                int.TryParse(xy.Last(), out int y);

                if (!parsedLine.Empty)
                {
                    throw new Exception($"Error parsing line, missing at least {parsedLine.PeekNextElement<string>()}");
                }

                rectangles.Add(new Rectangle(x: x, y: y, x0: x0, y0: y0)
                {
                    Id = id
                });
            }
            return(rectangles);
        }
示例#11
0
        public void ToSingleStringWithCustomSeparator()
        {
            IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "ToSingleString.txt"));

            parsedFile.NextLine();
            IParsedLine secondLine = parsedFile.NextLine();

            Assert.Equal(
                "Second^~line^~1^~2^~34",
                secondLine.ToSingleString("^~"));

            Assert.True(secondLine.Empty);
        }
示例#12
0
        public void NotSupportedException()
        {
            Assert.Throws <NotSupportedException>(() => new ParsedFile(_validPath + "Sample_file.txt").ToList <uint>());
            Assert.Throws <NotSupportedException>(() => new ParsedFile(_validPath + "Sample_file.txt").ToList <DateTime>());
            var line = new ParsedLine(new Queue <string>(new string[] { "1234" }));

            Assert.Throws <NotSupportedException>(() => line.NextElement <ulong>());

            IParsedFile parsedFile      = new ParsedFile(_validPath + "Sample_file.txt");
            IParsedLine firstParsedLine = parsedFile.NextLine();

            Assert.Throws <NotSupportedException>(() => firstParsedLine.NextElement <char>());
        }
示例#13
0
        private IEnumerable <long> ParseInput()
        {
            IParsedFile parsedFile = new ParsedFile(FilePath);

            while (!parsedFile.Empty)
            {
                IParsedLine parsedLine = parsedFile.NextLine();
                while (!parsedLine.Empty)
                {
                    yield return(parsedLine.NextElement <long>());
                }
            }
        }
示例#14
0
        private IEnumerable <Point> ParseInput()
        {
            IParsedFile parsedFile = new ParsedFile(FilePath);

            while (!parsedFile.Empty)
            {
                IParsedLine parsedLine = parsedFile.NextLine();

                int.TryParse(parsedLine.NextElement <string>().Trim(','), out int x);

                yield return(new Point(x, parsedLine.NextElement <int>()));
            }
        }
示例#15
0
        private static void ValidateFileWithPointsAndCommas(IParsedLine firstLine, IParsedLine secondLine, IParsedLine thirdLine, IParsedLine fourthLine)
        {
            Assert.Equal(1_000_000_000, firstLine.NextElement <double>());
            Assert.True(firstLine.Empty);

            Assert.Equal(1_000_000_000.99, secondLine.NextElement <double>());
            Assert.True(secondLine.Empty);

            Assert.Equal(5_000_111.3, thirdLine.NextElement <double>());
            Assert.True(thirdLine.Empty);

            Assert.Equal(0.99_000_111_88, fourthLine.NextElement <double>());
            Assert.True(fourthLine.Empty);
        }
        private IParsedLine Parse(ReadOnlySpan <byte> bytes, ref long offset, ParseMode parseMode)
        {
            Span <char> chars = stackalloc char[bytes.Length];

            Encoding.UTF8.GetChars(bytes, chars);

            IParsedLine parsedLine = LineParserSpans.ParseLine(chars, offset, parseMode);

            // Add 1 for CR or LF byte.
            offset++;

            offset += bytes.Length;
            return(parsedLine);
        }
示例#17
0
        public void ToSingleStringWithDefaultSeparator()
        {
            IParsedFile parsedFile = new ParsedFile(Path.Combine(_sampleFolderPath, "ToSingleString.txt"));

            IParsedLine firstLine = parsedFile.NextLine();

            Assert.Equal(0, firstLine.NextElement <int>());
            Assert.Equal("This", firstLine.NextElement <string>());

            Assert.Equal(
                "1234 is a line with some lines of text 404",
                firstLine.ToSingleString());

            Assert.True(firstLine.Empty);
        }
示例#18
0
        public void WriteMultipleElements()
        {
            string path = "WriteMultipleElements.txt";

            Writer.Clear(path);

            bool _bool = false;

            Writer.Write(path, _bool);

            int _int = 1;

            Writer.Write(path, _int);

            double _double = 3.14159265;

            Writer.Write(path, _double);

            string _string = " Vishy  ";

            Writer.Write(path, _string);

            DateTime _dateTime = new DateTime(1999, 12, 31, 23, 59, 59);

            Writer.WriteLine(path, _dateTime);

            Writer.NextLine(path);      // Extra line

            Writer.WriteLine(path, _bool);
            Writer.WriteLine(path, _int);
            Writer.WriteLine(path, _double);
            Writer.WriteLine(path, _string);

            IParsedFile parsedFile = new ParsedFile(path);
            IParsedLine firstLine  = parsedFile.NextLine();

            Assert.Equal(_bool, firstLine.NextElement <bool>());
            Assert.Equal(_int, firstLine.NextElement <int>());
            Assert.Equal(_double, firstLine.NextElement <double>());
            Assert.Equal(_string.Trim(), firstLine.NextElement <string>());

            Assert.Equal(_bool, parsedFile.NextLine().NextElement <bool>());
            Assert.Equal(_int, parsedFile.NextLine().NextElement <int>());
            Assert.Equal(_double, parsedFile.NextLine().NextElement <double>());
            Assert.Equal(_string.Trim(), parsedFile.NextLine().NextElement <string>());

            Assert.True(parsedFile.Empty);
        }
示例#19
0
        private static void ValidateSimpleFile(IParsedLine firstLine, IParsedLine secondLine)
        {
            Assert.Equal(1.1, firstLine.NextElement <double>());
            Assert.Equal(2.2, firstLine.NextElement <double>());
            Assert.Equal(3.3, firstLine.NextElement <double>());
            Assert.Equal(4.4, firstLine.NextElement <double>());
            Assert.Equal(5.5, firstLine.NextElement <double>());
            Assert.True(firstLine.Empty);

            Assert.Equal(6.6, secondLine.NextElement <double>());
            Assert.Equal(7.7, secondLine.NextElement <double>());
            Assert.Equal(8.8, secondLine.NextElement <double>());
            Assert.Equal(9.9, secondLine.NextElement <double>());
            Assert.Equal(10.10, secondLine.NextElement <double>());
            Assert.True(secondLine.Empty);
        }
示例#20
0
        public Tuple <int, int> ParseInput()
        {
            IParsedFile parsedFile = new ParsedFile(FilePath);

            IParsedLine parsedLine = parsedFile.NextLine();

            int nPlayers = parsedLine.NextElement <int>();

            string str = string.Empty;

            do
            {
                str = parsedLine.NextElement <string>();
            } while (str != "worth");

            int maxPoints = parsedLine.NextElement <int>();

            return(Tuple.Create(nPlayers, maxPoints));
        }
        private void ReadFromBuffer(ref ReadOnlySequence <byte> buffer, ParsingData parsingData)
        {
            while (TryReadLine(ref buffer, out ReadOnlySequence <byte> sequence))
            {
                IParsedLine parsedLine = ProcessSequence(
                    sequence, ref parsingData.CurrentOffset, parsingData.ParseMode);

                if (parsedLine == null)
                {
                    continue;
                }

                if (parsedLine.ParseMode == ParseMode.Regular &&
                    parsedLine is ObjectDataParsedLine objectDataParsedLine)
                {
                    parsingData.PdfObjects.Add(objectDataParsedLine.ObjectData);
                }

                if (parsedLine.ParseMode == ParseMode.InsideXref &&
                    parsedLine is XRefTableHeaderParsedLine xRefTableHeaderParsedLine)
                {
                    parsingData.CurrentXRefTableFirstObjectNumber =
                        xRefTableHeaderParsedLine.FirstObjectNumber;
                    parsingData.CurrentXRefTableSize =
                        xRefTableHeaderParsedLine.TableSize;
                    parsingData.CurrentXRefTableObjectNumberIndex = 0;
                }

                if (parsedLine.ParseMode == ParseMode.InsideXref &&
                    parsedLine is ObjectDataParsedLine xrefObjectDataParsedLine)
                {
                    parsingData.XRefObjects.Add(
                        new ObjectData(
                            parsingData.CurrentXRefTableObjectNumberIndex + parsingData.CurrentXRefTableFirstObjectNumber,
                            xrefObjectDataParsedLine.ObjectData.ObjectGeneration,
                            xrefObjectDataParsedLine.ObjectData.ObjectOffset));

                    parsingData.CurrentXRefTableObjectNumberIndex++;
                }

                parsingData.ParseMode = parsedLine.ParseMode;
            }
        }
示例#22
0
        public void BasicTest()
        {
            // Sample file:
            // First line has a random number and a category of aliments.
            // Following lines firstly indicate how many numeric elements are following.
            // After those numeric elements, they include an unknown number of items.

            List <int>    numberList = new();
            List <string> stringList = new();

            IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt");

            IParsedLine firstLine = file.NextLine();

            int    n   = firstLine.NextElement <int>();
            string str = firstLine.NextElement <string>();

            while (!file.Empty)
            {
                IParsedLine line    = file.NextLine();
                int         counter = line.NextElement <int>();
                for (int j = 0; j < counter; ++j)
                {
                    numberList.Add(line.NextElement <int>());
                }

                while (!line.Empty)
                {
                    stringList.Add(line.NextElement <string>());
                }
            }

            Assert.Equal(23, n);
            Assert.Equal("food", str);
            Assert.Equal(new List <int>()
            {
                100, 200, 300, 400, 500, 600, 700
            }, numberList);
            Assert.Equal(new List <string>()
            {
                "apple", "peer", "banana", "meat", "fish"
            }, stringList);
        }
示例#23
0
        public void PeekTestNotModifiyngFile()
        {
            IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt");

            for (int i = 0; i < 10; ++i)
            {
                IParsedLine peekedFirstLine = file.PeekNextLine();       // Allows its modification without extracting it

                int peekedN = peekedFirstLine.PeekNextElement <int>();
                Assert.Equal(peekedN, peekedFirstLine.PeekNextElement <int>());

                IParsedLine peekedFirstLine2 = file.PeekNextLine();

                int peekedN2 = peekedFirstLine.PeekNextElement <int>();
                Assert.Equal(peekedN2, peekedFirstLine2.PeekNextElement <int>());

                Assert.Equal(peekedN, peekedN2);
            }
        }
示例#24
0
        public void PeekTestEmptyingFile()
        {
            IParsedFile file = new ParsedFile(_sampleFolderPath + "Sample_file.txt");

            IParsedLine peekedFirstLine = file.PeekNextLine();   // Allows its modification without extracting it

            int peekedN = peekedFirstLine.PeekNextElement <int>();

            Assert.Equal(peekedN, peekedFirstLine.NextElement <int>());          // Extracting the element
            string peekedStr = peekedFirstLine.PeekNextElement <string>();

            Assert.Equal(peekedStr, peekedFirstLine.NextElement <string>());

            Assert.True(file.NextLine().Empty);

            while (!file.Empty)
            {
                List <int>    peekedNumberList = new();
                List <string> peekedStringList = new();

                IParsedLine peekedLine    = file.PeekNextLine();
                int         peekedCounter = peekedLine.PeekNextElement <int>();
                Assert.Equal(peekedCounter, peekedLine.NextElement <int>());
                for (int j = 0; j < peekedCounter; ++j)
                {
                    peekedNumberList.Add(peekedLine.PeekNextElement <int>());
                    Assert.Equal(peekedNumberList.Last(), peekedLine.NextElement <int>());   // Extracting the element
                }

                while (!peekedLine.Empty)
                {
                    peekedStringList.Add(peekedLine.PeekNextElement <string>());
                    Assert.Equal(peekedStringList.Last(), peekedLine.NextElement <string>());   // Extracting the element
                }

                IParsedLine line = file.NextLine();   // Extracting the line, already emptied, to allow the test to finish
                Assert.True(line.Empty);
            }
        }
示例#25
0
        private HashSet <Step> ParseInput()
        {
            HashSet <Step> steps = new HashSet <Step>();

            IParsedFile parsedFile = new ParsedFile(FilePath);

            while (!parsedFile.Empty)
            {
                IParsedLine parsedLine = parsedFile.NextLine();

                parsedLine.NextElement <string>();

                string dependencyName = parsedLine.NextElement <string>();
                Step   stepDependency = new Step(char.ToUpperInvariant(dependencyName.Single()));
                steps.Add(stepDependency);

                while (!parsedLine.Empty)
                {
                    string word = parsedLine.NextElement <string>();

                    if (word.ToUpperInvariant() == "STEP")
                    {
                        string mainStepName = parsedLine.NextElement <string>();

                        if (steps.TryGetValue(new Step(char.ToUpperInvariant(mainStepName.Single())), out Step existingStep))
                        {
                            existingStep.NonResolvedDependencies.Add(stepDependency);
                        }
                        else
                        {
                            steps.Add(new Step(mainStepName.Single(), stepDependency));
                        }
                        continue;
                    }
                }
            }
            return(steps);
        }
示例#26
0
        private IEnumerable <Star> ParseInput()
        {
            IParsedFile parsedFile = new ParsedFile(FilePath);

            while (!parsedFile.Empty)
            {
                IParsedLine parsedLine = parsedFile.NextLine();

                string firstPart = parsedLine.NextElement <string>();
                if (firstPart.EndsWith('<'))
                {
                    firstPart += parsedLine.NextElement <string>();
                }
                string x = firstPart.Substring(firstPart.IndexOf("position=<") + "position=<".Length).TrimStart('<').TrimEnd(',');

                string secondPart = parsedLine.NextElement <string>();
                string y          = secondPart.Trim().Trim('>');

                string thirdPart = parsedLine.NextElement <string>();
                if (thirdPart.EndsWith('<'))
                {
                    thirdPart += parsedLine.NextElement <string>();
                }
                string speedX = thirdPart.Substring(firstPart.IndexOf("velocity=<") + "velocity=<".Length).TrimStart('<').TrimEnd(',');

                string fourthPart = parsedLine.NextElement <string>();
                string speedY     = fourthPart.Trim().Trim('>');

                if (!parsedLine.Empty)
                {
                    throw new Exception("Exception parsing lines, some elements left");
                }

                yield return(new Star(int.Parse(x), int.Parse(y), new Point(int.Parse(speedX), int.Parse(speedY))));
            }
        }