CashScript / cashscript

⚖️ Easily write and interact with Bitcoin Cash smart contracts
https://cashscript.org
MIT License
115 stars 80 forks source link

[enhancement] add C style casts #155

Open A60AB5450353F40E opened 1 year ago

A60AB5450353F40E commented 1 year ago

Currently some casts will actually call conversion like int() resulting in compiled bytecode using OP_BIN2NUM.

In some cases, when the user knows that the hex will be a valid script number this will be terribly wasteful.

Consider this:

int a=1;
bytes1 b=0x01;
require((bytes) a == b);

it would compile to OP_1 OP_1 OP_EQUALVERIFY

while

int a=1;
bytes1 b=0x01;
require(a == (int) b);

would compile to OP_1 OP_1 OP_NUMEQUALVERIFY.

What if b is not a valid int encoding? Then still compile the same but compiled Script would fail due to OP_NUMEQUALVERIFY erroring.

rkalis commented 11 months ago

I agree that there should probably be a way to "just" typecast without adding any opcodes, but I'm not sure if I like having two separate "casting" syntaxes. The only cast where this applies is casting to int (when casting int to e.g. bytes4 you can already do bytes1(bytes(20)) to forego the OP_NUM2BIN (if you wanted to). So we may want to allow something similar for int casting. This is not a big priority right now, but I think it also shouldn't be a lot of work, so I'll try to think of some syntax that makes sense.