Imported Upstream version 3.0
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / gruimpl / seq_with_cursor.py
1 #
2 # Copyright 2003,2004 Free Software Foundation, Inc.
3
4 # This file is part of GNU Radio
5
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2, or (at your option)
9 # any later version.
10
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20
21
22 # misc utilities
23
24 import types
25 import exceptions
26
27 class seq_with_cursor (object):
28     __slots__ = [ 'items', 'index' ]
29
30     def __init__ (self, items, initial_index = None, initial_value = None):
31         assert len (items) > 0, "seq_with_cursor: len (items) == 0"
32         self.items = items
33         self.set_index (initial_index)
34         if initial_value is not None:
35             self.set_index_by_value(initial_value)
36
37     def set_index (self, initial_index):
38         if initial_index is None:
39             self.index = len (self.items) / 2
40         elif initial_index >= 0 and initial_index < len (self.items):
41             self.index = initial_index
42         else:
43             raise exceptions.ValueError
44         
45     def set_index_by_value(self, v):
46         """
47         Set index to the smallest value such that items[index] >= v.
48         If there is no such item, set index to the maximum value.
49         """
50         self.set_index(0)              # side effect!
51         cv = self.current()
52         more = True
53         while cv < v and more:
54             cv, more = self.next()      # side effect!
55         
56     def next (self):
57         new_index = self.index + 1
58         if new_index < len (self.items):
59             self.index = new_index
60             return self.items[new_index], True
61         else:
62             return self.items[self.index], False
63
64     def prev (self):
65         new_index = self.index - 1
66         if new_index >= 0:
67             self.index = new_index
68             return self.items[new_index], True
69         else:
70             return self.items[self.index], False
71
72     def current (self):
73         return self.items[self.index]
74
75     def get_seq (self):
76         return self.items[:]            # copy of items
77