@@ -2215,36 +2215,29 @@ Perl_do_print(pTHX_ SV *sv, PerlIO *fp)
22152215 STRLEN len ;
22162216 /* Do this first to trigger any overloading. */
22172217 const U8 * tmps = (const U8 * ) SvPV_const (sv , len );
2218- U8 * tmpbuf = NULL ;
22192218
2219+ /* If 'tmps' doesn't need converting, this will remain NULL and
2220+ * Safefree(free_me) will do nothing; Otherwise it points to the newly
2221+ * allocated memory that tmps will also be changed to point to, so
2222+ * Safefree(free_me) will free it. This saves having to have extra
2223+ * logic. */
2224+ void * free_me = NULL ;
22202225 bool happy = TRUE;
22212226
22222227 if (PerlIO_isutf8 (fp )) { /* If the stream is utf8 ... */
22232228 if (!SvUTF8 (sv )) { /* Convert to utf8 if necessary */
2224- /* We don't modify the original scalar. */
2225- tmpbuf = bytes_to_utf8 (tmps , & len );
2226- tmps = tmpbuf ;
2229+ /* This doesn't modify the original scalar. */
2230+ tmps = bytes_to_utf8_free_me (tmps , & len , & free_me );
22272231 }
22282232 else if (ckWARN4_d (WARN_UTF8 , WARN_SURROGATE , WARN_NON_UNICODE , WARN_NONCHAR )) {
22292233 (void ) check_utf8_print (tmps , len );
22302234 }
22312235 } /* else stream isn't utf8 */
22322236 else if (DO_UTF8 (sv )) { /* But if is utf8 internally, attempt to
22332237 convert to bytes */
2234- STRLEN tmplen = len ;
2235- bool utf8 = TRUE;
2236- U8 * const result = bytes_from_utf8 (tmps , & tmplen , & utf8 );
2237- if (!utf8 ) {
2238-
2239- /* Here, succeeded in downgrading from utf8. Set up to below
2240- * output the converted value */
2241- tmpbuf = result ;
2242- tmps = tmpbuf ;
2243- len = tmplen ;
2244- }
2245- else { /* Non-utf8 output stream, but string only representable in
2246- utf8 */
2247- assert (result == tmps );
2238+ if (! utf8_to_bytes_new_pv (& tmps , & len , & free_me )) {
2239+ /* Non-utf8 output stream, but string only representable in
2240+ utf8 */
22482241 Perl_ck_warner_d (aTHX_ packWARN (WARN_UTF8 ),
22492242 "Wide character in %s" ,
22502243 PL_op ? OP_DESC (PL_op ) : "print"
@@ -2262,7 +2255,7 @@ Perl_do_print(pTHX_ SV *sv, PerlIO *fp)
22622255 * io the write failure can be delayed until the flush/close. --jhi */
22632256 if (len && (PerlIO_write (fp ,tmps ,len ) == 0 ))
22642257 happy = FALSE;
2265- Safefree (tmpbuf );
2258+ Safefree (free_me );
22662259 return happy ? !PerlIO_error (fp ) : FALSE;
22672260 }
22682261}
0 commit comments