Debian Codegraph @

neutron_taas/common/utils.py

raw
1 # Copyright (C) 2018 AT&T
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15
16 def get_list_from_ranges_str(ranges_str):
17 """Convert the range in string format to ranges list
18
19 And yield the merged ranges in order. The argument must be a
20 string having comma separated vlan and vlan-ranges.
21
22 get_list_from_ranges_str("4,6,10-13,25-27,100-103")
23 [4, 6, 10, 11, 12, 13, 25, 26, 27, 100, 101, 102, 103]
24 """
25 return sum(((list(range(*[int(range_start) + range_index
26 for range_index, range_start in
27 enumerate(range_item.split('-'))]))
28 if '-' in range_item else [int(range_item)])
29 for range_item in ranges_str.split(',')), [])
30
31
32 def get_ranges_str_from_list(ranges):
33 """Convert the ranges list to string format
34
35 And yield the merged ranges in order in string format.
36 The argument must be an iterable of pairs (start, stop).
37
38 get_ranges_str_from_list([4, 11, 12, 13, 25, 26, 27, 101, 102, 103])
39 "4,11-13,25-27,101-103"
40 """
41 ranges_str = []
42 for val in sorted(ranges):
43 if not ranges_str or ranges_str[-1][-1] + 1 != val:
44 ranges_str.append([val])
45 else:
46 ranges_str[-1].append(val)
47 return ",".join([str(range_item[0]) if len(range_item) == 1
48 else str(range_item[0]) + "-" + str(range_item[-1])
49 for range_item in ranges_str])