As most as possible close equivalent of strtol(3) function (with base=0),
       used by postgres to parse parameter values.
    >>> strtol(0) == (0, '')
    True
    >>> strtol(1) == (1, '')
    True
    >>> strtol(9) == (9, '')
    True
    >>> strtol(' +0x400MB') == (1024, 'MB')
    True
    >>> strtol(' -070d') == (-56, 'd')
    True
    >>> strtol(' d ') == (None, 'd')
    True
    >>> strtol('9s', False) == (9, 's')
    True
    >>> strtol(' s ', False) == (1, 's')
    True

def strtol(value, strict=True):
    """As most as possible close equivalent of strtol(3) function (with base=0),
       used by postgres to parse parameter values.
    >>> strtol(0) == (0, '')
    True
    >>> strtol(1) == (1, '')
    True
    >>> strtol(9) == (9, '')
    True
    >>> strtol(' +0x400MB') == (1024, 'MB')
    True
    >>> strtol(' -070d') == (-56, 'd')
    True
    >>> strtol(' d ') == (None, 'd')
    True
    >>> strtol('9s', False) == (9, 's')
    True
    >>> strtol(' s ', False) == (1, 's')
    True
    """
    value = str(value).strip()
    ln = len(value)
    i = 0
    # skip sign:
    if i < ln and value[i] in ('-', '+'):
        i += 1

    # we always expect to get digit in the beginning
    if i < ln and value[i].isdigit():
        if value[i] == '0':
            i += 1
            if i < ln and value[i] in ('x', 'X'):  # '0' followed by 'x': HEX
                base = 16
                i += 1
            else:  # just starts with '0': OCT
                base = 8
        else:  # any other digit: DEC
            base = 10

        ret = None
        while i <= ln:
            try:  # try to find maximally long number
                i += 1  # by giving to `int` longer and longer strings
                ret = int(value[:i], base)
            except ValueError:  # until we will not get an exception or end of the string
                i -= 1
                break
        if ret is not None:  # yay! there is a number in the beginning of the string
            return ret, value[i:].strip()  # return the number and the "rest"

    return (None if strict else 1), value.strip()