]> granicus.if.org Git - python/commitdiff
Writer APIs: use empty string singletons
authorVictor Stinner <victor.stinner@gmail.com>
Mon, 12 Oct 2015 11:29:43 +0000 (13:29 +0200)
committerVictor Stinner <victor.stinner@gmail.com>
Mon, 12 Oct 2015 11:29:43 +0000 (13:29 +0200)
Modify _PyBytesWriter_Finish() and _PyUnicodeWriter_Finish() to return the
empty bytes/Unicode string if the string is empty.

Objects/bytesobject.c
Objects/unicodeobject.c

index 4b312717cfb3c2e03c5761fb1ae732c02a1c2a2a..532051e2424be631e7239005f8d3944147de3919 100644 (file)
@@ -4019,19 +4019,24 @@ _PyBytesWriter_Finish(_PyBytesWriter *writer, void *str)
     _PyBytesWriter_CheckConsistency(writer, str);
 
     pos = _PyBytesWriter_GetPos(writer, str);
-    if (!writer->use_small_buffer) {
+    if (pos == 0) {
+        Py_CLEAR(writer->buffer);
+        /* Get the empty byte string singleton */
+        result = PyBytes_FromStringAndSize(NULL, 0);
+    }
+    else if (writer->use_small_buffer) {
+        result = PyBytes_FromStringAndSize(writer->small_buffer, pos);
+    }
+    else {
+        result = writer->buffer;
+        writer->buffer = NULL;
+
         if (pos != writer->allocated) {
-            if (_PyBytes_Resize(&writer->buffer, pos)) {
-                assert(writer->buffer == NULL);
+            if (_PyBytes_Resize(&result, pos)) {
+                assert(result == NULL);
                 return NULL;
             }
         }
-
-        result = writer->buffer;
-        writer->buffer = NULL;
-    }
-    else {
-        result = PyBytes_FromStringAndSize(writer->small_buffer, pos);
     }
     return result;
 }
index 35df74714caac81257397119dc8945b8c501c4c1..4b3746c85c8f439b134ad5d39ab7304d5632fff7 100644 (file)
@@ -13715,17 +13715,26 @@ _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
         assert(PyUnicode_GET_LENGTH(str) == writer->pos);
         return str;
     }
-    if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
-        PyObject *newbuffer;
-        newbuffer = resize_compact(writer->buffer, writer->pos);
-        if (newbuffer == NULL) {
-            Py_CLEAR(writer->buffer);
-            return NULL;
+    if (writer->pos == 0) {
+        Py_CLEAR(writer->buffer);
+
+        /* Get the empty Unicode string singleton ('') */
+        _Py_INCREF_UNICODE_EMPTY();
+        str  = unicode_empty;
+    }
+    else {
+        str = writer->buffer;
+        writer->buffer = NULL;
+
+        if (PyUnicode_GET_LENGTH(str) != writer->pos) {
+            PyObject *str2;
+            str2 = resize_compact(str, writer->pos);
+            if (str2 == NULL)
+                return NULL;
+            str = str2;
         }
-        writer->buffer = newbuffer;
     }
-    str = writer->buffer;
-    writer->buffer = NULL;
+
     assert(_PyUnicode_CheckConsistency(str, 1));
     return unicode_result_ready(str);
 }