[pypy-svn] r78182 - in pypy/trunk/pypy/rpython/lltypesystem: . test

afa at codespeak.net afa at codespeak.net
Thu Oct 21 18:09:39 CEST 2010


Author: afa
Date: Thu Oct 21 18:09:35 2010
New Revision: 78182

Modified:
   pypy/trunk/pypy/rpython/lltypesystem/lltype.py
   pypy/trunk/pypy/rpython/lltypesystem/test/test_lltype.py
Log:
Attempt to define a "scoped allocator" to use in a 'with' statement.


Modified: pypy/trunk/pypy/rpython/lltypesystem/lltype.py
==============================================================================
--- pypy/trunk/pypy/rpython/lltypesystem/lltype.py	(original)
+++ pypy/trunk/pypy/rpython/lltypesystem/lltype.py	Thu Oct 21 18:09:35 2010
@@ -1868,6 +1868,32 @@
         leakfinder.remember_free(p._obj0)
     p._obj0._free()
 
+def _make_scoped_allocator(T):
+    class ScopedAlloc:
+        def __init__(self, n=None, zero=False):
+            self.buf = malloc(T, n=n, flavor='raw', zero=zero)
+
+        def __enter__(self):
+            return self.buf
+
+        def __exit__(self, *args):
+            free(self.buf, flavor='raw')
+
+    ScopedAlloc.__name__ = 'ScopedAlloc_%s' % (T,)
+    return ScopedAlloc
+_make_scoped_allocator._annspecialcase_ = 'specialize:memo'
+
+def scoped_alloc(T, n=None, zero=False):
+    """Returns a context manager which handles allocation and
+    deallocation of temporary memory. Use it in a with statement::
+
+        with scoped_alloc(Array(Signed), 1) as array:
+            ...use array...
+        ...it's freed now.
+    """
+    return _make_scoped_allocator(T)(n=n, zero=zero)
+scoped_alloc._annspecialcase_ = 'specialize:arg(0)'
+
 def functionptr(TYPE, name, **attrs):
     if not isinstance(TYPE, FuncType):
         raise TypeError, "functionptr() for FuncTypes only"

Modified: pypy/trunk/pypy/rpython/lltypesystem/test/test_lltype.py
==============================================================================
--- pypy/trunk/pypy/rpython/lltypesystem/test/test_lltype.py	(original)
+++ pypy/trunk/pypy/rpython/lltypesystem/test/test_lltype.py	Thu Oct 21 18:09:35 2010
@@ -1,3 +1,4 @@
+from __future__ import with_statement
 import py
 from pypy.rpython.lltypesystem.lltype import *
 from pypy.rpython.lltypesystem import lltype, rffi
@@ -846,3 +847,9 @@
         p2 = malloc(Array(Signed), 1, flavor='raw', track_allocation=False)
         free(p2, flavor='raw', track_allocation=False)
         # p1 is not freed
+
+    def test_scoped_allocator(self):
+        with scoped_alloc(Array(Signed), 1) as array:
+            array[0] = -42
+            x = array[0]
+        assert x == -42



More information about the Pypy-commit mailing list