peachpie icon indicating copy to clipboard operation
peachpie copied to clipboard

Unexpected results when working with binary strings

Open kripper opened this issue 2 years ago • 10 comments

This asserts fail when working with WebAssemblies:

<?
$ub = chr(220);
$s1 = str_repeat($ub, 4);
$s2 = $ub . $ub . $ub . $ub;
assert(base64_encode($s1) == "3Nzc3A==", 'str_repeat fails');
assert(base64_encode($s2) == "3Nzc3A==", 'chr() fails');

kripper avatar Oct 17 '21 22:10 kripper

base64_encode(chr(220)) also gives a wrong result.

kripper avatar Oct 17 '21 23:10 kripper

BTW, the test case can be easily placed inside PHPScripts/index.php following the instructions here: https://www.peachpie.io/2021/08/run-debug-php-browser.html

Then execute dotnet run inside BlazorApp\Client.

kripper avatar Oct 20 '21 00:10 kripper

Hi @jakubmisek, do you know if there is some configuration or workaround to support working with binary strings on PeachPie WebAssemblies?

kripper avatar Oct 25 '21 18:10 kripper

@kripper there is nothing special for webasm, just a thin wrapper at https://github.com/peachpiecompiler/peachpie-blazor . Strings are handled the same

jakubmisek avatar Oct 25 '21 20:10 jakubmisek

Right. I tested on peachpie (latest version) and both asserts fail too for a console app. I tried adding the (binary) cast, using mb_chr(220, 'ASCII'), but everything fails. Is there any way to create a binary string containig chr(220)?

kripper avatar Oct 25 '21 20:10 kripper

https://github.com/peachpiecompiler/peachpie/blob/9dec67e719f762c5c8c4c1a5200651471ef5096f/src/Peachpie.Library/Strings.cs#L57

chr(220) // == new byte[]{ 220 }

jakubmisek avatar Oct 25 '21 20:10 jakubmisek

It seems like chr() only returns binary strings when bytevalue < 240.

        public static PhpString chr(int bytevalue)
        {
            if (bytevalue < 0xf0)
            {
                return ((char)bytevalue).ToString();
            }
            else
            {
                return new PhpString(new byte[] { (byte)bytevalue });
            }
        }

kripper avatar Oct 25 '21 20:10 kripper

Can we add an option to make chr() compatbile with Zend's PHP? I believe most of the time we see chr() in the code is because the programmer wants to generate binary code.

kripper avatar Oct 25 '21 20:10 kripper

seems like a typo, should be string only for 32 <= bytevalue < 128

jakubmisek avatar Oct 25 '21 21:10 jakubmisek

Agree.

kripper avatar Oct 25 '21 21:10 kripper

Tested and working fine after https://github.com/peachpiecompiler/peachpie/pull/982

kripper avatar Mar 15 '23 19:03 kripper