summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Razor/Text/SourceLocationTracker.cs
blob: aaf830bc4cb661b56306236ba40b5c38e543cc6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Web.Razor.Parser;

namespace System.Web.Razor.Text
{
    public class SourceLocationTracker
    {
        private int _absoluteIndex = 0;
        private int _characterIndex = 0;
        private int _lineIndex = 0;
        private SourceLocation _currentLocation;

        public SourceLocationTracker()
            : this(SourceLocation.Zero)
        {
        }

        public SourceLocationTracker(SourceLocation currentLocation)
        {
            CurrentLocation = currentLocation;

            UpdateInternalState();
        }

        public SourceLocation CurrentLocation
        {
            get { return _currentLocation; }
            set
            {
                if (_currentLocation != value)
                {
                    _currentLocation = value;
                    UpdateInternalState();
                }
            }
        }

        public void UpdateLocation(char characterRead, char nextCharacter)
        {
            _absoluteIndex++;

            if (ParserHelpers.IsNewLine(characterRead) && (characterRead != '\r' || nextCharacter != '\n'))
            {
                _lineIndex++;
                _characterIndex = 0;
            }
            else
            {
                _characterIndex++;
            }

            UpdateLocation();
        }

        public SourceLocationTracker UpdateLocation(string content)
        {
            for (int i = 0; i < content.Length; i++)
            {
                char nextCharacter = '\0';
                if (i < content.Length - 1)
                {
                    nextCharacter = content[i + 1];
                }
                UpdateLocation(content[i], nextCharacter);
            }
            return this;
        }

        private void UpdateInternalState()
        {
            _absoluteIndex = CurrentLocation.AbsoluteIndex;
            _characterIndex = CurrentLocation.CharacterIndex;
            _lineIndex = CurrentLocation.LineIndex;
        }

        private void UpdateLocation()
        {
            CurrentLocation = new SourceLocation(_absoluteIndex, _lineIndex, _characterIndex);
        }

        public static SourceLocation CalculateNewLocation(SourceLocation lastPosition, string newContent)
        {
            return new SourceLocationTracker(lastPosition).UpdateLocation(newContent).CurrentLocation;
        }
    }
}