Lichen

Change of lib/__builtins__/int.py

932:c07b0dd14f85
lib/__builtins__/int.py
     1.1 --- a/lib/__builtins__/int.py	Sun Jun 27 22:39:01 2021 +0200
     1.2 +++ b/lib/__builtins__/int.py	Mon Jun 28 00:13:11 2021 +0200
     1.3 @@ -19,6 +19,7 @@
     1.4  this program.  If not, see <http://www.gnu.org/licenses/>.
     1.5  """
     1.6  
     1.7 +from __builtins__.str import basestring
     1.8  from __builtins__.unicode import utf8string
     1.9  from native import get_maxint, get_minint, is_int, \
    1.10                     int_add, int_and, int_div, int_eq, int_ge, int_gt, \
    1.11 @@ -26,15 +27,47 @@
    1.12                     int_neg, int_not, int_or, int_pow, int_rshift, int_str, \
    1.13                     int_sub, int_xor
    1.14  
    1.15 +def new_int(number_or_string, base=10):
    1.16 +
    1.17 +    "Initialise the integer with the given 'number_or_string'."
    1.18 +
    1.19 +    if is_int(number_or_string):
    1.20 +        return number_or_string
    1.21 +    elif isinstance(number_or_string, basestring):
    1.22 +        return str_to_int(number_or_string, base)
    1.23 +    else:
    1.24 +        raise TypeError
    1.25 +
    1.26 +def str_to_int(value, base=10):
    1.27 +
    1.28 +    "Decode the string 'value' using the given 'base'."
    1.29 +
    1.30 +    # NOTE: Add support for lower and upper in the string classes.
    1.31 +
    1.32 +    #value = value.lower()
    1.33 +    len_value = len(value)
    1.34 +    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    1.35 +
    1.36 +    result = 0
    1.37 +    i = 0
    1.38 +
    1.39 +    while i < len_value:
    1.40 +        c = value[i]
    1.41 +        d = digits.index(c)
    1.42 +        result = result * base + d
    1.43 +        i += 1
    1.44 +
    1.45 +    return result
    1.46 +
    1.47  class int:
    1.48  
    1.49      "An integer abstraction."
    1.50  
    1.51 -    def __init__(self, number_or_string=None):
    1.52 +    def __init__(self, number_or_string=None, base=10):
    1.53  
    1.54          "Initialise the integer with the given 'number_or_string'."
    1.55  
    1.56 -        # Implemented in the translator.
    1.57 +        # Implemented by new_int above, invoked specially by the translator.
    1.58  
    1.59          pass
    1.60