summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Razor/Text/SeekableTextReader.cs
blob: bfe6d40185063c4b95ec242d56b1880342186620 (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
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.IO;

namespace System.Web.Razor.Text
{
    public class SeekableTextReader : TextReader, ITextDocument
    {
        private int _position = 0;
        private LineTrackingStringBuffer _buffer = new LineTrackingStringBuffer();
        private SourceLocation _location = SourceLocation.Zero;
        private char? _current;

        public SeekableTextReader(string content)
        {
            _buffer.Append(content);
            UpdateState();
        }

        public SeekableTextReader(TextReader source)
            : this(source.ReadToEnd())
        {
        }

        public SeekableTextReader(ITextBuffer buffer)
            : this(buffer.ReadToEnd())
        {
        }

        public SourceLocation Location
        {
            get { return _location; }
        }

        public int Length
        {
            get { return _buffer.Length; }
        }

        public int Position
        {
            get { return _position; }
            set
            {
                if (_position != value)
                {
                    _position = value;
                    UpdateState();
                }
            }
        }

        internal LineTrackingStringBuffer Buffer
        {
            get { return _buffer; }
        }

        public override int Read()
        {
            if (_current == null)
            {
                return -1;
            }
            char chr = _current.Value;
            _position++;
            UpdateState();
            return chr;
        }

        public override int Peek()
        {
            if (_current == null)
            {
                return -1;
            }
            return _current.Value;
        }

        private void UpdateState()
        {
            if (_position < _buffer.Length)
            {
                LineTrackingStringBuffer.CharacterReference chr = _buffer.CharAt(_position);
                _current = chr.Character;
                _location = chr.Location;
            }
            else if (_buffer.Length == 0)
            {
                _current = null;
                _location = SourceLocation.Zero;
            }
            else
            {
                _current = null;
                _location = _buffer.EndLocation;
            }
        }
    }
}