Commits

Jeethu Rao committed e7032cb

Merged patch from brentp, fixes: #1.

  • Participants
  • Parent commits c3792cc

Comments (0)

Files changed (5)

+syntax: regexp
+tinycdb\.c
 
 Example #1 writing :
 
-import pytinycdb
+import tinycdb
 
-db = pytinycdb.create('foo.db')
+db = tinycdb.create('foo.db')
 db['foo'] = 'bar'
 db['bar'] = 'baz'
 print 'foo' in db # Prints True
 Example #2 reading :
 
 import pytinycdb
-db = pytinycdb.read('foo.db')
+db = tinycdb.read('foo.db')
 if 'foo' in db :
     print "Found"
     print db['foo']
 from Cython.Distutils import build_ext
 
 setup(
+    name="tinycdb",
+    version="0.1",
+    description="A Python wrapper for TinyCDB",
+    author='Jeethu Rao',
+    author_email='jeethu@jeethurao.com',
     cmdclass = {'build_ext': build_ext},
-    ext_modules = [Extension("pytinycdb", ["tinycdb.pyx"],
+    ext_modules = [Extension("tinycdb", ["tinycdb.pyx"],
                              libraries=['cdb'])]
 )
 
 import unittest
-import pytinycdb
+import tinycdb
 import os
 
+class TinyCDBTestCase(unittest.TestCase):
+    _TEST_DB_FILENAME = 'test.cdb'
+    def setUp(self):
+        self.db = tinycdb.TinyCDB(self._TEST_DB_FILENAME, mode="w")
+
+    def test_writes(self):
+        data = os.urandom(100)
+        db = self.db
+
+        db['foo'] = data
+        db['bar'] = 'hello world'
+        self.assertEqual('foo' in db,True)
+        self.assertEqual('moo' in db,False)
+        self.assertRaises(TypeError,lambda : db['foo'])
+        self.assert_(hasattr(db, "__setitem__"))
+        db.close()
+
+        db1 = tinycdb.TinyCDB(self._TEST_DB_FILENAME, mode="r")
+        self.assertEqual(db1['foo'],data)
+        self.assertRaises(KeyError,lambda : db1['moo'])
+        self.assert_(not hasattr(db1, "__setitem__"))
+
+    def test_repr(self):
+        db = self.db
+        self.assertEqual(repr(db), "TinyCDB('test.cdb', 'w')")
+        db.close()
+
+        db1 = tinycdb.TinyCDB(self._TEST_DB_FILENAME, mode="r")
+        self.assertEqual(repr(db1), "TinyCDB('test.cdb', 'r')")
+        db1.close()
+
+    def tearDown( self ) :
+        os.unlink(self._TEST_DB_FILENAME)
+
 class TestCase(unittest.TestCase) :
     _TEST_DB_FILENAME = 'test.cdb'
     def tearDown( self ) :
         db[k] = v
 
     def test( self ) :
-        db = pytinycdb.create(self._TEST_DB_FILENAME)
+        db = tinycdb.create(self._TEST_DB_FILENAME)
         data = os.urandom(100)
         db['foo'] = data
         db['bar'] = 'hello world'
         self.assertEqual('moo' in db,False)
         self.assertRaises(TypeError,lambda : db['foo'])
         db.close()
-        db1 = pytinycdb.read(self._TEST_DB_FILENAME)
+        db1 = tinycdb.read(self._TEST_DB_FILENAME)
         self.assertEqual(db1['foo'],data)
         self.assertRaises(KeyError,lambda : db1['moo'])
         self.assertRaises(TypeError,lambda : self._setitem(db1,'foo','bar'))
 
 By Jeethu Rao <jeethu@jeethurao.com>
 '''
-
-cdef extern from "Python.h":
-    int PyString_AsStringAndSize(object obj, char **buffer, Py_ssize_t* length) except -1
-    object PyString_FromStringAndSize(char *v, int len)
-
-cdef extern from "stdlib.h" :
-    void *malloc(size_t size)
-    void *free(void *ptr)
+cimport python_string as PS
+cimport stdlib
 
 cdef extern from "fcntl.h" :
     int open( char* path, int flag, int mode )
     cdef char *buffer
     cdef Py_ssize_t len
     cdef int rez
-    rez = PyString_AsStringAndSize(file_name, &buffer, &len)
+    rez = PS.PyString_AsStringAndSize(file_name, &buffer, &len)
     if rw :
         rez = open( buffer, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR )
     else :
 class CDBError( Exception ) :
     pass
 
-cdef class create :
-    cdef int fd, finished
+cdef class tinycdb:
+    cdef int fd
+    cdef public char mode
+    cdef public fname
     cdef cdb_make cdbm
+    def __contains__( self, key ) :
+        cdef char *buffer
+        cdef Py_ssize_t len
+        cdef int rez
+        cdef unsigned int dlen
+        rez = PS.PyString_AsStringAndSize(key, &buffer, &len)
+        if self.mode == c'w':
+            rez = cdb_make_exists(&self.cdbm, buffer, len)
+        else:
+            rez = cdb_seek( self.fd, buffer, len, &dlen )
+        if rez < 0 :
+            raise CDBError("Unknown Error")
+        return rez
+
+    def __repr__(self):
+        return "TinyCDB('%s', '%s')" % (self.fname, chr(self.mode))
+
+    def close(self):
+        if self.fd: close( self.fd )
+
+def TinyCDB(fname, mode="r"):
+    if mode == "r":
+        return read(fname)
+    return create(fname)
+
+cdef class create(tinycdb):
+    cdef int finished
     def __init__( self, fname ) :
+        self.mode = 'w'
+        self.fname = fname
         cdef int rez
         self.fd = openFile( fname, 1 )
         rez = cdb_make_start( &self.cdbm, self.fd )
         cdef char *buffer1, *buffer2
         cdef Py_ssize_t len1, len2
         cdef int rez
-        rez = PyString_AsStringAndSize(key, &buffer1, &len1)
-        rez = PyString_AsStringAndSize(value, &buffer2, &len2)
+        rez = PS.PyString_AsStringAndSize(key, &buffer1, &len1)
+        rez = PS.PyString_AsStringAndSize(value, &buffer2, &len2)
         rez = cdb_make_add( &self.cdbm, buffer1, len1, buffer2, len2 )
         if rez != 0 :
             raise CDBError("Unknown Error")
     
-    def __contains__( self, key ) :
-        cdef char *buffer
-        cdef Py_ssize_t len
-        cdef int rez
-        rez = PyString_AsStringAndSize(key, &buffer, &len)
-        rez = cdb_make_exists(&self.cdbm, buffer, len)
-        if rez < 0 :
-            raise CDBError("Unknown Error")
-        if rez == 1 :
-            return True
-        return False
-
-
     def close( self ) :
         if not self.finished :
             self.finished = 1
 
     def __dealloc__( self ) :
         if not self.finished :
+            self.finished = 1
             cdb_make_finish(&self.cdbm)
         if self.fd :
             close( self.fd )
 
-cdef class read :
-    cdef int fd
+cdef class read(tinycdb):
     def __init__( self, fname ) :
         self.fd = openFile( fname, 0 )
-
-    def __contains__( self, key ) :
-        cdef char *buffer
-        cdef Py_ssize_t len
-        cdef int rez
-        cdef unsigned int dlen
-        rez = PyString_AsStringAndSize(key, &buffer, &len)
-        rez = cdb_seek( self.fd, buffer, len, &dlen )
-        if rez < 0 :
-            raise CDBError("Unknown Error")
-        return rez
+        self.mode = 'r'
+        self.fname = fname
 
     def __getitem__( self, key ) :
         cdef char *buffer
         cdef int rez
         cdef unsigned int dlen
         cdef object ret
-        rez = PyString_AsStringAndSize(key, &buffer, &len)
+        rez = PS.PyString_AsStringAndSize(key, &buffer, &len)
         rez = cdb_seek( self.fd, buffer, len, &dlen )
         if rez < 0 :
             raise CDBError("Unknown Error")
         if rez == 0 :
             raise KeyError("Key \'%s\' not found"%key)
-        buffer = <char *>malloc(dlen)
+        buffer = <char *>stdlib.malloc(dlen)
         if buffer == NULL :
             raise MemoryError("malloc() failed")
         rez = cdb_bread( self.fd, buffer, dlen )
         if rez == 0 :
-            ret = PyString_FromStringAndSize( buffer, dlen )
-            free(buffer)
+            ret = PS.PyString_FromStringAndSize( buffer, dlen )
+            stdlib.free(buffer)
             return ret
         raise CDBError("Unknown Error")
-        free(buffer)
+        stdlib.free(buffer)
 
     def __dealloc__( self ) :
-        if self.fd :
-            close( self.fd )
+        self.close()