Skip to content

Commit 8c573be

Browse files
atoomictonycoz
authored andcommitted
add a small buffer to gv_stash_name
1 parent f8ac814 commit 8c573be

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

gv.c

+14-5
Original file line numberDiff line numberDiff line change
@@ -1595,10 +1595,11 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
15951595
STRLEN *len, const char *nambeg, STRLEN full_len,
15961596
const U32 is_utf8, const I32 add)
15971597
{
1598-
char *tmpbuf = NULL;
1598+
char *tmpfullbuf = NULL; /* only malloc one big chunk of memory when the smallbuff is not large enough */
15991599
const char *name_cursor;
16001600
const char *const name_end = nambeg + full_len;
16011601
const char *const name_em1 = name_end - 1;
1602+
char smallbuf[64]; /* small buffer to avoid a malloc when possible */
16021603

16031604
PERL_ARGS_ASSERT_PARSE_GV_STASH_NAME;
16041605

@@ -1629,8 +1630,16 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
16291630
*len += 2;
16301631
}
16311632
else { /* using ' for package separator */
1632-
if (tmpbuf == NULL) /* only malloc&free once, a little more than needed */
1633-
Newx(tmpbuf, full_len+2, char);
1633+
/* use our pre-allocated buffer when possible to save a malloc */
1634+
char *tmpbuf;
1635+
if ( *len+2 <= sizeof smallbuf)
1636+
tmpbuf = smallbuf;
1637+
else {
1638+
/* only malloc once if needed */
1639+
if (tmpfullbuf == NULL) /* only malloc&free once, a little more than needed */
1640+
Newx(tmpfullbuf, full_len+2, char);
1641+
tmpbuf = tmpfullbuf;
1642+
}
16341643
Copy(*name, tmpbuf, *len, char);
16351644
tmpbuf[(*len)++] = ':';
16361645
tmpbuf[(*len)++] = ':';
@@ -1639,7 +1648,7 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
16391648
gvp = (GV**)hv_fetch(*stash, key, is_utf8 ? -((I32)*len) : (I32)*len, add);
16401649
*gv = gvp ? *gvp : NULL;
16411650
if (!*gv || *gv == (const GV *)&PL_sv_undef) {
1642-
Safefree(tmpbuf);
1651+
Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
16431652
return FALSE;
16441653
}
16451654
/* here we know that *gv && *gv != &PL_sv_undef */
@@ -1681,7 +1690,7 @@ S_parse_gv_stash_name(pTHX_ HV **stash, GV **gv, const char **name,
16811690
MUTABLE_HV(SvREFCNT_inc_simple(PL_defstash));
16821691
}
16831692
}
1684-
Safefree(tmpbuf);
1693+
Safefree(tmpfullbuf); /* free our tmpfullbuf if it was used */
16851694
return TRUE;
16861695
}
16871696
}

0 commit comments

Comments
 (0)