3 # Copyright 2008 The Closure Linter Authors. All Rights Reserved.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS-IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 """Classes to represent positions within strings."""
19 __author__ = ('robbyw@google.com (Robert Walker)',
20 'ajp@google.com (Andy Perelson)')
23 class Position(object):
24 """Object representing a segment of a string.
27 start: The index in to the string where the segment starts.
28 length: The length of the string segment.
31 def __init__(self, start, length):
32 """Initialize the position object.
35 start: The start index.
36 length: The number of characters to include.
41 def Get(self, string):
42 """Returns this range of the given string.
45 string: The string to slice.
48 The string within the range specified by this object.
50 return string[self.start:self.start + self.length]
52 def Set(self, target, source):
53 """Sets this range within the target string to the source string.
56 target: The target string.
57 source: The source string.
62 return target[:self.start] + source + target[self.start + self.length:]
65 """Create a Position representing the end of the given string.
68 string: The string to represent the end of.
71 The created Position object.
73 return Position(len(string), 0)
74 AtEnd = staticmethod(AtEnd)
76 def IsAtEnd(self, string):
77 """Returns whether this position is at the end of the given string.
80 string: The string to test for the end of.
83 Whether this position is at the end of the given string.
85 return self.start == len(string) and self.length == 0
88 """Create a Position representing the beginning of any string.
91 The created Position object.
94 AtBeginning = staticmethod(AtBeginning)
96 def IsAtBeginning(self):
97 """Returns whether this position is at the beginning of any string.
100 Whether this position is at the beginning of any string.
102 return self.start == 0 and self.length == 0
105 """Create a Position representing the entire string.
108 string: The string to represent the entirety of.
111 The created Position object.
113 return Position(0, len(string))
114 All = staticmethod(All)
117 """Returns a Position object for the specified index.
120 index: The index to select, inclusively.
123 The created Position object.
125 return Position(index, 1)
126 Index = staticmethod(Index)