Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ArraySlice.cs « PatternMatching « Impl « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6e7455e76240f403c994934f95c7af3362b6c6fc (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
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Diagnostics;
using TextSpan = Microsoft.VisualStudio.Text.Span;

namespace Microsoft.VisualStudio.Text.PatternMatching.Implementation
{
    internal struct ArraySlice<T>
    {
        private readonly T[] _array;
        private int _start;
        private int _length;

        public int Length => _length;

        public ArraySlice(T[] array) : this(array, 0, array.Length)
        {
        }

        public ArraySlice(T[] array, TextSpan span) : this(array, span.Start, span.Length)
        {
        }

        public ArraySlice(T[] array, int start, int length) : this()
        {
            _array = array;
            SetStartAndLength(start, length);
        }

        public T this[int i]
        {
            get
            {
                Debug.Assert(i < _length);
                return _array[i + _start];
            }
        }

        private void SetStartAndLength(int start, int length)
        {
            if (start < 0)
            {
                throw new ArgumentException(nameof(start), $"{start} < {0}");
            }

            if (start > _array.Length)
            {
                throw new ArgumentException(nameof(start), $"{start} > {_array.Length}");
            }

            CheckLength(start, length);

            _start = start;
            _length = length;
        }

        private void CheckLength(int start, int length)
        {
            if (length < 0)
            {
                throw new ArgumentException(nameof(length), $"{length} < {0}");
            }

            if (start + length > _array.Length)
            {
                throw new ArgumentException(nameof(start), $"{start} + {length} > {_array.Length}");
            }
        }

        public void MoveStartForward(int amount)
        {
            SetStartAndLength(_start + amount, _length - amount);
        }

        public void SetLength(int length)
        {
            CheckLength(_start, length);
            _length = length;
        }
    }
}