changeset 36654:b864f4536ca8

cext: refactor cleanup code in bdiff() A future commit will need to introduce additional cleanup code. We refactor the cleanup code to check NULL before calling free(). We also initialize these variables as NULL. We set the out of memory exception explicitly, so we can just return result. Differential Revision: https://phab.mercurial-scm.org/D2586
author Gregory Szorc <gregory.szorc@gmail.com>
date Sat, 03 Mar 2018 11:19:43 -0500
parents 2f7a3c90c0d7
children 68026dd7c4f9
files mercurial/cext/bdiff.c
diffstat 1 files changed, 22 insertions(+), 12 deletions(-) [+]
line wrap: on
line diff
--- a/mercurial/cext/bdiff.c	Fri Mar 02 07:13:33 2018 +0530
+++ b/mercurial/cext/bdiff.c	Sat Mar 03 11:19:43 2018 -0500
@@ -62,11 +62,11 @@
 {
 	char *sa, *sb, *rb, *ia, *ib;
 	PyObject *result = NULL;
-	struct bdiff_line *al, *bl;
+	struct bdiff_line *al = NULL, *bl = NULL;
 	struct bdiff_hunk l, *h;
 	int an, bn, count;
 	Py_ssize_t len = 0, la, lb, li = 0, lcommon = 0, lmax;
-	PyThreadState *_save;
+	PyThreadState *_save = NULL;
 
 	l.next = NULL;
 
@@ -89,12 +89,16 @@
 
 	an = bdiff_splitlines(sa + lcommon, la - lcommon, &al);
 	bn = bdiff_splitlines(sb + lcommon, lb - lcommon, &bl);
-	if (!al || !bl)
-		goto nomem;
+	if (!al || !bl) {
+		PyErr_NoMemory();
+		goto cleanup;
+	}
 
 	count = bdiff_diff(al, an, bl, bn, &l);
-	if (count < 0)
-		goto nomem;
+	if (count < 0) {
+		PyErr_NoMemory();
+		goto cleanup;
+	}
 
 	/* calculate length of output */
 	la = lb = 0;
@@ -110,7 +114,7 @@
 	result = PyBytes_FromStringAndSize(NULL, len);
 
 	if (!result)
-		goto nomem;
+		goto cleanup;
 
 	/* build binary patch */
 	rb = PyBytes_AsString(result);
@@ -130,13 +134,19 @@
 		lb = h->b2;
 	}
 
-nomem:
+cleanup:
 	if (_save)
 		PyEval_RestoreThread(_save);
-	free(al);
-	free(bl);
-	bdiff_freehunks(l.next);
-	return result ? result : PyErr_NoMemory();
+	if (al) {
+		free(al);
+	}
+	if (bl) {
+		free(bl);
+	}
+	if (l.next) {
+		bdiff_freehunks(l.next);
+	}
+	return result;
 }
 
 /*