shithub: libmujs

Download patch

ref: 9281c68b680507cb2dda3acab7b990521e2451b2
parent: 3ceaeb153d9c324bfe73209b6beb0e2768ee59cb
author: Tor Andersson <tor.andersson@artifex.com>
date: Mon Jan 5 12:32:09 EST 2015

Use offsetof instead of hardcoded short string length.

--- a/jsrun.c
+++ b/jsrun.c
@@ -103,9 +103,9 @@
 
 void js_pushstring(js_State *J, const char *v)
 {
-	int n = strlen(v);
+	unsigned int n = strlen(v);
 	CHECKSTACK(1);
-	if (n < 16) {
+	if (n <= offsetof(js_Value, type)) {
 		char *s = STACK[TOP].u.shrstr;
 		while (n--) *s++ = *v++;
 		*s = 0;
@@ -120,7 +120,7 @@
 void js_pushlstring(js_State *J, const char *v, unsigned int n)
 {
 	CHECKSTACK(1);
-	if (n < 16) {
+	if (n <= offsetof(js_Value, type)) {
 		char *s = STACK[TOP].u.shrstr;
 		while (n--) *s++ = *v++;
 		*s = 0;
--- a/jsvalue.h
+++ b/jsvalue.h
@@ -40,6 +40,13 @@
 	JS_CUSERDATA,
 };
 
+/*
+	Short strings abuse the js_Value struct. By putting the type tag in the
+	last byte, and using 0 as the tag for short strings, we can use the
+	entire js_Value as string storage by letting the type tag serve double
+	purpose as the string zero terminator.
+*/
+
 struct js_Value
 {
 	union {
@@ -50,8 +57,8 @@
 		js_String *memstr;
 		js_Object *object;
 	} u;
-	char pad[7];
-	char type;
+	char pad[7]; /* extra storage for shrstr */
+	char type; /* type tag and zero terminator for shrstr */
 };
 
 struct js_String