Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string memory to string calldata?

Wondering if its possible to convert between string memory and string calldata in order to use indexing of the form string[start : end] which only works string calldata. This function seems to works:

function splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {
        if (startPos > int(length(sourcestring))) return "";
        int start = startPos -1;
        int end = startPos + (numchars -1);
        string memory retval = string(source[uint(start) : uint(end)]);
        return retval;

    }

but if I change the parameter source to string memory, then I get an error on string memory retval = string(source([uint(start) : uint(end)]) because apparently the form sourcestring[start : end] to get a substring works on calldata strings not on memory strings, and there is no obvious way to convert a string memory to a string calldata.

Is there any means to do this?

like image 632
GGizmos Avatar asked Oct 24 '25 04:10

GGizmos


2 Answers

Calldata is read-only. You can decode calldata variables into memory but not the other way around.

Unfortunately array slicing is only implemented for calldata. For memory and storage it's a bit more complicated and has not been implemented yet (see issue #7423).

The workaround in your case is to copy the characters one by one, which is really what the compiler would do under the hood anyway since you're trying to return the slice from a public function (which would materialize the slice into an array).

like image 165
cameel Avatar answered Oct 27 '25 01:10

cameel


Probably not since calldata is for data supplied while making an external transaction. Very different purpose compared to storage.

like image 26
djd Avatar answered Oct 27 '25 01:10

djd