Submission 32916b15...

ChallengeString search
Submitterricmoo.firefly.eth
Submitted at2018-57-01
Gas used204815
pragma solidity 0.4.24;

contract IndexOf {
    function indexOf(string haystack, string needle) public pure returns(int) {
        assembly {
            let needleLength := mload(needle)
            if iszero(needleLength) {
                mstore(0x0, 0)
                return (0, 32)
            }

            let haystackLength := mload(haystack)
            if gt(needleLength, haystackLength) {
                mstore(0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                return(0, 32)
            }

            let haystackIndex := add(haystack, 32)
            let haystackEnd := add(add(haystackIndex, sub(haystackLength, needleLength)), 1)
            for { } lt(haystackIndex, haystackEnd) { } {
                let needleIndex := add(needle, 32)
                let needleEnd := add(needleIndex, needleLength)

                let found := 1
                let haystackSubIndex := haystackIndex
                let needleBlockLength := needleLength
                for { } lt(needleIndex, needleEnd) { } {
                    let haystackData := mload(haystackSubIndex)
                    let needleData :=  mload(needleIndex)
                    //let needleSubLength := needleBlockLength

                    let mask := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
                    if lt(needleBlockLength, 32) {
                        mstore(0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                        mstore8(sub(needleBlockLength, 1), 0xfe)
                        mask := add(mload(0), 1)
                    }
                    //mask := sub(mask, sub(exp(2, mul(8, sub(32, needleSubLength))), 1))
                    //mask := sub(mask

                    if and(xor(haystackData, needleData), mask) {
                        needleIndex := 0xffffffffffffff
                        found := 0
                    }
                    needleIndex := add(needleIndex, 32)
                    haystackSubIndex := add(haystackSubIndex, 32)
                    needleBlockLength := sub(needleBlockLength, 32)
                }

                if eq(found, 1) {
                    mstore(0x0, sub(haystackIndex, add(haystack, 32)))
                    return(0x0, 32)
                }

                haystackIndex := add(haystackIndex, 1)
            }

            mstore(0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
            return(0, 32)
        }
    }
}