Sub-Name-0.20-TRIAL
[p5sagit/Sub-Name.git] / Name.xs
diff --git a/Name.xs b/Name.xs
index 10a8cd2..9a4d493 100644 (file)
--- a/Name.xs
+++ b/Name.xs
@@ -40,8 +40,8 @@ subname(name, sub)
        const char *s, *end = NULL, *begin = NULL;
        MAGIC *mg;
        STRLEN namelen;
-       int utf8flag = SvUTF8(name);
        const char* nameptr = SvPV(name, namelen);
+       int utf8flag = SvUTF8(name);
        int seen_quote = 0, need_subst = 0;
     PPCODE:
        if (!SvROK(sub) && SvGMAGICAL(sub))
@@ -63,28 +63,29 @@ subname(name, sub)
                croak("Not a subroutine reference");
 
        for (s = nameptr; s <= nameptr + namelen; s++) {
-               if (*s == ':' && s[-1] == ':') {
+               if (s > nameptr && *s == ':' && s[-1] == ':') {
                        end = s - 1;
                        begin = ++s;
                        if (seen_quote)
-                               seen_quote++;
+                               need_subst++;
                }
-               else if (*s && s[-1] == '\'') {
+               else if (s > nameptr && *s != '\0' && s[-1] == '\'') {
                        end = s - 1;
                        begin = s;
-                       seen_quote++;
+                       if (seen_quote++)
+                               need_subst++;
                }
        }
        s--;
        if (end) {
                SV* tmp;
-               if (seen_quote > 1) {
-                       STRLEN length = end - nameptr + seen_quote;
+               if (need_subst) {
+                       STRLEN length = end - nameptr + seen_quote - (*end == '\'' ? 1 : 0);
                        char* left;
                        int i, j;
                        tmp = newSV(length);
                        left = SvPVX(tmp);
-                       for (i = 0, j = 0; j <= end - nameptr; ++i, ++j) {
+                       for (i = 0, j = 0; j < end - nameptr; ++i, ++j) {
                                if (nameptr[j] == '\'') {
                                        left[i] = ':';
                                        left[++i] = ':';
@@ -93,7 +94,7 @@ subname(name, sub)
                                        left[i] = nameptr[j];
                                }
                        }
-                       stash = gv_stashpvn(left, i - 2, GV_ADD | utf8flag);
+                       stash = gv_stashpvn(left, length, GV_ADD | utf8flag);
                        SvREFCNT_dec(tmp);
                }
                else