changeset 138:1a982ee56458

A script's bytecode is now exposed as a buffer object.
author Atul Varma <varmaa@toolness.com>
date Sun, 23 Aug 2009 22:26:58 -0700
parents f83a1603c417
children d08cb5a06c66
files src/script.cpp tests/test_pymonkey.py
diffstat 2 files changed, 39 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/src/script.cpp	Sun Aug 23 21:59:39 2009 -0700
+++ b/src/script.cpp	Sun Aug 23 22:26:58 2009 -0700
@@ -37,6 +37,8 @@
 #include "script.h"
 #include "utils.h"
 
+#include "jsscript.h"
+
 static void
 PYM_JSScriptDealloc(PYM_JSScript *self)
 {
@@ -44,6 +46,34 @@
   PYM_JSObjectType.tp_dealloc((PyObject *) self);
 }
 
+Py_ssize_t PYM_readbuffer(PYM_JSScript *self, Py_ssize_t segment,
+                          void **ptrptr)
+{
+  *ptrptr = self->script->code;
+  return self->script->length;
+}
+
+Py_ssize_t PYM_segcount(PYM_JSScript *self, Py_ssize_t *lenp)
+{
+  if (lenp)
+    *lenp = self->script->length;
+  return 1;
+}
+
+Py_ssize_t PYM_charbuffer(PYM_JSScript *self, Py_ssize_t segment,
+                          const char **ptrptr)
+{
+  *ptrptr = (char *) self->script->code;
+  return self->script->length;
+}
+
+static PyBufferProcs PYM_bufferProcs = {
+  (readbufferproc) PYM_readbuffer,
+  NULL,
+  (segcountproc) PYM_segcount,
+  (charbufferproc) PYM_charbuffer
+};
+
 PyTypeObject PYM_JSScriptType = {
   PyObject_HEAD_INIT(NULL)
   0,                           /*ob_size*/
@@ -65,9 +95,9 @@
   0,                           /*tp_str*/
   0,                           /*tp_getattro*/
   0,                           /*tp_setattro*/
-  0,                           /*tp_as_buffer*/
+  &PYM_bufferProcs,            /*tp_as_buffer*/
                                /*tp_flags*/
-  Py_TPFLAGS_DEFAULT,
+  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GETCHARBUFFER,
                                /* tp_doc */
   "JavaScript Script.",
   0,                           /* tp_traverse */
--- a/tests/test_pymonkey.py	Sun Aug 23 21:59:39 2009 -0700
+++ b/tests/test_pymonkey.py	Sun Aug 23 22:26:58 2009 -0700
@@ -48,6 +48,13 @@
                 u'SyntaxError: missing ; before statement'
                 )
 
+    def testScriptIsExposedAsBuffer(self):
+        rt = pymonkey.Runtime()
+        cx = rt.new_context()
+        obj = cx.new_object()
+        script = cx.compile_script(obj, 'foo', '<string>', 1)
+        self.assertTrue(len(buffer(script)) > 0)
+
     def testCompileScriptWorks(self):
         self.assertEqual(self._execjs('5 + 1'), 6)