Arachnid / solidity-stringutils

Basic string utilities for Solidity
Apache License 2.0
1.14k stars 373 forks source link

strings.slice stored in structs when retrieved and converted into slice yields gibberish when console.logged #60

Open 0xJamesBong opened 1 year ago

0xJamesBong commented 1 year ago

I have a struct like this

struct Question {
        strings.slice question;
        strings.slice answer;
    }

And a mappingmapping(uint256 => QA) public questions; and a proposeQuestion function that looks like this

        public
        returns (bool done)
    {
        questions[questionId].question = _question.toSlice();
        questions[questionId].answer = _answer.toSlice();
        questionId++;
        return true;
    }

When I retrieve the question and the answer stored in the struct which is stored in a mapping, and console log it, using foundry

function testQuestion() public {

        string memory q = "What?";
        console.log(q, q.toSlice().toString());
        myContract.proposeQuestion(q, unicode"すみません");
        assertTrue(
            keccak256(abi.encodePacked(q)) ==
                keccak256(abi.encodePacked(q.toSlice().toString()))
        );
        (          
            strings.slice memory question,
            strings.slice memory answer
        ) = myContract.questions(0);
        console.log(question.toString());

The console prints out gibberish ,.��

However, if I just do this console.log(q, q.toSlice().toString()) they print out the same thing! What's going on here?

PS:

Also, when I tried this out, this test fails

 assertEq(
            keccak256(abi.encodePacked(q)),
            keccak256(abi.encodePacked(question.toString()))
        );

and yields this error


    Expected: 0xc649b6993c4fe2cdb223c885f0145101f4d5ef046eebceed76b6431c34626612
      Actual: 0xf8a49a8b34d42855db8ed1c016fa2fe0354abc43323b8d67be08e3837aae8b60

Test result: FAILED. 0 passed; 1 failed; finished in 5.19ms```