Revision 7b4126b7

b/lib/utils.py
1039 1039
  return result
1040 1040

  
1041 1041

  
1042
def FirstFree(seq, base=0):
1043
  """Returns the first non-existing integer from seq.
1044

  
1045
  The seq argument should be a sorted list of positive integers. The
1046
  first time the index of an element is smaller than the element
1047
  value, the index will be returned.
1048

  
1049
  The base argument is used to start at a different offset,
1050
  i.e. [3, 4, 6] with offset=3 will return 5.
1051

  
1052
  Example: [0, 1, 3] will return 2.
1053

  
1054
  """
1055
  for idx, elem in enumerate(seq):
1056
    assert elem >= base, "Passed element is higher than base offset"
1057
    if elem > idx + base:
1058
      # idx is not used
1059
      return idx + base
1060
  return None
1061

  
1062

  
1042 1063
def all(seq, pred=bool):
1043 1064
  "Returns True if pred(x) is True for every element in the iterable"
1044 1065
  for elem in itertools.ifilterfalse(pred, seq):
b/test/ganeti.utils_unittest.py
41 41
     RemoveFile, CheckDict, MatchNameComponent, FormatUnit, \
42 42
     ParseUnit, AddAuthorizedKey, RemoveAuthorizedKey, \
43 43
     ShellQuote, ShellQuoteArgs, TcpPing, ListVisibleFiles, \
44
     SetEtcHostsEntry, RemoveEtcHostsEntry
44
     SetEtcHostsEntry, RemoveEtcHostsEntry, FirstFree
45 45
from ganeti.errors import LockError, UnitParseError
46 46

  
47 47
def _ChildHandler(signal, stack):
......
689 689
    self._test(["a", "b"], ["a", "b"])
690 690
    self._test(["a", "b", "a"], ["a", "b"])
691 691

  
692
class TestFirstFree(unittest.TestCase):
693
  """Test case for the FirstFree function"""
694

  
695
  def test(self):
696
    """Test FirstFree"""
697
    self.failUnlessEqual(FirstFree([0, 1, 3]), 2)
698
    self.failUnlessEqual(FirstFree([]), None)
699
    self.failUnlessEqual(FirstFree([3, 4, 6]), 0)
700
    self.failUnlessEqual(FirstFree([3, 4, 6], base=3), 5)
701
    self.failUnlessRaises(AssertionError, FirstFree, [0, 3, 4, 6], base=3)
692 702

  
693 703
if __name__ == '__main__':
694 704
  unittest.main()

Also available in: Unified diff