IPsec: add nth matching SPD entry outbound TCs
[csit.git] / resources / libraries / python / IncrementUtil.py
1 # Copyright (c) 2021 PANTHEON.tech s.r.o.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Increment utilities library."""
15
16
17 class ObjIncrement(object):
18     """
19     An iterator class used to generate incremented values in each iteration
20     or when inc_fmt is called.
21
22     Subclasses should override:
23         _incr: when a simple '+' binary operation isn't sufficient.
24         _str_fmt: when a simple str representation of the incremented object
25             isn't the proper format.
26     """
27     def __init__(self, initial_value, increment):
28         """
29         :param initial_value: The first value to be returned.
30         :param increment: Each iteration/inc_fmt call will return the previous
31             value incremented by this.
32         :type initial_value: object supporting the '+' binary operation
33         :type increment: object supporting the '+' binary operation
34         """
35         self._value = initial_value
36         self._increment = increment
37
38     def _incr(self):
39         """
40         This function will be called in each iteration/inc_fmt call. Subclasses
41         should override this when their object is incremented differently.
42         The function must compute the next iterated value and store it in
43         self._value.
44         """
45         self._value += self._increment
46
47     def __next__(self):
48         """
49         Each iteration returns the current object and stores the incremented
50         object (which will be returned in the next iteration). The first
51         iteration returns the initial value.
52         """
53         return_value = self._value
54         self._incr()
55         return return_value
56
57     def __iter__(self):
58         return self
59
60     def _str_fmt(self):
61         """
62         The string representation is a standard string representation of the
63         incremented object. Subclasses may override this for a different
64         string representation.
65         """
66         return str(self._value)
67
68     def inc_fmt(self):
69         """
70         Return a string representation and increment the current value.
71         """
72         return_value = self._str_fmt()
73         self._incr()
74         return return_value