Mercurial > public > mercurial-scm > hg
comparison mercurial/revset.py @ 20540:fa16c710a3d8
revset: added cached generated list on generatorset
This allows to iterate the generatorset more than once.
author | Lucas Moscovicz <lmoscovicz@fb.com> |
---|---|
date | Wed, 12 Feb 2014 18:45:49 -0800 |
parents | fe220013e4db |
children | 0e99a66eb7bc |
comparison
equal
deleted
inserted
replaced
20539:aa021ece4506 | 20540:fa16c710a3d8 |
---|---|
2175 | 2175 |
2176 def set(self): | 2176 def set(self): |
2177 return set([r for r in self]) | 2177 return set([r for r in self]) |
2178 | 2178 |
2179 class generatorset(object): | 2179 class generatorset(object): |
2180 """Wrapper structure for generators that provides lazy membership.""" | 2180 """Wrapper structure for generators that provides lazy membership and can |
2181 be iterated more than once. | |
2182 When asked for membership it generates values until either it finds the | |
2183 requested one or has gone through all the elements in the generator | |
2184 """ | |
2181 def __init__(self, gen): | 2185 def __init__(self, gen): |
2182 self._gen = gen | 2186 self._gen = gen |
2183 self._iter = iter(gen) | 2187 self._iter = iter(gen) |
2184 self._cache = {} | 2188 self._cache = {} |
2189 self._genlist = baseset([]) | |
2190 self._iterated = False | |
2191 | |
2192 def _nextitem(self): | |
2193 l = self._iter.next() | |
2194 self._cache[l] = True | |
2195 self._genlist.append(l) | |
2196 return l | |
2185 | 2197 |
2186 def __contains__(self, x): | 2198 def __contains__(self, x): |
2187 if x in self._cache: | 2199 if x in self._cache: |
2188 return self._cache[x] | 2200 return self._cache[x] |
2189 | 2201 |
2202 self._iterated = True | |
2190 while True: | 2203 while True: |
2191 try: | 2204 try: |
2192 l = self._iter.next() | 2205 l = self._nextitem() |
2193 self._cache[l] = True | |
2194 if l == x: | 2206 if l == x: |
2195 return True | 2207 return True |
2196 except (StopIteration): | 2208 except (StopIteration): |
2197 break | 2209 break |
2198 | 2210 |
2199 self._cache[x] = False | 2211 self._cache[x] = False |
2200 return False | 2212 return False |
2201 | 2213 |
2202 def __iter__(self): | 2214 def __iter__(self): |
2203 for item in self._gen: | 2215 if self._iterated: |
2204 self._cache[item] = True | 2216 for l in self._genlist: |
2205 yield item | 2217 yield l |
2218 while True: | |
2219 try: | |
2220 item = self._nextitem() | |
2221 yield item | |
2222 except (StopIteration): | |
2223 break | |
2224 else: | |
2225 self._iterated = True | |
2226 for item in self._gen: | |
2227 self._cache[item] = True | |
2228 self._genlist.append(item) | |
2229 yield item | |
2206 | 2230 |
2207 def set(self): | 2231 def set(self): |
2208 return self | 2232 return self |
2209 | 2233 |
2210 class spanset(object): | 2234 class spanset(object): |