Sfoglia il codice sorgente

Add basic iteration methods to Keyset.

Stefano Cossu 6 anni fa
parent
commit
3d537e5693

+ 2 - 0
lakesuperior/store/ldp_rs/keyset.pxd

@@ -3,7 +3,9 @@ cdef class Keyset:
         readonly unsigned char *data
         readonly unsigned char itemsize
         readonly size_t ct, size
+        size_t _cur
 
         void resize(self, size_t ct) except *
         unsigned char *get_item(self, i)
+        bint next(self, unsigned char *val)
 

+ 30 - 0
lakesuperior/store/ldp_rs/keyset.pyx

@@ -30,6 +30,7 @@ cdef class Keyset:
         self.ct = ct
         self.itemsize = itemsize
         self.size = self.itemsize * self.ct
+        self._cur = 0
 
         #logger.debug('Got malloc sizes: {}, {}'.format(ct, itemsize))
         #logger.debug(
@@ -104,9 +105,19 @@ cdef class Keyset:
 
         :rtype: bytes
         """
+        if i >= self.ct:
+            raise ValueError(f'Index {i} out of range.')
+
         return self.get_item(i)[: self.itemsize]
 
 
+    def tell(self):
+        """
+        Tell the position of the cursor in the keyset.
+        """
+        return _cur
+
+
     cdef unsigned char *get_item(self, i):
         """
         Get an item at a given index position. Cython-level method.
@@ -115,8 +126,27 @@ cdef class Keyset:
 
         :rtype: unsigned char*
         """
+        self._cur = i
         return self.data + self.itemsize * i
 
 
+    cdef bint next(self, unsigned char *val):
+        """
+        Return current value and advance the cursor by 1.
+
+        :param unsigned char *val: Addres of value returned. It is void if
+            the end of the buffer was reached.
+
+        :rtype: bint
+        :return: True if a value was found, False if the end of the buffer
+            has been reached.
+        """
+        if _cur >= self.ct:
+            val = NULL
+            return False
+
+        val = self.data + self.itemsize * self._cur
+        self._cur += 1
 
+        return True