solidity – Solving TypeError: Operator >= Not Compatible with Types bytes1 and int_const 37

soliditytruffle-compile

pragma solidity ^0.5.16;

library EmailRegex {
  struct State {
    bool accepts;
    function (byte) internal pure returns (uint) func;
  }

  function state(uint id) internal pure returns (State memory) {
    if (id == 1) {
      return State(false, s1);
    }
    if (id == 2) {
      return State(false, s2);
    }
}
function matches(string memory input) public pure returns (bool) {
    uint cur = 1;

    for (uint i = 0; i < bytes(input).length; i++) {
      bytes1 c = bytes(input)[i];

      cur = state(cur).func(c);
      if (cur == 0) {
        return false;
      }
    }

    return state(cur).accepts;
  }

  function s1(byte c) internal pure returns (uint) {
    if (c >= 37 && c <= 37 || c >= 43 && c <= 43 || c >= 45 && c <= 45 || c >= 46 && c <= 46 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 95 && c <= 95 || c >= 97 && c <= 122) {
      return 2;
    }

    return 0;
  }

  function s2(byte c)  internal pure  returns (uint) {
    if (c >= 37 && c <= 37 || c >= 43 && c <= 43 || c >= 45 && c <= 45 || c >= 46 && c <= 46 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 95 && c <= 95 || c >= 97 && c <= 122) {
      return 3;
    }
    if (c >= 64 && c <= 64) {
      return 4;
    }

    return 0;
  }
}

Trying to have a test run from source code from GitHub and faced this error. At first, it came with pragma solidity ^0.4.26 version then I changed it to pragma solidity ^0.5.16.

I am not sure of how can I replace the operator error.
Here is the error log

https://github.com/lionel1702/log/blob/master/emailRegexLog

Best Answer

There's a few solutions for this:

  • If c needs to be a byte, you can use hexadecimal notation, e.g. c >= 0x25 && c <= 0x25 (or c == 0x25).
  • Otherwise, you can simply cast the type from byte to uint8 (which is essentially the same type, since both consist of 8 bits):
    uint8 c = uint8(bytes(input)[i]);
    
    // ...
    function s1(uint8 c) internal pure returns (uint) { ... }
    

Note that c == 37 is the same as c >= 37 && c <= 37, so you can simplify your functions like this:

function s1(uint8 c) internal pure returns (uint) {
  if (c == 37 || c == 43 || c == 45 || c == 46 || ...) {
    return 2;
  }

  return 0;
}
Related Topic