I had to do something similar on my Tie::Array::Packed module:
static char * my_sv_unchop(pTHX_ SV *sv, STRLEN size) { STRLEN len; char *pv = SvPV(sv, len); IV off = SvOOK(sv) ? SvIVX(sv) : 0; if (!size) return pv; if (off >= size) { SvLEN_set(sv, SvLEN(sv) + size); SvCUR_set(sv, len + size); SvPV_set(sv, pv - size); if (off == size) SvFLAGS(sv) &= ~SVf_OOK; else SvIV_set(sv, off - size); } else if (len + size <= off + SvLEN(sv)) { if (off) { SvLEN_set(sv, SvLEN(sv) + off); SvFLAGS(sv) &= ~SVf_OOK; } SvCUR_set(sv, len + size); SvPV_set(sv, pv - off); Move(pv, pv + size - off, len, char); } else { SV *tmp = sv_2mortal(newSV(len + size)); STRLEN tmp_len; char *tmp_pv; SvPOK_on(tmp); tmp_pv = SvPV(tmp, tmp_len); Move(pv, tmp_pv + size, len, char); SvCUR_set(tmp, size + len); sv_setsv(sv, tmp); } return SvPVX(sv); }
this function inserts size bytes in front of the string efficiently and returns a pointer to the start of the new pv.

You would probably want to modify it so that more bytes than requested are reserved on the string to optimize consecutive insertions.

Note that sv_setsv is used to only copy the string contents once as it steals the SV string memory from the source SV when it is a mortal.


In reply to Re: XS Prepending space to an SVs PV by salva
in thread XS Prepending space to an SVs PV by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.